SubjectCallable's call method:
public V call() throws Exception {
try {
threadState.bind();
return doCall(this.callable);
} finally {
threadState.restore();
}
}
1.bind method is necsssary, but restore is why?
public void bind() {
SecurityManager securityManager = this.securityManager;
if ( securityManager == null ) {
//try just in case the constructor didn't find one at the time:
securityManager = ThreadContext.getSecurityManager();
}
this.originalResources = ThreadContext.getResources();
ThreadContext.remove();
ThreadContext.bind(this.subject);
if (securityManager != null) {
ThreadContext.bind(securityManager);
}
}
public void restore() {
ThreadContext.remove();
if (!CollectionUtils.isEmpty(this.originalResources)) {
ThreadContext.setResources(this.originalResources);
}
}
2.originalResources is use to do ? each time enter the AbstractShiroFilter will create a new subject and invoke it's execute method, the originalResources seems useless.
General thread health. You need to clean up resource in case the thread is re-used (very common). And it would help with garbage collection too.
Do you ever go hiking? Leave no trace ;)
Related
I have seen the same question with an answer, but unfortunately I haven't fully understood how to address the issue, as I get a null reference exception.
I try to have 2 coroutines run simultaneously. Each is from a different base class. They both are identical, apart from the class's name and activation key (one is Up Arrow and the other Down Arrow).
public IEnumerator DetectArrow()
{
if (Input.GetKey(KeyCode.UpArrow))
{
if (PrintMessage == null)
{
PrintMessage += SendMessage;
}
}
return null;
}
public void SendMessage()
{
print("I am B.");
PrintMessage = null;
}
I try to run something such as this for the entire run (from a parent class):
void Update ()
{
if (b.PrintMessage != null)
{
b.PrintMessage();
}
if (a.PrintMessage != null)
{
a.PrintMessage();
}
}
So I'm not quite sure how to solve this. Thanks for the help.
On the ContainerBuilder i can do the following:
builder.Register<ScenariosConfig>(c =>
(ScenariosConfig)c.Resolve<ConfigFactory>()
.Create(typeof(ScenariosConfig)))
.SingleInstance();
With assembly scanning i can do the following:
builder.RegisterAssemblyTypes(assemblies)
.Where(HasSingletonAttribute)
.As(t => GetNameMatchingInterfaces(t))
.SingleInstance();
Now the question: Is there any way to achieve the following: ?
builder.RegisterAssemblyTypes(assemblies)
.Where(... some condition)
.CreateByDelegate((container, type)
=> c.Resolve<ConfigFactory>().Create(type))
.SingleInstance();
I've already found out about IRegistrationSource with which i can achieve something similar. However, I'm a bit skeptic about the performance impact of creating ton's of IRegistrationSource's for each of my conventions which require a delegate for creation...
And also there's the fact that IRegistrationSource can't be used whenever you need to resolve all instances of IFoo which should be bound by such a "convention".
In the end we did choose to use an IRegistrationSource. The only alternative i've "found" would have been to detect all types per reflection (not using autofac API...) and then generating a delegate for each and registering this with autofac. Would not really result in code that easily understandable...
So for completeness sake' here's the IRegistrationSource implementation:
public class ConfigConventionRegistrationSource : IRegistrationSource
{
public IEnumerable<IComponentRegistration> RegistrationsFor(
Service service,
Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
{
var s = service as IServiceWithType;
if (s != null
&& s.ServiceType.IsClass
&& s.ServiceType.Name.EndsWith("Config")
&& !s.ServiceType.GetInterfaces().Any())
{
yield return RegistrationBuilder
.ForDelegate((componentContext, parameters) =>
CreateConfigByFactory(componentContext, s.ServiceType))
.As(s.ServiceType)
.SingleInstance()
.CreateRegistration();
}
}
private static object CreateConfigByFactory(
IComponentContext componentContext,
Type configType)
{
IConfig configFactory = componentContext.Resolve<IConfig>();
MethodInfo method = Reflector<IConfig>
.GetMethod(x => x.Load<object>())
.GetGenericMethodDefinition()
.MakeGenericMethod(configType);
try
{
return method.Invoke(configFactory, new object[0]);
}
catch (TargetInvocationException tex)
{
ExceptionDispatchInfo
.Capture(tex.InnerException)
.Throw();
throw; // will not be reached as thrown above ;-)
}
}
public bool IsAdapterForIndividualComponents
{
get { return false; }
}
}
I'm trying to find a method that allows me to do a rollback when one of the elements of a list fails for a reason within the business rules established (ie: when throw my customize exception)
Example, (the idea is not recording anything if one element in list fails)
public class ControlSaveElement {
public void saveRecords(List<MyRecord> listRecords) {
Boolean status = true;
foreach(MyRecord element: listRecords) {
// Here is business rules
if(element.getStatus() == false) {
// something
status = false;
}
element.persist();
}
if(status == false) {
// I need to do roll back from all elements persisted before
}
}
...
}
Any idea? I'm working with Roo 1.2.2..
What you're describing is a service method (saveRecords) that needs to be transactional. Either annotated with the #Transactional annotation and then you raise an exception, or you will have to look into using the TransactionTemplate to get finer control in order to do a manual rollback.
http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/transaction.html
http://springinpractice.com/2008/03/18/annotation-based-transactions-in-spring/
is there a way to force a transactional rollback without encountering an exception?
How about creating a new static method in the MyRecord entity:
#Transactional
public static void saveMyRecordsList(List<MyRecord> listRecords) {
boolean persistAll = true;
foreach(MyRecord element: listRecords) {
if(element.getStatus() == false) {
persistAll = false;
}
}
if (persistAll) {
foreach(MyRecord element: listRecords) {
entityManager().persist(element);
}
}
}
This may be more efficient than persisting elements and having to roll them back?
My problem is that in the main class I have some osgi references that work just fine when the class is call. But after that all the references became null. When I close the main windows and call shutdown method, the hubService reference returns null. What do I do wrong here?
private void shutdown() {
if(hubService == null) {
throw new NullPointerException();
}
hubService.shutdownHub(); // why is hubService null?
}
// bind hub service
public synchronized void setHubService(IHubService service) {
hubService = service;
try {
hubService.startHub(PORT, authenticationHandler);
} catch (Exception e) {
JOptionPane.showMessageDialog(mainFrame, e.toString(), "Server", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
// remove hub service
public synchronized void unsetHubService(IHubService service) {
hubService.shutdownHub();
hubService = null;
}
If a field can be read and written by multiple threads, you must protect access to read as well as write. Your first method, shutdown, does not protect the read of hubService so that the value of hubService can change between the first read and the second read. You don't show the declaration of the hubService field. You could make it volatile or only read when synchronized (on the same object used to synchronized when writing the field). Then your shutdown implementation could look like:
private volatile IHubService hubService;
private void shutdown() {
IHubService service = hubService; // make a copy of the field in a local variable
if (service != null) // use local var from now on since the field could have changed
service.shutdownHub();
}
I assume your shutdown method is the DS deactivate method? If so, why do you shutdown in the unset method as well in the shutdown method?
Overall the design does not seem very sound. The IHubService is used as a factory and should return some object that is then closed in the deactivate method. You made the IHubService effectively a singleton. Since it must come from another bundle, it should handle its life cycle itself.
Since you also do not use annotations, it is not clear if your set/unset methods are static/dynamic and/or single/multiple. The following code should not have your problems (exammple code with bnd annotations):
#Component public class MyImpl {
IHubService hub;
#Activate
void activate() {
hubService.startHub(PORT, authenticationHandler);
}
#DeActivate
void deactivate() {
hubService.shutdown();
}
#Reference
void setHub(IHubService hub) { this.hub = hub; }
}
QuartzTriggerHandle object that returned by Asynchronous method in Seam always 'null',
the job starts but cann't cancelled or paused.
In, seam forum i found the next example that should be work,but it doesn't work with me.
#Name("quartzObserver")
public class SCSQuartzObserver {
#In(create = true)
SCSQuartzTask quartzTask;
#SuppressWarnings("unused")
#Observer("org.jboss.seam.postInitialization")
public void observe() {
try {
Calendar cal = Calendar.getInstance();
cal.set(2040, Calendar.MAY, 10);
QuartzTriggerHandle handle = quartzTask.performTask(new Date(),
86400000l);
handle.cancel();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Name("quartzTask")
#AutoCreate
public class SCSQuartzTask {
#Asynchronous
public QuartzTriggerHandle performTask(#Expiration java.util.Date when,
#IntervalDuration long duration) {
// do stuff
QuartzTriggerHandle handle = new QuartzTriggerHandle("SCSQuartzTask");
return handle;
}
}
thnx for help.
You shouldn't create the QuartzTriggerHandle. Just do your work in the body of the performTask method, seam runtime will take care to return the QuartzTriggerHandle object. Something like this:
#Asynchronous
public QuartzTriggerHandle performTask(#Expiration java.util.Date when,
#IntervalDuration long duration) {
// do stuff
return null;
}
The QuartzTriggerHandle is serializable, you can keep it in a database table so you can later cancel the task.
Hi You must add something in component.xml
1-)async:quartz-dispatcher
2-)xsi:schemaLocation
http://jboss.com/products/seam/async
http://jboss.com/products/seam/async-2.2.xsd"
now it will work
you can find example Melih sakarya web site
http://www.melihsakarya.com/2011/09/seam-de-zamanli-isler-scheduling/