Is there something I can call from a POJO to see if the code is currently in an App Server or outside of an App Server?
Something like this (In rough PseudoCode):
System.getRunningEnvironment().equals(Environment.Glassfish)
or
System.getRunningEnvironment().equals(Environment.ApplicationServer)
or
System.getRunningEnvironment().equals(Environment.JavaSE)
If you can change AppServer initialization scripts (take a look at this link):
Add -DRunningInAppServer=true at your AppServer initialization script.
Add -DRunningInAppServer=false at your application initialization script.
Then use this method:
public boolean isRunningInAppServer() {
if ("true".equals(System.getProperty("RunningAppServer"))) {
return true;
}
return false;
}
I don't believe you can do this trivially. And would you want to distinguish between an app server, a web container etc.?
What is the reason for determining this ? To allow your POJOs to behave differently in different environments ? If so then I think this points to an object/component structure that is not quite correct, or at least where the object responsibilities are not clearly defined.
The easiest way is, to check the existence of Java EE/App Server specific classes.
I never used an application server, but maybe you'll be able to achieve this with System.getProperties() / System.getProperty(...)
Consider checking for the current SecurityManager, if your application server uses one.
I don't think there's any way to determine this directly. Yes, as SourceRebel says you could set a system property. Personally I'd avoid doing this, though, as you then have some hidden coupling going on: your function is dependent on a system property that must be set correctly for it to work, but there is nothing clearly defined in the interface to reflect this. I think you'd be far better off to just pass in a parameter that says which it is, and let the caller be responsible to pass in the correct parameter. Then the existence of this parameter can be clearly seen in the function signature, and anyone using it will have a strong clue that they need to set it correctly. Having the caller set it correctly should be trivial, as presumably at some point in the call chain you are either calling from a desktop app or from a web page, and that caller knows which it is.
Some applications server set system properties, JBoss for example:
http://community.jboss.org/wiki/JBossProperties
Related
I am working on workflow management system.
Have one separate java class which contains logic method. One of this is:
public static in get_nxt_stg(int current_stg,int action)
{
}
and define static variable cur_stg and nxt_stg. used in servlet. call this method.
When multiple users log in and do some action these variables get not proper value. It seems like it is shared between all user requests.
What is best way to use variable in servlet, which is remain specific for that request?
You should not use static in such a way. If you need to share state, consider using the singleton pattern; but try to avoid static. Unwise use of "static" can turn into a nightmare (for example regarding unit testing).
In addition: it seems that you are a beginner with the Java language. But creating servlets is definitely a "advanced" java topic. I really recommend you to start learning more about Java as preparation for working on servlets. Otherwise the user of your server might have many unpleasant experiences ...
What you are doing is wrong. You should use Servlets only for the purpose of reading request parameters and sending responses. What you are trying to do, should be implemented in the Business layer of your application and if you have it implemented with EJBs, then your problem can easily be solved with an Stateful EJB.
I am using a Java library, with two classes Foo and FooConfig; I am unable to change the library code, but can read it. Here are the relevant functions of a Foo:
public class Foo
{
/** Install a configuration on this Foo */
void configure(FooConfig config);
/** Uninstall the current configuration */
void unconfigure();
}
The library creates Foos at times I can't control, and installs configurations shortly after creation. A Foo can only have on configuration at a time. I would like to use MyFooConfig, inherited from FooConfig, instead. Is there any way to intercept the configure call, or the FooConfig constructor, or anything like that to use my class instead?
My current solution is to get a reference to the Foo object shortly after its creation and configuration, uninstall the current configuration,and then install a MyFooConfig instead. This could work, but it causes several different problems (both with being a difficult solution to implement and with some inelegancies which can't be hidden from the user). Is there a better way, preferably using features of Java to intercept the constructor call to FooConfig, or the configure method, or something similar? The closest thing to an alternate solution I've found is to try to use a different ClassLoader to replace FooConfig with my own class behind the scenes, but I don't actually have access to the object that creates the FooConfigs so I don't think that's possible. Other things that looked promising but ultimately didn't pan out are proxy objects (I can't make the Foos be proxy objects), seeing if I could somehow get notified when a FooConfig was created without actually intercepting the constructor (so I could find its Foo and reconfigure it in a better way than I`m currently doing), and changing the library code itself (which, for various reasons, turns out to not be possible).
I don't know much about aspect-oriented programming, but it seems like it could help. Unfortunately, all the AOP Java tools seem to require special compilers, and I don't want to change the build process.
I have a Java class which have some confidential information which I don't want to provide to any unauthorized class.
I want to access this class in some packages (classes from this packages are going to utilize confidential information), So that my secure class should be accessible in these packages.
Is there any way where I can check if caller of method is a authorized class from authorized package or not?
I know public/private/default all things (so please don't ask me to use it), but those are not useful here, because I want a class to be accessible in some packages(not one/same).
I feel that you are going in the wrong direction. It might be a design problem.
The security requirement is your business logic. You should implement your security policy somehow, not rely on the java language level visibility modifier or caller package names. since if you give your jar to someone, he can anyway get access to your "confidencial" class.
And moreover, a class is a type, something abstract. it should not contain "data". well sure sometimes conf information was written as static variable etc. However if some data is sensitive, it should not be written in class. It could be stored in database or encrypted file and so on. Once a request to the sensitive information comes, you check your implemented security policy, if it is allowed to access those data.
just my 2cents
The visibility modifiers in Java are not a security tool, but an OO design tool. Whatever you might do, if someone uses your class, it can access any private members of any class using reflection.
If your objects contain confidential information, leave these objects in your secure server.
You can create an Exception (no need for it to be thrown) and use the getStackTrace() to analize the call stack. I always found it ugly, though.
That said, anything that you put in a client machine is vulnerable to that machine; if you have something really confidential protect it in your server; make it available only as a service.
You can use the proxy pattern, implemented by the Proxy class in Java - it is designed exactly for your purpose.
Here is a how-to.
EDIT : AFAIK, you cannot use the regular Proxy mechanism for static methods, as the proxy and the proxied class must implement a common interface. However, there are more advanced tools, which may help you like javassist. Unfortunately I'm not familiar with it myself.
You might be able to leverage aspectj here. It's theoretically possible to intercept the call to a given classes' methods based on the current flow scope, and have the aspect throw an exception or something. I'm no aspectj expert though, but the "cflow" pointcut qualifier would be your most likely bet. Maybe something like this
! cflow(call(* com.mycom.AllowedClient.*))
I haven't tested this kind of pointcut, but i believe it would work.
You'd probably want compile time weaving in this case though (as opposed to load time weaving).
As a side note, i agree with some of the others that i think this is the wrong approach to take. You protect data. You protected function access based on logged in user permissions. You typically don't protect function calls from other classes.
Guideline 4-2 / EXTEND-2: Limit the accessibility of packages
Containers may hide implementation code by adding to the package.access security property. This property prevents untrusted classes from other class loaders linking and using reflection on the specified package hierarchy. Care must be taken to ensure that packages cannot be accessed by untrusted contexts before this property has been set.
This example code demonstrates how to append to the package.access security property. Note that it is not thread-safe. This code should generally only appear once in a system.
private static final String PACKAGE_ACCESS_KEY = "package.access";
static {
String packageAccess = Security.getProperty(PACKAGE_ACCESS_KEY);
Security.setProperty(PACKAGE_ACCESS_KEY,
(packageAccess == null || packageAccess.trim().isEmpty()
? "" : packageAccess + ",")
+ "xx.example.product.implementation.");
}
I wrote program in java which is using some kind of win lib and now I want to write one more program to simulate other one. I mean, it should be going like that :
first program asking lib for some simple data ( just true false)
and other program in this same time by using function from this lib setting some variable in this lib which might be return to first program...
both programs are independent first (lets say "getter") in java and second ("setter") in c++... I have already set all variables in lib as static but it didn't solved problem.
Is this kind of solution even possible? or I have to use maybe some kind of socket or else
thanks for replay
I've been working with this kind of stuff (Java + dll + another programs) and I can tell that the libraries executed from another program and Java doesn't share the static variables, so I think you won't be able to do it that way.
The example that I have uses a window, whose size is 0, to exchange messages between the two programs (Java and VB 6.0), the first call between the two programs share the window handler, but I think this isn't the best way to do it, and, in addition, it has some limitations.
I expose the ways I think that could match your problem:
Shared file: pretty easy, just must take care with the encoding.
Memory area: You can use in the dll a memory area for data exchange, this is a truly "static" context
Socket: Maybe is the most flexible since it will work with any program/system.
The last one would be the one that I'll use if I must implement something like that, but that depends on you.
I have a simple problem: I want to configure an object differently based on whether the object is instantiated within a servlet container, or whether it is instantiated in a stand alone app.
The object is a database connection, and I care about setting query timeouts.
The first solution that I can come up with is:
if (insideServletContainer(this.getClass().getClassLoader()) {
/// do some servlet specific config
}
else {
/// do some standalone config
}
The question is, of course, can I write a reliable method of telling whether the class was loaded within a servlet container. It feels like a hack at best.
The second option is to assume that the default case is a stand alone instantiation, set defaults based on stand-alone configuration, and override them within the servlet context.
So, to sum up my question is: Do you know of a good/reliable mechanism if the class was loaded from within a servlet container? If not, I will have to take the second route.
Nick
This seems like a really bad idea. Instead, why don't you allow the class to take parameters, then let the container or app configure it appropriately?
Setting aside whether or not this is a good idea, I'd suggest looking up java:comp/env, which is only going to be available in an EE server:
try {
new InitialContext().lookup("java:comp/env");
/// do some servlet specific config
} catch (NamingException ex) {
/// do some standalone config
}
An alternate way to do this sort of thing is to have the configuration injected into this class by some sort of bootstrap loader.
In a standalone version, this would be done by the main() method (or something called from it).
In a webapp version, this would be done by a listener or filter invoked configured within the web.xml.
Dependency injection is useful here as it removes the need for your application to check these sorts of things; instead the application is given what it needs.
I would recommend Dependency Injection like #matt b.
As a second option, if it is only the simple case you described and you don't want to add or learn a DI framework to support this feature. You can accomplish the same thing as your current code by using a properties file to load different value based on the environment. You can simply use a different file for each environment and supply a VM arg to indicate which environment you are running.
db_prop.dev
db_prop.stalone
dp_prop.int
db_prop.prod
Then you can load by resource
"db_prop." + System.getProperty("runtime.env")