Simultaneous access http filter [closed] - multithreading

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I implemented a Http filter using Filter interface and it works fine in localhost.
The problem is that in a testing environment when two users want to access to the application this filter does not work like always. It mixes the data between two users. I know it because I have lots of logs reporting me the steps every moment. I don't know if there is any problem with the simultaneous access.

Like servlets, filters are application scoped. There's only one instance of a filter class being created during application startup and the very same instance is being reused across all HTTP requests throughout the application's lifetime. Your problem symptoms indicate that you're for some reason assigning request or session scoped variables as an instance variable of the filter instance, such as request parameters or session attributes, or perhaps even the whole request or session object itself.
For example,
public class MyFilter implements Filter {
private String someParam;
public void doFilter(... ...) {
someParam = request.getParameter("someParam");
// ...
}
}
This is not threadsafe! You should be declaring them in the method local scope:
public class MyFilter implements Filter {
public void doFilter(... ...) {
String someParam = request.getParameter("someParam");
// ...
}
}
See also:
How do servlets work? Instantiation, sessions, shared variables and multithreading

Related

What is the use of #DeclareRoles in JakartaEE 8+ security?

In the past I always implemented authorization with some very proprietary code having an #ApplicationScoped bean with methods like isUserInAnyOfTheseRoles(String... roles), which executes appropriate database queries. I always had to call these methods at the start of a protected EJB method/REST resource, making an if-statement and possibly throwing a "NotAuthorized"-exception.
For the future I consider using JakartaEE's security mechanisms so I am reading into it. I have a problem understanding the use of the #javax.annotation.security.DeclareRoles annotation.
Amongst others I read SO answer to ejb Security questions regarding Roles and Authentication. There it is said that
The #DeclareRoles annotation on the other hand is merely used to declare a list of roles; [...]. The EJB container does not require knowledge of these roles to enforce access control checks on business methods of an EJB; instead, the bean provider/developer may use these roles in isCallerInRole tests to ensure programmatic security.
If I understand it right I need to declare the roles I use programmatically with javax.security.enterprise.SecurityContext#isCallerInRole(String). So my class might look like the following.
#DeclareRoles({"ADD_ENTITY", "DELETE_ENTITY", "UPDATE_ENTITY", "SEE_ENTITY", "SEE_ENTITY_DETAILS", "SEE_RESTRICTED_DATA", "MERGE_ENTITY", "ATTACH_METADATA"})
public class PersonService {
#Inject SecurityContext ctx;
#RolesAllowed({"SEE_ENTITY"})
public Person getPerson(long id) {
if(ctx.isCallerInRole("SEE_ENTITY_DETAILS") {...}
else if(ctx.isCallerInRole("SEE_RESTRICTED_DATA") {...}
else {...}
}
...
}
1st question:
Now if I have another class, do I need to declare all the roles again?
#DeclareRoles({"ADD_ENTITY", "DELETE_ENTITY", "UPDATE_ENTITY", "SEE_ENTITY", "SEE_ENTITY_DETAILS", "SEE_RESTRICTED_DATA", "MERGE_ENTITY", "ATTACH_METADATA"})
public class CompanyService {
#Inject SecurityContext ctx;
#RolesAllowed({"SEE_ENTITY"})
public Company geCompany(long id) {
if(ctx.isCallerInRole("SEE_ENTITY_DETAILS") {...}
else {...}
}
...
}
In the mentioned answer the EJB spec is quoted with
The DeclareRoles annotation is specified on a bean class, where it serves to declare roles that may be tested by calling isCallerInRole [...]
2nd question: Is it correct that this declaration is only used by the programmatically access and not for the declarative part? So that I do not need to declare any roles if I only use the annotation #RolesAllowed.
3rd question: What is the reason for this "duplication"? For me it is just annoying to declare the roles (by the way I do have plenty of roles in my application) twice. I do not see the point in doing so, after all it is just a string. I need to write a custom javax.security.enterprise.identitystore.IdentityStore to map roles to a user. Aligning these roles in every EJB seems to be unnecessary.
4th question: In a comment to a similar question (Define #DeclareRoles annotation programmatically) I interpret that #DeclareRoles might by a ancient relic and is no longer needed if an IdentityStore is used. If that would be true, it would make things a little bit clearer to me.
Sorry for the four questions in one post, but it all tangled together somehow. Basically it is question 3 that haunts me the most.

VB.Net shared constant strings [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I'm refactoring a project, moving all the magic strings used to access the fields of datatables to a dedicated Module. This application has a lot of tables, with obviously even more fields, so my question is: is there any problem putting so many static constants (probably hundreds) in a Module, in terms of performances of the application?
Personally I would split the tables into classes and add them to the Module. You can then reference them in a more structured way, and the module will be easier to manage. e.g.
For a database named Person:
''' <summary>
''' Represents the fields of database table Person
''' </summary>
Public Class Person
Public Property FirstName As String = NameOf(FirstName)
Public Property Surname As String = NameOf(Surname)
Public Property DateOfBirth As String = NameOf(DateOfBirth)
End Class
Then add that to your module:
Public Module Tables
Public Person As New Person
End Module
To then reference:
Sub Main(args As String())
Console.WriteLine(Tables.Person.FirstName)
Console.WriteLine(Tables.Person.Surname)
Console.WriteLine(Tables.Person.DateOfBirth)
Console.ReadLine()
End Sub
Or you could reference the object to make it slightly easier to read.
Sub Main(args As String())
Dim person = Tables.Person
Console.WriteLine(person.FirstName)
Console.WriteLine(person.Surname)
Console.WriteLine(person.DateOfBirth)
Console.ReadLine()
End Sub
Regarding performance, the objects will be stored in memory but will have no real impact on performance.

How to use the strategy pattern with managed objects

I process messages from a queue. I use data from the incoming message to determine which class to use to process the message; for example origin and type. I would use the combination of origin and type to look up a FQCN and use reflection to instantiate an object to process the message. At the moment these processing objects are all simple POJOs that implement a common interface. Hence I am using a strategy pattern.
The problem I am having is that all my external resources (mostly databases accessed via JPA) are injected (#Inject) and when I create the processing object as described above all these injected objects are null. The only way I know to populate these injected resources is to make each implementation of the interface a managed bean by adding #stateless. This alone does not solve the problem because the injected members are only populated if the class implementing the interface is itself injected (i.e. container managed) as opposed to being created by me.
Here is a made up example (sensitive details changed)
public interface MessageProcessor
{
public void processMessage(String xml);
}
#Stateless
public VisaCreateClient implements MessageProcessor
{
#Inject private DAL db;
…
}
public MasterCardCreateClient implements MessageProcessor…
In the database there is an entry "visa.createclient" = "fqcn.VisaCreateClient", so if the message origin is "Visa" and the type is "Create Client" I can look up the appropriate processing class. If I use reflection to create VisaCreateClient the db variable is always null. Even if I add the #Stateless and use reflection the db variable remains null. It's only when I inject VisaCreateClient will the db variable get populated. Like so:
#Stateless
public QueueReader
{
#Inject VisaCreateClient visaCreateClient;
#Inject MasterCardCreateClient masterCardCreateClient;
#Inject … many more times
private Map<String, MessageProcessor> processors...
private void init()
{
processors.put("visa.createclient", visaCreateClient);
processors.put("mastercard.createclient", masterCardCreateClient);
… many more times
}
}
Now I have dozens of message processors and if I have to inject each implementation then register it in the map I'll end up with dozens of injections. Also, should I add more processors I have to modify the QueueReader class to add the new injections and restart the server; with my old code I merely had to add an entry into the database and deploy the new processor on the class path - didn't even have to restart the server!
I have thought of two ways to resolve this:
Add an init(DAL db, OtherResource or, ...) method to the interface that gets called right after the message processor is created with reflection and pass the required resource. The resource itself was injected into the QueueReader.
Add an argument to the processMessage(String xml, Context context) where Context is just a map of resources that were injected into the QueueReader.
But does this approach mean that I will be using the same instance of the DAL object for every message processor? I believe it would and as long as there is no state involved I believe it is OK - any and all transactions will be started outside of the DAL class.
So my question is will my approach work? What are the risks of doing it that way? Is there a better way to use a strategy pattern to dynamically select an implementation where the implementation needs access to container managed resources?
Thanks for your time.
In a similar problem statement I used an extension to the processor interface to decide which type of data object it can handle. Then you can inject all variants of the handler via instance and simply use a loop:
public interface MessageProcessor
{
public boolean canHandle(String xml);
public void processMessage(String xml);
}
And in your queueReader:
#Inject
private Instance<MessageProcessor> allProcessors;
public void handleMessage(String xml) {
MessageProcessor processor = StreamSupport.stream(allProcessors.spliterator(), false)
.filter(proc -> proc.canHandle(xml))
.findFirst()
.orElseThrow(...);
processor.processMessage(xml);
}
This does not work on a running server, but to add a new processor simply implement and deploy.

Accessing WinForm UI from Rhino Service Bus consumer [duplicate]

This question already has answers here:
Invoke or BeginInvoke cannot be called on a control until the window handle has been created
(8 answers)
Closed 9 years ago.
I have a WinForm screen that is also a message consumer (using Rhino ESB). If I try to update anything on the screen when I receive a message, nothing happens. A call to Invoke gives me an error that the handle is not created. The form is definitely created though, I'm firing a message on button click on the form and the background process sends a message back. It's with this return message I want to update the UI.
THIS IS NOT A DUPLICATE QUESTION, NONE OF THE SUGGESTED SOLUTIONS WORK.
I believe the difference here may be because I'm using Rhino Service bus. Rhino may be constructing a separate instance of my form rather than the one I'm using. I think what I probably need to do is to have Rhino use my instance of the form as the consumer by passing my instance into the IoC container Rhino is using. Another alternative is to move the Consumer off to it's own class and inject my Form into the consumer, and put a public method on my Form for the Consumer to use. This may work fine with my app because this is the main form and will never be disposed unless the app is closed. This would become problematic on another form that may be instantiated multiple times. Perhaps I could have my form "observe" another static object that a separate Consumer class updates. Please give suggestions as to the best approach.
public partial class MainForm : Form, ConsumerOf<MoveJobCompletedEvent>
{
public void Consume(MoveJobCompletedEvent message)
{
// This does nothing!
txtLogs.Text = "\nJob completed!";
}
}
This throws an error:
this.BeginInvoke((MethodInvoker)delegate
{
txtLogs.Text += "\nJob job completed!";
});
ERROR: Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
It seems that you're consuming a JobCompleted event before the window handle is created. You could try the following:
public partial class MainForm : Form, ConsumerOf<MoveJobCompletedEvent>
{
public void Consume(MoveJobCompletedEvent message)
{
if (!this.HandleCreated)
return;
this.BeginInvoke((MethodInvoker)delegate
{
txtLogs.Text += "\nJob job completed!";
});
}
}

Application Object Won't Share

I'm having issues with my Application Object. I am currently using a Service to simulate incoming data from an electronic game board. This data is represented as a 2D boolean array. Every five seconds the Service uses a method of the Application Object to update the array (setDetectionMap()). This array is being read by a Thread in my main Activity using another method (getDetectionMap()). After some debugging I am almost positive that the main Activity is not seeing the changes. Here is the code for my Application Object:
public class ChessApplication extends Application{
private static ChessApplication singleton;
private boolean[][] detectionMap;
public static ChessApplication getInstance(){
return singleton;
}
#Override
public void onCreate() {
super.onCreate();
singleton=this;
detectionMap=new boolean[8][8];
}
public boolean[][] getDetectionMap(){
return detectionMap;
}
public void setDetectionMap(boolean[][] newMap){
detectionMap=newMap;
Log.d("Chess Application","Board Changed");
}
}
I've checked my Manifest, I've rewritten my object declaration a dozen times, I've added LogCat tags to make sure that the code is executing when I think it should be, and I've even implemented the supposedly redundant Singleton code. Any ideas what could be causing this? Incidentally can anyone tell me how to view variable states as the activity is running? Thanks in advance.
Is your Activity calling getDetectionMap() to get the new map after the update occurs?
Because otherwise, it's holding onto a reference to the old boolean[][] array, wheras setDetectionMap(...) isn't actually updating the current data structure, it's just updating the "detectionMap" variable to point to a different one. As such, your main activity won't be aware of the swapout until the next time it calls getDetectionMap.
Easy fix: in setDetectionMap, manually copy values from newMap into detectionMap. Or, update the Activity's reference so it's looking at the right map.
One other observation entirely unrelated to the original question: It's quite unusual to override Application during Android development, and is usually considered a "code smell" unless you have a really good reason for doing so. In this case I imagine it's so that you can communicate between your service and Activity, but you create a middle-man where one isn't entirely necessary. Here's a useful SO thread on how to communicate directly between the two :)

Resources