I'm developing GWT application which has many different forms. Visibility of these forms depends on type of authorized user. In other words, I want to do the following:
String type = rpc.getUserType(); // ask from server only ONCE
if(type.equals("advancedUser"))
{
ContentPanel advPanel= new ContentPanel();
add(advPanel);
}
if(type.equals("admin"))
{
ContentPanel adminPanel= new ContentPanel();
add(adminPanel);
}
My question is the following:
Is getting user type from server only once and using this variable everywhere safe? I mean is there any possibility to change this variable (if it stored on client side)?
My friend told me that GWT prepares html on server side, so I can safely store type in one variable and use it - nobody can acces it.
But i think, that i have to make rpc call before each construction like if(userType=blah-blah-blah) add(something) because I think that GWT translates my Java code to Javascript which runs on client side and all variables can be modified with programms like ArtMoney.
My question is the following: Is getting user type from server only once and using this variable everywhere safe? I mean is there any possibility to change this variable (if it stored on client side)?
Yes that is the most possible and Robust solution. More over I would like to suggest, make it static
public static String USER_TYPE = rpc.getUserType();
That variable should initialize with a value in very first of onModuleLoad and should be in to whole application.
But i think, that i have to make rpc call before each construction like if(userType=blah-blah-blah) add(something)
No that raises performance issues and unnecessary server calls through the wire.
because I think that GWT translates my Java code to Javascript which runs on client side and all variables can be modified with programms like ArtMoney.
GWT secure enough and compile your module with the option Obfuscated, which makes your code not human readable in browser.
That Obfuscation alone protect from all vulnerable things, there are some other steps also needs to be taken to sleep happy :)
I'm suggesting to go through the GWT security documentation.
Besides all,
While saving or processing data on serverside that check you done on client side needs to be done strictly, So that you cn avoid such situation.
On server side
if(clientsideUserType.equals(serverSideUserType)) //
{
// Then only insert/process data
}
Related
I'm making a system for an app, witch have for objective to allow the user to create custom script to interact with the program by handleing events and reacting to them by calling functions. The main program is wrote in java, but If want to allow the script to be wrote in JavaScript. What is the best way to do that ?
I've tryed to use the sockets to transfer data and events, but I thinks it's a bit overkill, because the app and the scripts are on the same machine. Does it exist a better way to do that?
If I understand correctly, what you want to do is called Remote Procedure Call and it doesn't help much that all your code (java and js) runs on the same computer. But you can probably at least get away without authentication or security.
There are a bunch of libraries that may save you some trouble. You may want to take a look at those options:
https://en.wikipedia.org/wiki/Remote_procedure_call#General
I only got the occasion of using one: json-rpc, which isn't necessarily the best option, but it is the only one I can give you more details about.
The specification of the protocol is available here https://www.jsonrpc.org/specification and there should be Java and Javascript libraries to ease the implementation.
For example:
Java - https://github.com/briandilley/jsonrpc4j
Javascript - https://github.com/jershell/simple-jsonrpc-js
Calling this Java hello method:
public String hello(#JsonRpcParam(value="message") String message) {
return message;
}
From your client, a call to hello would look like this:
var jrpc = simple_jsonrpc.connect_xhr('localhost:8080');
jrpc.call('hello', {message: 'hello world!'}).then(res => console.log(res));
Of course there's additional configuration, at least on sever (java) side to make this work.
i am working on a chat program.
[JAVA] [Without RMI, just Sockets] [Command example: 'sentToMike', 'Disconnect', 'Login', etc]
How do i send a "command" Object through Sockets to be excecuted on the server directly?
I want to send all kind of messages(Strings, Audio, Video), and all kind of Command objects to many clients, any of them. I know there exist ObjectInput/Output objects and all of that. My problem is trying to get a polymorphic solution.
For example i want to create a IMessage interface with a method signature "execute()". Then i would create a AudioMessage, TextMessage, etc that implements the IMessage. The problem is that at some point i need to share the server code with the client and viceversa in order Server and client know all the objects involved in every excecute method. And worst of all is that if i send an IMessage, the server would't know what specific type the message is, so i dont know to what kind cast the Object. The same would happen when i send the Command back to the client.
I can work a solution with simple text strings "commands" and a big and ugly switch in the server(and in the client by the way), but i believe that is not elegant, i would need to create a wrapper class with the string command plus the object of the kind i want to send plus the string with the type of object been sent(Message[String type; String command; IMessage->AudioMessage ]), this wont be polymorphic since i will need to use the switch to ask the type of the object and then cast it to AudioMessage for example. Furthermore i would need to share a lot of code between server and client and i dont know if that would be ok.
Any advice will be very very welcome, maybe i need a design pattern, an architecture pattern, i have no clue.
There are security reason to not allow just any code to run on server!
But if you are willing to expose your server (and client) to unknown code, then you need to also serve classes bytecode, and have classloaders to enable instanciating classes' types you expect the other end to accept. Your protocol would have to send the full classname and locations (if not inlining the bytecode) of the alien class (and all its dependencies not found in parent classloader), for the purpose of hoping to call any method of such object.
(FYI, that just reinventing RMI).
If you don't have to call anything on this object (it's not your case, I know, but I musy say it), then it is passive and there is really no point in transporting it as an object instance.
I've written a Java Applet and run it from my website.
In the long-term I plan to charge money per use of this applet.
The question is, is it possible to prevent users of downloading my code (i.e. my jar file) and then running it from their home, without paying?
(In this I don't mean decompile - I use obfuscator. I mean someone can use it easily without even decompiling it or understand it's code...)
I thought about using a changing password which the server sends to the applet using the HTML, but I thought - maybe someone knows a standard way of achieving my goal instead of reinventing the wheel??
Thanks..
There are several ways you can do this.
You can put code like this at the beginning of the applet's init method, assuming it creates some components:
if (!getDocumentBase().getHost().equals("yourhost.com")) {
JOptionPane.showMessageDialog(this, "You can't download it");
return;
}
Of course, you have to change yourhost.com to your actual website.
Pros:
Easy to implement, no server-side code
Cons:
Can be decompiled and the test can be removed
Someone could trick their computer into thinking it is "yourhost.com"
You can put all of your code on the server. For this, I will assume that your applet computes the cube of an integer.
Then the code looks like this for your applet:
public class CubingApplet extends JApplet {
private JTextField intField = new JTextField(3);
private JLabel output = new JLabel();
public void init() {
setLayout(new GridLayout(2, 2));
add(new JLabel("Enter an integer: "));
add(intField);
add(new JLabel("The cube of that is: ");
add(output);
intField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
output.setText("" + getCube());
}
};
}
private int getCube() {
try {
int n = Integer.parseInt(intField.getText());
InputStream response = new URL("http://www.yourhost.com/dosomething.php?n=" + n).openStream();
String sResponse = new BufferedReader(new InputStreamReader(response)).readLine();
return Integer.parseInt(sResponse);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
I must stop writing this right now, but I will add server-side code at the earliest opportunity.
By the way, even if you obfuscate, and it can't be decompiled, it is possible to recognize what these kinds of protection schemes look like, and remove them. So any protection scheme you devise can be short-circuited, because no obfuscation is bulletproof.
If the user's computer does all of the work of the applet, then it is impossible to prevent them from downloading a copy of the code. The browser has to download the code in order to run it; all the user needs to do is tell the browser to save the file or to use another program that will. The only way to prevent the user from being able to use the applet offline is with DRM. Perhaps you can include a check to your servers to ensure that the usage is valid; while the program is free the usage would always be valid but later you could verify it online. This is vulnerable to decompilation and modification to remove the DRM. Another option is to do some of the computation on your server, using code that is never exposed, but this of course has the downside of requiring you to maintain servers to do the calculations, which can be expensive.
In short no. Anyone can look at the webpages source code, find where the applet is stored and directly download it. If your product is not limited to an applet then it would probably be better to have it as an executable and sell that.
If you really need for it to be an applet that is payed for every time without being downloadable you could run all the actual processing on a separate server, construct what the screen would look like on the server and then send that image to the client (whos is using the applet). You would then display that image on the applet. Bear in mind that if your program would accept user input the applet would have to send that input to the server to be processed to.
The best way to do this would be to have a program on the serverside that provides data that is necessary for the app to do anything useful. They are only allowed to connect the applet to this if they have purchased an account (they have to log in inside the applet).
Since this is enforced serverside, they cannot bypass the restriction.
This obviates the problem of them downloading and decompiling it, because they still have to have an account to make any use of the applet.
The downside is that will probably require some rewriting of the applet and the creation of an entirely new program for the server.
If you really wish to protect your source code, you can make use of J2EE and make servlets that run on your webserver. The great thing about this is that all the work is done server-sided, similar to using PHP. This means that the end user can only see the output of the program and can not access the program files themselves.
A great article to read on the subject of J2EE servlets can be found here:
Java Servlet
Here is a quote from that page, I think it is exactly what you are looking for:
The servlet is a Java programming language class used to extend the capabilities of a server. Although servlets can respond to any types of requests, they are commonly used to extend the applications hosted by web servers, so they can be thought of as Java Applets that run on servers instead of in web browsers.
If you will implement a login page before the user will be able to use the applet, then you will not need to prevent them from downloading it. Anyone who wants to use must register (buy) from you a username/password.
Additionally you have already using obfuscator to prevent decompiling, which means that it will not be that easy to modify the applet to bypass login.
I am java and php programmer.
In java i can use static class/method so that anyone can use the same one time created class during run-time.
But for php how to do it since it is script based and only run while we refreshing the page?
My main objective is, I want to use syncronized class/method so that it wont clash while executing the PHP...
Need your help to give input.
Thanks
Update:
I am doing portal like multi level marketing(mlm)
Once register a member, we should pay bonus to the uplines
I don't want immidiately calculate the bonus because it is risky and could take some time to finish, so is is better just to register the member and show successfull.
My idea is, after registration, just invoke another class to run bonus with syncronized method so that the bonus calculation will not disturb by another registration.
Given that a php scripts runs from new every sinlge time a "static" class would not be very different from an ordinary class.
If you want to store some sort of state or preserve some data between runs of a php program then there are a number of options.
SESSION variables can be used to store data between requests from a single users as long as he keeps the session open.
COOKIES can be used to store data which persists between sessions as long as the user is using the same browser, on hte same machine and hasnt emptied the cookie jar.
memchached and similar packages can be used to store data and make it available to any php program on the server.
Databases are the most scalable solution as they will persist data between sessions, and between servers. There is some overhead involved is establishing connections and retrieving the data compared with the other solutions.
PHP is shared-nothing. Everything just lives for the Request. If you want to share information between Requests, you have to implement some additional technology layer that can do so. Or look into process control, shared memory segments and semaphores. The latter three are uncommon usage in PHP though. And all of the above will still be asynchronous.
To my knowledge, there is no way to update class Foo in one Request and have it change state immediately in a concurrent Request with PHP.
So here's my project:
I am building a central interface/dashboard to present the test data for several test types of multiple product versions. We're using TestNG on our massive product, and while not enough tests are being written, that's a discussion for another topic. Here's what the directory structure looks like:
Filesystem/productVersion+testType/uniqueDateAndBuildID/testng-results.xml
That results.xml file contains tags with child test tags, which correspond to a filesystem directory and then xml files containing actual test case results (pass, fail, etc)
The XML parsing and filesystem traversal is all well and good/reliable.
Flow of control:
Client accesses main page --> server opens properties file --> server checks for web server property (either Websphere or Tomcat, if I'm working locally) --> server sets bunch of constants based on that. Constants include: root filesystem directory, filesystem separator (translation), "like types (basically same tests on different platforms)", and a base URL to append onto. --> server then reads properties file some more and does all of its XML processing. Results are cached in memory as well as to the filesystem using ObjectOutputStream. --> A big list of results is sent back to the client to do the UI processing/display.
Here's where I run into a problem: I can't access those Global variables (contained/set in a Globals class...bad I know :-/ ) back on the client, even though they're in the shared folder. If you're wondering why I can't just load the properties again, it's because the client is GWT-ified Javascript which doesn't include File(). So my next thought, having done a little bit of upper level Java reading was to maybe use a Globals singleton object and pass that back too..but it seems like that's just as bad if not impossible. Suggestions here would be great.
This whole thing is pretty tightly coupled, something my previous Java education hadn't really gotten into yet. And since this is just an internal portal for devs to check, there doesn't seem to be much of a point in actually testing my code. As long as it displays correctly, logs properly, and handles errors gracefully, right? All in all it's <15 classes, so it's not really a big big deal I guess. Should I refactor to clean it all up and make it "better Java", comment everything to clearly delineate flow of control, or not worry too much about it because it's small? I know in the future to think more about things before I design them, but I really didn't know a large amount of the higher Java principles I've been exposed to since starting.
edit after doing a bit of thinking, came up with a possible workaround. What about, instead of passing back only a list of results, I passed back some other custom list implementation that included a globals 'header' object? I could preserve state.
A simple solution would be the Dictionary class:
Provides dynamic string lookup of
key/value string pairs defined in a
module's host HTML page. Each unique
instance of Dictionary is bound to a
named JavaScript object that resides
in the global namespace of the host
page's window object. The bound
JavaScript object is used directly as
an associative array.
You just need to add some dynamic content to your host HTML page - make the server print the values read from the properties file in the form of a JavaScript object:
var GlobalProperties = {
property1: "value1",
property2: "value2"
};
Then, use Dictionary in your code to read those values:
Dictionary globalProperties = Dictionary.getDictionary("GlobalProperties");
String property1 = globalProperties.get("property1");
PS: If you are looking for good ideas/advices on how to make your code less coupled -> more testable, I'd recommend Misko Hevery's blog. He's got many interesting posts, like why singletons are usually bad (global state, not the pattern itself). But most importantly - it has the awesome guide to writing testable code (some guidelines used internally in Google).
You could pass those Global variables using a simple object with a HashMap thought a GWT-RPC call or just include this Hashmap with the result you already retrieve in the first place (along the "big list of results [that] is sent back to the client to do the UI processing/display.")
You can't access serverside singletons from the compiled javascript.
You have two options basically. You can make a Serializable class in the client code, that represents the global variables, or pass your global variables object, but this is a rather inefficient solution.
The simplest is to use a HashMap<String, String> in a serializable object, which you can retrieve with an RPC call:
public class GwtGlobalVariables implements Serializable {
private HashMap<String, String> map = new HashMap<String, String>();
public void put(// a delegate put method of choice
public void setMap() // a getter / setter for the map if you need it
}
Ensure the class is within a GWT module's source folders, i.e. in the same place as your entry point maybe.
Fill the map out with the values needed, pass it through rpc and you have it in your client side code.