Search Results

Search found 215 results on 9 pages for 'interceptor'.

Page 1/9 | 1 2 3 4 5 6 7 8 9  | Next Page >

  • Using the BAM Interceptor with Continuation

    - by Charles Young
    Originally posted on: http://geekswithblogs.net/cyoung/archive/2014/06/02/using-the-bam-interceptor-with-continuation.aspxI’ve recently been resurrecting some code written several years ago that makes extensive use of the BAM Interceptor provided as part of BizTalk Server’s BAM event observation library.  In doing this, I noticed an issue with continuations.  Essentially, whenever I tried to configure one or more continuations for an activity, the BAM Interceptor failed to complete the activity correctly.   Careful inspection of my code confirmed that I was initializing and invoking the BAM interceptor correctly, so I was mystified.  However, I eventually found the problem.  It is a logical error in the BAM Interceptor code itself. The BAM Interceptor provides a useful mechanism for implementing dynamic tracking.  It supports configurable ‘track points’.  These are grouped into named ‘locations’.  BAM uses the term ‘step’ as a synonym for ‘location’.   Each track point defines a BAM action such as starting an activity, extracting a data item, enabling a continuation, etc.  Each step defines a collection of track points. Understanding Steps The BAM Interceptor provides an abstract model for handling configuration of steps.  It doesn’t, however, define any specific configuration mechanism (e.g., config files, SSO, etc.)  It is up to the developer to decide how to store, manage and retrieve configuration data.  At run time, this configuration is used to register track points which then drive the BAM Interceptor. The full semantics of a step are not immediately clear from Microsoft’s documentation.  They represent a point in a business activity where BAM tracking occurs.  They are named locations in the code.  What is less obvious is that they always represent either the full tracking work for a given activity or a discrete fragment of that work which commences with the start of a new activity or the continuation of an existing activity.  The BAM Interceptor enforces this by throwing an error if no ‘start new’ or ‘continue’ track point is registered for a named location. This constraint implies that each step must marked with an ‘end activity’ track point.  One of the peculiarities of BAM semantics is that when an activity is continued under a correlated ID, you must first mark the current activity as ‘ended’ in order to ensure the right housekeeping is done in the database.  If you re-start an ended activity under the same ID, you will leave the BAM import tables in an inconsistent state.  A step, therefore, always represents an entire unit of work for a given activity or continuation ID.  For activities with continuation, each unit of work is termed a ‘fragment’. Instance and Fragment State Internally, the BAM Interceptor maintains state data at two levels.  First, it represents the overall state of the activity using a ‘trace instance’ token.  This token contains the name and ID of the activity together with a couple of state flags.  The second level of state represents a ‘trace fragment’.   As we have seen, a fragment of an activity corresponds directly to the notion of a ‘step’.  It is the unit of work done at a named location, and it must be bounded by start and end, or continue and end, actions. When handling continuations, the BAM Interceptor differentiates between ‘root’ fragments and other fragments.  Very simply, a root fragment represents the start of an activity.  Other fragments represent continuations.  This is where the logic breaks down.  The BAM Interceptor loses state integrity for root fragments when continuations are defined. Initialization Microsoft’s BAM Interceptor code supports the initialization of BAM Interceptors from track point configuration data.  The process starts by populating an Activity Interceptor Configuration object with an array of track points.  These can belong to different steps (aka ‘locations’) and can be registered in any order.  Once it is populated with track points, the Activity Interceptor Configuration is used to initialise the BAM Interceptor.  The BAM Interceptor sets up a hash table of array lists.  Each step is represented by an array list, and each array list contains an ordered set of track points.  The BAM Interceptor represents track points as ‘executable’ components.  When the OnStep method of the BAM Interceptor is called for a given step, the corresponding list of track points is retrieved and each track point is executed in turn.  Each track point retrieves any required data using a call back mechanism and then serializes a BAM trace fragment object representing a specific action (e.g., start, update, enable continuation, stop, etc.).  The serialised trace fragment is then handed off to a BAM event stream (buffered or direct) which takes the appropriate action. The Root of the Problem The logic breaks down in the Activity Interceptor Configuration.  Each Activity Interceptor Configuration is initialised with an instance of a ‘trace instance’ token.  This provides the basic metadata for the activity as a whole.  It contains the activity name and ID together with state flags indicating if the activity ID is a root (i.e., not a continuation fragment) and if it is completed.  This single token is then shared by all trace actions for all steps registered with the Activity Interceptor Configuration. Each trace instance token is automatically initialised to represent a root fragment.  However, if you subsequently register a ‘continuation’ step with the Activity Interceptor Configuration, the ‘root’ flag is set to false at the point the ‘continue’ track point is registered for that step.   If you use a ‘reflector’ tool to inspect the code for the ActivityInterceptorConfiguration class, you can see the flag being set in one of the overloads of the RegisterContinue method.    This makes no sense.  The trace instance token is shared across all the track points registered with the Activity Interceptor Configuration.  The Activity Interceptor Configuration is designed to hold track points for multiple steps.  The ‘root’ flag is clearly meant to be initialised to ‘true’ for the preliminary root fragment and then subsequently set to false at the point that a continuation step is processed.  Instead, if the Activity Interceptor Configuration contains a continuation step, it is changed to ‘false’ before the root fragment is processed.  This is clearly an error in logic. The problem causes havoc when the BAM Interceptor is used with continuation.  Effectively the root step is no longer processed correctly, and the ultimate effect is that the continued activity never completes!   This has nothing to do with the root and the continuation being in the same process.  It is due to a fundamental mistake of setting the ‘root’ flag to false for a continuation before the root fragment is processed. The Workaround Fortunately, it is easy to work around the bug.  The trick is to ensure that you create a new Activity Interceptor Configuration object for each individual step.  This may mean filtering your configuration data to extract the track points for a single step or grouping the configured track points into individual steps and the creating a separate Activity Interceptor Configuration for each group.  In my case, the first approach was required.  Here is what the amended code looks like: // Because of a logic error in Microsoft's code, a separate ActivityInterceptorConfiguration must be used // for each location. The following code extracts only those track points for a given step name (location). var trackPointGroup = from ResolutionService.TrackPoint tp in bamActivity.TrackPoints                       where (string)tp.Location == bamStepName                       select tp; var bamActivityInterceptorConfig =     new Microsoft.BizTalk.Bam.EventObservation.ActivityInterceptorConfiguration(activityName); foreach (var trackPoint in trackPointGroup) {     switch (trackPoint.Type)     {         case TrackPointType.Start:             bamActivityInterceptorConfig.RegisterStartNew(trackPoint.Location, trackPoint.ExtractionInfo);             break; etc… I’m using LINQ to filter a list of track points for those entries that correspond to a given step and then registering only those track points on a new instance of the ActivityInterceptorConfiguration class.   As soon as I re-wrote the code to do this, activities with continuations started to complete correctly.

    Read the article

  • struts2: Redirect from global interceptor

    - by Dewfy
    In struts2 I have very simple task, after user is logged-in I'm checking if they profile is complete. If not user should be blocked from any other action and redirected to edit page. So I have created my default package: <package name="main" extends="tiles-default" > <interceptors> <interceptor name="checkProfile" class="my.CheckProfileInterceptor" /> <interceptor-stack name="secure"> <interceptor-ref name="defaultStack"/> <interceptor-ref name="checkProfile"/> </interceptor-stack> </interceptors> <default-interceptor-ref name="secure"/> </package> After it all my packages would include this template as a base: <package namespace="/packageA" name="packageA" extends="main"> ... <package namespace="/packageB" name="packageB" extends="main"> ... Saying editing page is /packageA/editProfile, my interceptor does following: public String intercept(ActionInvocation actionInvocation) throws Exception { if( currentUser.isOk() ) return "editProfile"; ... BUT! interceptor is global, so it raises struts2 error: No result defined for action (name of editProfile action class) When interceptor is placed inside some package - then everything ok. What should i do to declare global action?

    Read the article

  • Struts 2 how to display messages saved in a Interceptor which would redirec to another action?

    - by mui13
    in my interceptor, if user doesn't have enough right, there would be a warn message: public String intercept(ActionInvocation invocation) throws Exception { ActionContext actionContext = invocation.getInvocationContext(); Map<String, Object> sessionMap = actionContext.getSession(); User loginUser = (User) sessionMap.get("user"); Object action = invocation.getAction(); if (loginUser != null && loginUser.getRole().getId() != Constant.AUTHORITY_ADMIN) { ((ValidationAware) action).addFieldError("user.authority", ((DefaultAction) action).getText("user.action.authority.not.enough")); return DefaultAction.HOME_PAGE; } return invocation.invoke(); } then, it would redirect to "HOME_PAGE" action, if success, display information in the jsp. So how to display the warn message? i have used two interceptors configed in strust.xml, for admin right requirment: <interceptor-stack name="authorityStack"> <interceptor-ref name="authority" /> <interceptor-ref name="defaultStack" /> <interceptor-ref name="store"> <param name="operationMode">STORE</param> </interceptor-ref> </interceptor-stack> default is: <interceptor-stack name="default"> <interceptor-ref name="login" /> <interceptor-ref name="defaultStack" /> <interceptor-ref name="store"> <param name="operationMode">AUTOMATIC</param> </interceptor-ref> </interceptor-stack>

    Read the article

  • Redirect to another action in an interceptor in struts 2

    - by user292662
    I am currently in the process of learning Struts 2 and I am currently building a simple application where unverified users are redirected to a login form. I have a login form and action functional which takes the users credentials, verifies them and stores a User object in the session however I am now trying to prevent access to pages before the login has taken place and I am trying to do this with an interceptor. My problem is that I have written an interceptor that checks whether the User object has been saved in the session but if it has not I want to redirect to the login page and can't find any way of doing this without bypassing struts and using the HttpServletResponse.sendRedirect method Configuration: <package name="mypackage" extends="struts-default" namespace="/admin"> <interceptors> <interceptor name="login" class="my.LoginInterceptor" /> </interceptors> <default-interceptor-ref name="login"/> <action name="login" class="my.LoginAction"> <result name="input">/admin/login.jsp</result> <result name="success" type="redirect">/admin</result> </action> <action name="private" class="my.PrivateAction"> <result>/admin/private.jsp</result> </action> </package> The interceptor code: @Override public String intercept(ActionInvocation inv) throws Exception { Map<String, Object> session = inv.getInvocationContext().getSession(); Object user = session.get("user"); if(user == null) { // redirect to the 'login' action here } else { return inv.invoke(); } }

    Read the article

  • Using an extended interceptor in struts2 does not work w/ action parameters

    - by Ricardo
    I have a default package w/ an interceptor configure, and i'm extending that package into another one and calling the same interceptor <action name="availability**"> <param name="subTab">availability</param> <interceptor-ref name="tabStack"/> <result>/WEB-INF/jsp/index.jsp?include=visibilit/availability.jsp</result> </action> The problem is that the param is not being read inside my interceptor code: Map params = invocation.getInvocationContext().getParameters(); subTab = params.get("subTab").toString(); //NULL exception Any idea how i can pass parameters to extended interceptors? Thanks!

    Read the article

  • In apache cxf, How do i know the soap request message is gzip compressed?

    - by aspirant75
    I'm using Apache CXF to send soap message. in specific case, i have to send a soap message gzip compressed. Using log4j, i printed detailed info. would you let me know how i can know the message is gzip compressed and transfered to server. thanks in advance. Below is my java code for gzip and log info. java code Client cxfClient = ClientProxy.getClient(port); /** Logging Interceptor */ cxfClient.getInInterceptors().add(new GZIPInInterceptor()); cxfClient.getOutInterceptors().add(new GZIPOutInterceptor()); log info 20120814 18:56:15,351 DEBUG Interceptors contributed by bus: [] 20120814 18:56:15,351 DEBUG Interceptors contributed by client: [org.apache.cxf.transport.http.gzip.GZIPOutInterceptor@1682a53] 20120814 18:56:15,351 DEBUG Interceptors contributed by endpoint: [org.apache.cxf.interceptor.MessageSenderInterceptor@1b2d7df, org.apache.cxf.jaxws.interceptors.SwAOutInterceptor@7a9224, org.apache.cxf.jaxws.interceptors.WrapperClassOutInterceptor@110b640, org.apache.cxf.jaxws.interceptors.HolderOutInterceptor@2d59a3] 20120814 18:56:15,351 DEBUG Interceptors contributed by binding: [org.apache.cxf.interceptor.AttachmentOutInterceptor@158015a, org.apache.cxf.interceptor.StaxOutInterceptor@c0c8b5, org.apache.cxf.binding.soap.interceptor.SoapHeaderOutFilterInterceptor@b914b3, org.apache.cxf.interceptor.BareOutInterceptor@fdfc58, org.apache.cxf.binding.soap.interceptor.SoapPreProtocolOutInterceptor@c22a3b, org.apache.cxf.binding.soap.interceptor.SoapOutInterceptor@1629e71] 20120814 18:56:15,351 DEBUG Interceptors contributed by databinding: [] 20120814 18:56:15,357 DEBUG Adding interceptor org.apache.cxf.transport.http.gzip.GZIPOutInterceptor@1682a53 to phase prepare-send 20120814 18:56:15,358 DEBUG Adding interceptor org.apache.cxf.interceptor.MessageSenderInterceptor@1b2d7df to phase prepare-send 20120814 18:56:15,358 DEBUG Adding interceptor org.apache.cxf.jaxws.interceptors.SwAOutInterceptor@7a9224 to phase pre-logical 20120814 18:56:15,358 DEBUG Adding interceptor org.apache.cxf.jaxws.interceptors.WrapperClassOutInterceptor@110b640 to phase pre-logical 20120814 18:56:15,358 DEBUG Adding interceptor org.apache.cxf.jaxws.interceptors.HolderOutInterceptor@2d59a3 to phase pre-logical 20120814 18:56:15,358 DEBUG Adding interceptor org.apache.cxf.interceptor.AttachmentOutInterceptor@158015a to phase pre-stream 20120814 18:56:15,358 DEBUG Adding interceptor org.apache.cxf.interceptor.StaxOutInterceptor@c0c8b5 to phase pre-stream 20120814 18:56:15,358 DEBUG Adding interceptor org.apache.cxf.binding.soap.interceptor.SoapHeaderOutFilterInterceptor@b914b3 to phase pre-logical 20120814 18:56:15,358 DEBUG Adding interceptor org.apache.cxf.interceptor.BareOutInterceptor@fdfc58 to phase marshal 20120814 18:56:15,358 DEBUG Adding interceptor org.apache.cxf.binding.soap.interceptor.SoapPreProtocolOutInterceptor@c22a3b to phase post-logical 20120814 18:56:15,359 DEBUG Adding interceptor org.apache.cxf.binding.soap.interceptor.SoapOutInterceptor@1629e71 to phase write 20120814 18:56:15,360 DEBUG Chain org.apache.cxf.phase.PhaseInterceptorChain@31688f was created. Current flow: pre-logical [HolderOutInterceptor, SwAOutInterceptor, WrapperClassOutInterceptor, SoapHeaderOutFilterInterceptor] post-logical [SoapPreProtocolOutInterceptor] prepare-send [MessageSenderInterceptor, GZIPOutInterceptor] pre-stream [AttachmentOutInterceptor, StaxOutInterceptor] write [SoapOutInterceptor] marshal [BareOutInterceptor] 20120814 18:56:15,361 DEBUG Invoking handleMessage on interceptor org.apache.cxf.jaxws.interceptors.HolderOutInterceptor@2d59a3 20120814 18:56:15,361 DEBUG op: [OperationInfo: {https://asp.cyberbooking.co.kr/TopasApiSvc/services}getAirAvail] 20120814 18:56:15,361 DEBUG op.hasOutput(): true 20120814 18:56:15,361 DEBUG op.getOutput().size(): 2 20120814 18:56:15,361 DEBUG Invoking handleMessage on interceptor org.apache.cxf.jaxws.interceptors.SwAOutInterceptor@7a9224 20120814 18:56:15,364 DEBUG Invoking handleMessage on interceptor org.apache.cxf.jaxws.interceptors.WrapperClassOutInterceptor@110b640 20120814 18:56:15,364 DEBUG Invoking handleMessage on interceptor org.apache.cxf.binding.soap.interceptor.SoapHeaderOutFilterInterceptor@b914b3 20120814 18:56:15,365 DEBUG Invoking handleMessage on interceptor org.apache.cxf.binding.soap.interceptor.SoapPreProtocolOutInterceptor@c22a3b 20120814 18:56:15,365 DEBUG Invoking handleMessage on interceptor org.apache.cxf.interceptor.MessageSenderInterceptor@1b2d7df 20120814 18:56:15,365 DEBUG Adding interceptor org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor@dc9065 to phase prepare-send-ending 20120814 18:56:15,366 DEBUG Chain org.apache.cxf.phase.PhaseInterceptorChain@31688f was modified. Current flow: pre-logical [HolderOutInterceptor, SwAOutInterceptor, WrapperClassOutInterceptor, SoapHeaderOutFilterInterceptor] post-logical [SoapPreProtocolOutInterceptor] prepare-send [MessageSenderInterceptor, GZIPOutInterceptor] pre-stream [AttachmentOutInterceptor, StaxOutInterceptor] write [SoapOutInterceptor] marshal [BareOutInterceptor] prepare-send-ending [MessageSenderEndingInterceptor] 20120814 18:56:15,366 DEBUG Invoking handleMessage on interceptor org.apache.cxf.transport.http.gzip.GZIPOutInterceptor@1682a53 20120814 18:56:15,366 DEBUG Requestor role, so gzip enabled 20120814 18:56:15,366 DEBUG gzip permitted: YES 20120814 18:56:15,367 DEBUG Invoking handleMessage on interceptor org.apache.cxf.interceptor.AttachmentOutInterceptor@158015a 20120814 18:56:15,367 DEBUG Invoking handleMessage on interceptor org.apache.cxf.interceptor.StaxOutInterceptor@c0c8b5 20120814 18:56:15,370 DEBUG Adding interceptor org.apache.cxf.interceptor.StaxOutInterceptor$StaxOutEndingInterceptor@1f488f1 to phase pre-stream-ending 20120814 18:56:15,370 DEBUG Chain org.apache.cxf.phase.PhaseInterceptorChain@31688f was modified. Current flow: pre-logical [HolderOutInterceptor, SwAOutInterceptor, WrapperClassOutInterceptor, SoapHeaderOutFilterInterceptor] post-logical [SoapPreProtocolOutInterceptor] prepare-send [MessageSenderInterceptor, GZIPOutInterceptor] pre-stream [AttachmentOutInterceptor, StaxOutInterceptor] write [SoapOutInterceptor] marshal [BareOutInterceptor] pre-stream-ending [StaxOutEndingInterceptor] prepare-send-ending [MessageSenderEndingInterceptor] 20120814 18:56:15,370 DEBUG Invoking handleMessage on interceptor org.apache.cxf.binding.soap.interceptor.SoapOutInterceptor@1629e71 20120814 18:56:15,383 DEBUG Adding interceptor org.apache.cxf.binding.soap.interceptor.SoapOutInterceptor$SoapOutEndingInterceptor@1ce663c to phase write-ending 20120814 18:56:15,384 DEBUG Chain org.apache.cxf.phase.PhaseInterceptorChain@31688f was modified. Current flow: pre-logical [HolderOutInterceptor, SwAOutInterceptor, WrapperClassOutInterceptor, SoapHeaderOutFilterInterceptor] post-logical [SoapPreProtocolOutInterceptor] prepare-send [MessageSenderInterceptor, GZIPOutInterceptor] pre-stream [AttachmentOutInterceptor, StaxOutInterceptor] write [SoapOutInterceptor] marshal [BareOutInterceptor] write-ending [SoapOutEndingInterceptor] pre-stream-ending [StaxOutEndingInterceptor] prepare-send-ending [MessageSenderEndingInterceptor] 20120814 18:56:15,384 DEBUG Invoking handleMessage on interceptor org.apache.cxf.interceptor.BareOutInterceptor@fdfc58 20120814 18:56:15,387 DEBUG Compressing message. 20120814 18:56:15,388 DEBUG Sending POST Message with Headers to http://test.co.kr:80/###/###/###Conduit :{https://test.co.kr/###/####}###.http-conduit Content-Type: text/xml; charset=UTF-8 20120814 18:56:15,388 DEBUG SOAPAction: "getAirAvail" 20120814 18:56:15,388 DEBUG Accept: */* 20120814 18:56:15,388 DEBUG Accept-Encoding: gzip;q=1.0, identity; q=0.5, *;q=0 20120814 18:56:15,388 DEBUG Content-Encoding: gzip 20120814 18:56:15,388 DEBUG No Trust Decider for Conduit '{https://test.co.kr/###/###}###.http-conduit'. An afirmative Trust Decision is assumed. 20120814 18:56:15,394 DEBUG Invoking handleMessage on interceptor org.apache.cxf.binding.soap.interceptor.SoapOutInterceptor$SoapOutEndingInterceptor@1ce663c 20120814 18:56:15,394 DEBUG Invoking handleMessage on interceptor org.apache.cxf.interceptor.StaxOutInterceptor$StaxOutEndingInterceptor@1f488f1 20120814 18:56:15,394 DEBUG Invoking handleMessage on interceptor org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor@dc9065 20120814 18:56:15,459 DEBUG Response Code: 200 Conduit: {https://test.co.kr/###/###}###.http-conduit 20120814 18:56:15,459 DEBUG Content length: 11034 20120814 18:56:15,459 DEBUG Header fields: null: [HTTP/1.1 200 OK] Content-Language: [ko-KR] Date: [Tue, 14 Aug 2012 09:56:15 GMT] Content-Length: [11034] P3P: [CP='CAO PSA CONi OTR OUR DEM ONL'] Expires: [Thu, 01 Dec 1994 16:00:00 GMT] Keep-Alive: [timeout=10, max=100] Set-Cookie: [WMONID=mL6rq_Irpa_; Expires=Wed, 14 Aug 2013 09:56:15 GMT; Path=/] Connection: [Keep-Alive] Content-Type: [text/xml; charset=utf-8] Server: [IBM_HTTP_Server] Cache-Control: [no-cache="set-cookie, set-cookie2"]

    Read the article

  • Proxy is created, and interceptor is in the __interceptors array, but the interceptor is never calle

    - by drewbu
    This is the first time I've used interceptors with the fluent registration and I'm missing something. With the following registration, I can resolve an IProcessingStep, and it's a proxy class and the interceptor is in the __interceptors array, but for some reason, the interceptor is not called. Any ideas what I'm missing? Thanks, Drew AllTypes.Of<IProcessingStep>() .FromAssembly(Assembly.GetExecutingAssembly()) .ConfigureFor<IProcessingStep>(c => c .Unless(Component.ServiceAlreadyRegistered) .LifeStyle.PerThread .Interceptors(InterceptorReference.ForType<StepLoggingInterceptor>()).First ), Component.For<StepMonitorInterceptor>(), Component.For<StepLoggingInterceptor>(), Component.For<StoreInThreadInterceptor>() public abstract class BaseStepInterceptor : IInterceptor { public void Intercept(IInvocation invocation) { IProcessingStep processingStep = (IProcessingStep)invocation.InvocationTarget; Command cmd = (Command)invocation.Arguments[0]; OnIntercept(invocation, processingStep, cmd); } protected abstract void OnIntercept(IInvocation invocation, IProcessingStep processingStep, Command cmd); } public class StepLoggingInterceptor : BaseStepInterceptor { private readonly ILogger _logger; public StepLoggingInterceptor(ILogger logger) { _logger = logger; } protected override void OnIntercept(IInvocation invocation, IProcessingStep processingStep, Command cmd) { _logger.TraceFormat("<{0}> for cmd:<{1}> - begin", processingStep.StepType, cmd.Id); bool exceptionThrown = false; try { invocation.Proceed(); } catch { exceptionThrown = true; throw; } finally { _logger.TraceFormat("<{0}> for cmd:<{1}> - end <{2}> times:<{3}>", processingStep.StepType, cmd.Id, !exceptionThrown && processingStep.CompletedSuccessfully ? "succeeded" : "failed", cmd.CurrentMetric==null ? "{null}" : cmd.CurrentMetric.ToString()); } } }

    Read the article

  • Access custom attribute on method from Castle Windsor interceptor

    - by RobW
    I am trying to access a custom attribute applied to a method within a castle interceptor, e.g.: [MyCustomAttribute(SomeParam = "attributeValue")] public virtual MyEntity Entity { get; set; } using the following code: internal class MyInterceptor : IInterceptor { public void Intercept(IInvocation invocation) { if (invocation.Method.GetCustomAttributes(typeof(MyCustomAttribute), true) != null) { //Do something } } } The interceptor is firing OK when the method is called but this code does not return the custom attribute. How can I achieve this?

    Read the article

  • Implementing an Interceptor Using NHibernate’s Built In Dynamic Proxy Generator

    - by Ricardo Peres
    NHibernate 3.2 came with an included proxy generator, which means there is no longer the need – or the possibility, for that matter – to choose Castle DynamicProxy, LinFu or Spring. This is actually a good thing, because it means one less assembly to deploy. Apparently, this generator was based, at least partially, on LinFu. As there are not many tutorials out there demonstrating it’s usage, here’s one, for demonstrating one of the most requested features: implementing INotifyPropertyChanged. This interceptor, of course, will still feature all of NHibernate’s functionalities that you are used to, such as lazy loading, and such. We will start by implementing an NHibernate interceptor, by inheriting from the base class NHibernate.EmptyInterceptor. This class does not do anything by itself, but it allows us to plug in behavior by overriding some of its methods, in this case, Instantiate: 1: public class NotifyPropertyChangedInterceptor : EmptyInterceptor 2: { 3: private ISession session = null; 4:  5: private static readonly ProxyFactory factory = new ProxyFactory(); 6:  7: public override void SetSession(ISession session) 8: { 9: this.session = session; 10: base.SetSession(session); 11: } 12:  13: public override Object Instantiate(String clazz, EntityMode entityMode, Object id) 14: { 15: Type entityType = Type.GetType(clazz); 16: IProxy proxy = factory.CreateProxy(entityType, new _NotifyPropertyChangedInterceptor(), typeof(INotifyPropertyChanged)) as IProxy; 17: 18: _NotifyPropertyChangedInterceptor interceptor = proxy.Interceptor as _NotifyPropertyChangedInterceptor; 19: interceptor.Proxy = this.session.SessionFactory.GetClassMetadata(entityType).Instantiate(id, entityMode); 20:  21: this.session.SessionFactory.GetClassMetadata(entityType).SetIdentifier(proxy, id, entityMode); 22:  23: return (proxy); 24: } 25: } Then we need a class that implements the NHibernate dynamic proxy behavior, let’s place it inside our interceptor, because it will only need to be used there: 1: class _NotifyPropertyChangedInterceptor : NHibernate.Proxy.DynamicProxy.IInterceptor 2: { 3: private PropertyChangedEventHandler changed = delegate { }; 4:  5: public Object Proxy 6: { 7: get; 8: set;} 9:  10: #region IInterceptor Members 11:  12: public Object Intercept(InvocationInfo info) 13: { 14: Boolean isSetter = info.TargetMethod.Name.StartsWith("set_") == true; 15: Object result = null; 16:  17: if (info.TargetMethod.Name == "add_PropertyChanged") 18: { 19: PropertyChangedEventHandler propertyChangedEventHandler = info.Arguments[0] as PropertyChangedEventHandler; 20: this.changed += propertyChangedEventHandler; 21: } 22: else if (info.TargetMethod.Name == "remove_PropertyChanged") 23: { 24: PropertyChangedEventHandler propertyChangedEventHandler = info.Arguments[0] as PropertyChangedEventHandler; 25: this.changed -= propertyChangedEventHandler; 26: } 27: else 28: { 29: result = info.TargetMethod.Invoke(this.Proxy, info.Arguments); 30: } 31:  32: if (isSetter == true) 33: { 34: String propertyName = info.TargetMethod.Name.Substring("set_".Length); 35: this.changed(this.Proxy, new PropertyChangedEventArgs(propertyName)); 36: } 37:  38: return (result); 39: } 40:  41: #endregion 42: } What this does for every interceptable method (those who are either virtual or from the INotifyPropertyChanged) is: For methods that came from the INotifyPropertyChanged interface, add_PropertyChanged and remove_PropertyChanged (yes, events are methods ), we add an implementation that adds or removes the event handlers to the delegate which we declared as changed; For all the others, we direct them to the place where they are actually implemented, which is the Proxy field; If the call is setting a property, it fires afterwards the PropertyChanged event. In order to use this, we need to add the interceptor to the Configuration before building the ISessionFactory: 1: using (ISessionFactory factory = cfg.SetInterceptor(new NotifyPropertyChangedInterceptor()).BuildSessionFactory()) 2: { 3: using (ISession session = factory.OpenSession()) 4: using (ITransaction tx = session.BeginTransaction()) 5: { 6: Customer customer = session.Get<Customer>(100); //some id 7: INotifyPropertyChanged inpc = customer as INotifyPropertyChanged; 8: inpc.PropertyChanged += delegate(Object sender, PropertyChangedEventArgs e) 9: { 10: //fired when a property changes 11: }; 12: customer.Address = "some other address"; //will raise PropertyChanged 13: customer.RecentOrders.ToList(); //will trigger the lazy loading 14: } 15: } Any problems, questions, do drop me a line!

    Read the article

  • NInject2 Interceptor usage with NHibernate transactions

    - by Daniil Harik
    Hello, In my previous project we used NHibernate and Spring.NET. Transactions were handled by adding [Transaction] attribute to service methods. In my current project I'm using NHibernate and NInject 2 and I was wondering if it's possible to solve transaction handling using "Ninject.Extensions.Interception" and similar [Transaction] type attributes? Thank You very much!

    Read the article

  • A trigger on hibernate (maybe this is called interceptor)

    - by Ittai
    Hi, I have a module which uses Hibernate as an ORM solution with EHCache as second level cache. I have another seperate module which inserts and updates the database. What I need is to have the ability to trigger an event when a row is inserted or updated. Let's say I have a Customers table and it is mapped to a Customer entity. I want some procedure to notify me that a new Customer has been added. Regarding the second seperate module it uses Hibernate also but at least for the time being they are not connected (I'm pointing this out as if someone thinks that I must share the Hibernate session (or something of the sort) between them then this is something I will consider). Please note that I have limited experience with Hibernate. Thanks in advance

    Read the article

  • Passing data between Castle Windsor's Interceptors

    - by Nhím H? Báo
    I'm adopting Castle Windsor for my WCF project and feel really amazed about this. However, I'm having a scenario that I don't really know if Castle Windsor supports. For example I have the following chained Interceptors Interceptor 1 > Interceptor 2 > Interceptor 3 > Interceptor 4 > Real method Interceptor 1 returns some data and I want that to be available in Interceptor 2 Interceptor 2 in turn does it work and returns the data that I want to make avaialbe in the 3,4, interceptor. The real case scenario is that we're having a WCF service, Interceptor 1 will parse the request header into a Header object(username, password, etc.). The latter interceptors and real method will ultilize this Header object. I know that I can use Session variable to transport data, but is it a built-in, more elegant, more reliable way to handle this?

    Read the article

  • Creating a dynamic proxy generator with c# – Part 2 – Interceptor Design

    - by SeanMcAlinden
    Creating a dynamic proxy generator – Part 1 – Creating the Assembly builder, Module builder and caching mechanism For the latest code go to http://rapidioc.codeplex.com/ Before getting too involved in generating the proxy, I thought it would be worth while going through the intended design, this is important as the next step is to start creating the constructors for the proxy. Each proxy derives from a specified type The proxy has a corresponding constructor for each of the base type constructors The proxy has overrides for all methods and properties marked as Virtual on the base type For each overridden method, there is also a private method whose sole job is to call the base method. For each overridden method, a delegate is created whose sole job is to call the private method that calls the base method. The following class diagram shows the main classes and interfaces involved in the interception process. I’ll go through each of them to explain their place in the overall proxy.   IProxy Interface The proxy implements the IProxy interface for the sole purpose of adding custom interceptors. This allows the created proxy interface to be cast as an IProxy and then simply add Interceptors by calling it’s AddInterceptor method. This is done internally within the proxy building process so the consumer of the API doesn’t need knowledge of this. IInterceptor Interface The IInterceptor interface has one method: Handle. The handle method accepts a IMethodInvocation parameter which contains methods and data for handling method interception. Multiple classes that implement this interface can be added to the proxy. Each method override in the proxy calls the handle method rather than simply calling the base method. How the proxy fully works will be explained in the next section MethodInvocation. IMethodInvocation Interface & MethodInvocation class The MethodInvocation will contain one main method and multiple helper properties. Continue Method The method Continue() has two functions hidden away from the consumer. When Continue is called, if there are multiple Interceptors, the next Interceptors Handle method is called. If all Interceptors Handle methods have been called, the Continue method then calls the base class method. Properties The MethodInvocation will contain multiple helper properties including at least the following: Method Name (Read Only) Method Arguments (Read and Write) Method Argument Types (Read Only) Method Result (Read and Write) – this property remains null if the method return type is void Target Object (Read Only) Return Type (Read Only) DefaultInterceptor class The DefaultInterceptor class is a simple class that implements the IInterceptor interface. Here is the code: DefaultInterceptor namespace Rapid.DynamicProxy.Interception {     /// <summary>     /// Default interceptor for the proxy.     /// </summary>     /// <typeparam name="TBase">The base type.</typeparam>     public class DefaultInterceptor<TBase> : IInterceptor<TBase> where TBase : class     {         /// <summary>         /// Handles the specified method invocation.         /// </summary>         /// <param name="methodInvocation">The method invocation.</param>         public void Handle(IMethodInvocation<TBase> methodInvocation)         {             methodInvocation.Continue();         }     } } This is automatically created in the proxy and is the first interceptor that each method override calls. It’s sole function is to ensure that if no interceptors have been added, the base method is still called. Custom Interceptor Example A consumer of the Rapid.DynamicProxy API could create an interceptor for logging when the FirstName property of the User class is set. Just for illustration, I have also wrapped a transaction around the methodInvocation.Coninue() method. This means that any overriden methods within the user class will run within a transaction scope. MyInterceptor public class MyInterceptor : IInterceptor<User<int, IRepository>> {     public void Handle(IMethodInvocation<User<int, IRepository>> methodInvocation)     {         if (methodInvocation.Name == "set_FirstName")         {             Logger.Log("First name seting to: " + methodInvocation.Arguments[0]);         }         using (TransactionScope scope = new TransactionScope())         {             methodInvocation.Continue();         }         if (methodInvocation.Name == "set_FirstName")         {             Logger.Log("First name has been set to: " + methodInvocation.Arguments[0]);         }     } } Overridden Method Example To show a taster of what the overridden methods on the proxy would look like, the setter method for the property FirstName used in the above example would look something similar to the following (this is not real code but will look similar): set_FirstName public override void set_FirstName(string value) {     set_FirstNameBaseMethodDelegate callBase =         new set_FirstNameBaseMethodDelegate(this.set_FirstNameProxyGetBaseMethod);     object[] arguments = new object[] { value };     IMethodInvocation<User<IRepository>> methodInvocation =         new MethodInvocation<User<IRepository>>(this, callBase, "set_FirstName", arguments, interceptors);          this.Interceptors[0].Handle(methodInvocation); } As you can see, a delegate instance is created which calls to a private method on the class, the private method calls the base method and would look like the following: calls base setter private void set_FirstNameProxyGetBaseMethod(string value) {     base.set_FirstName(value); } The delegate is invoked when methodInvocation.Continue() is called within an interceptor. The set_FirstName parameters are loaded into an object array. The current instance, delegate, method name and method arguments are passed into the methodInvocation constructor (there will be more data not illustrated here passed in when created including method info, return types, argument types etc.) The DefaultInterceptor’s Handle method is called with the methodInvocation instance as it’s parameter. Obviously methods can have return values, ref and out parameters etc. in these cases the generated method override body will be slightly different from above. I’ll go into more detail on these aspects as we build them. Conclusion I hope this has been useful, I can’t guarantee that the proxy will look exactly like the above, but at the moment, this is pretty much what I intend to do. Always worth downloading the code at http://rapidioc.codeplex.com/ to see the latest. There will also be some tests that you can debug through to help see what’s going on. Cheers, Sean.

    Read the article

  • Can I inject a SessionBean into a JEE AroundInvoke-Interceptor?

    - by Michael Locher
    I have an EAR with modules: foo-api.jar foo-impl.jar interceptor.jar In foo-api there is: @Local FooService // (interface of a local stateless session bean) In foo-impl there is: @Stateless FooServiceImpl implements FooService //(implementation of the foo service) In interceptor.jar I want public class BazInterceptor { @EJB private FooService foo; @AroundInvoke public Object intercept( final InvocationContext i) throws Exception { // do someting with foo service return i.proceed(); } The question is: Will a Java EE 5 compliant application server (e.g. JBoss 5) inject into the interceptor? If no, what is good strategy for accessing the session bean? To consider: Deployment ordering / race conditions

    Read the article

  • EntityManager injection works in JBoss 7.1.1 but not WebSphere 7

    - by BikerJared
    I've built an EJB that will manage my database access. I'm building a web app around it that uses Struts 2. The problem I'm having is when I deploy the ear, the EntityManager doesn't get injected into my service class (and winds up null and results in NullPointerExceptions). The weird thing is, it works on JBoss 7.1.1 but not on WebSphere 7. You'll notice that Struts doesn't inject the EJB, so I've got some intercepter code that does that. My current working theory right now is that the WS7 container can't inject the EntityManager because of Struts for some unknown reason. My next step is to try Spring next, but I'd really like to get this to work if possible. I've spent a few days searching and trying various things and haven't had any luck. I figured I'd give this a shot. Let me know if I can provide additional information. <?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"> <persistence-unit name="JPATestPU" transaction-type="JTA"> <description>JPATest Persistence Unit</description> <jta-data-source>jdbc/Test-DS</jta-data-source> <class>org.jaredstevens.jpatest.db.entities.User</class> <properties> <property name="hibernate.hbm2ddl.auto" value="update"/> </properties> </persistence-unit> </persistence> package org.jaredstevens.jpatest.db.entities; import java.io.Serializable; import javax.persistence.*; @Entity @Table public class User implements Serializable { private static final long serialVersionUID = -2643583108587251245L; private long id; private String name; private String email; @Id @GeneratedValue(strategy = GenerationType.TABLE) public long getId() { return id; } public void setId(long id) { this.id = id; } @Column(nullable=false) public String getName() { return this.name; } public void setName( String name ) { this.name = name; } @Column(nullable=false) public String getEmail() { return this.email; } @Column(nullable=false) public void setEmail( String email ) { this.email= email; } } package org.jaredstevens.jpatest.db.services; import java.util.List; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceContextType; import javax.persistence.Query; import org.jaredstevens.jpatest.db.entities.User; import org.jaredstevens.jpatest.db.interfaces.IUserService; @Stateless(name="UserService",mappedName="UserService") @Remote public class UserService implements IUserService { @PersistenceContext(unitName="JPATestPU",type=PersistenceContextType.TRANSACTION) private EntityManager em; @TransactionAttribute(TransactionAttributeType.REQUIRED) public User getUserById(long userId) { User retVal = null; if(userId > 0) { retVal = (User)this.getEm().find(User.class, userId); } return retVal; } @TransactionAttribute(TransactionAttributeType.REQUIRED) public List<User> getUsers() { List<User> retVal = null; String sql; sql = "SELECT u FROM User u ORDER BY u.id ASC"; Query q = this.getEm().createQuery(sql); retVal = (List<User>)q.getResultList(); return retVal; } @TransactionAttribute(TransactionAttributeType.REQUIRED) public void save(User user) { this.getEm().persist(user); } @TransactionAttribute(TransactionAttributeType.REQUIRED) public boolean remove(long userId) { boolean retVal = false; if(userId > 0) { User user = null; user = (User)this.getEm().find(User.class, userId); if(user != null) this.getEm().remove(user); if(this.getEm().find(User.class, userId) == null) retVal = true; } return retVal; } public EntityManager getEm() { return em; } public void setEm(EntityManager em) { this.em = em; } } package org.jaredstevens.jpatest.actions.user; import javax.ejb.EJB; import org.jaredstevens.jpatest.db.entities.User; import org.jaredstevens.jpatest.db.interfaces.IUserService; import com.opensymphony.xwork2.ActionSupport; public class UserAction extends ActionSupport { @EJB(mappedName="UserService") private IUserService userService; private static final long serialVersionUID = 1L; private String userId; private String name; private String email; private User user; public String getUserById() { String retVal = ActionSupport.SUCCESS; this.setUser(userService.getUserById(Long.parseLong(this.userId))); return retVal; } public String save() { String retVal = ActionSupport.SUCCESS; User user = new User(); if(this.getUserId() != null && Long.parseLong(this.getUserId()) > 0) user.setId(Long.parseLong(this.getUserId())); user.setName(this.getName()); user.setEmail(this.getEmail()); userService.save(user); this.setUser(user); return retVal; } public String getUserId() { return this.userId; } public void setUserId(String userId) { this.userId = userId; } public String getName() { return this.name; } public void setName( String name ) { this.name = name; } public String getEmail() { return this.email; } public void setEmail( String email ) { this.email = email; } public User getUser() { return this.user; } public void setUser(User user) { this.user = user; } } package org.jaredstevens.jpatest.utils; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.Interceptor; public class EJBAnnotationProcessorInterceptor implements Interceptor { private static final long serialVersionUID = 1L; public void destroy() { } public void init() { } public String intercept(ActionInvocation ai) throws Exception { EJBAnnotationProcessor.process(ai.getAction()); return ai.invoke(); } } package org.jaredstevens.jpatest.utils; import java.lang.reflect.Field; import javax.ejb.EJB; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; public class EJBAnnotationProcessor { public static void process(Object instance)throws Exception{ Field[] fields = instance.getClass().getDeclaredFields(); if(fields != null && fields.length > 0){ EJB ejb; for(Field field : fields){ ejb = field.getAnnotation(EJB.class); if(ejb != null){ field.setAccessible(true); field.set(instance, EJBAnnotationProcessor.getEJB(ejb.mappedName())); } } } } private static Object getEJB(String mappedName) { Object retVal = null; String path = ""; Context cxt = null; String[] paths = {"cell/nodes/virgoNode01/servers/server1/","java:module/"}; for( int i=0; i < paths.length; ++i ) { try { path = paths[i]+mappedName; cxt = new InitialContext(); retVal = cxt.lookup(path); if(retVal != null) break; } catch (NamingException e) { retVal = null; } } return retVal; } } <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="basicstruts2" namespace="/diagnostics" extends="struts-default"> <interceptors> <interceptor name="ejbAnnotationProcessor" class="org.jaredstevens.jpatest.utils.EJBAnnotationProcessorInterceptor"/> <interceptor-stack name="baseStack"> <interceptor-ref name="defaultStack"/> <interceptor-ref name="ejbAnnotationProcessor"/> </interceptor-stack> </interceptors> <default-interceptor-ref name="baseStack"/> </package> <package name="restAPI" namespace="/conduit" extends="json-default"> <interceptors> <interceptor name="ejbAnnotationProcessor" class="org.jaredstevens.jpatest.utils.EJBAnnotationProcessorInterceptor" /> <interceptor-stack name="baseStack"> <interceptor-ref name="defaultStack" /> <interceptor-ref name="ejbAnnotationProcessor" /> </interceptor-stack> </interceptors> <default-interceptor-ref name="baseStack" /> <action name="UserAction.getUserById" class="org.jaredstevens.jpatest.actions.user.UserAction" method="getUserById"> <result type="json"> <param name="ignoreHierarchy">false</param> <param name="includeProperties"> ^user\.id, ^user\.name, ^user\.email </param> </result> <result name="error" type="json" /> </action> <action name="UserAction.save" class="org.jaredstevens.jpatest.actions.user.UserAction" method="save"> <result type="json"> <param name="ignoreHierarchy">false</param> <param name="includeProperties"> ^user\.id, ^user\.name, ^user\.email </param> </result> <result name="error" type="json" /> </action> </package> </struts> Stack Trace java.lang.NullPointerException org.jaredstevens.jpatest.actions.user.UserAction.save(UserAction.java:38) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37) java.lang.reflect.Method.invoke(Method.java:611) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:453) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:292) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:255) org.jaredstevens.jpatest.utils.EJBAnnotationProcessorInterceptor.intercept(EJBAnnotationProcessorInterceptor.java:21) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:211) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:211) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:90) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:192) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:511) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:188) com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:116) com.ibm.ws.webcontainer.filter.WebAppFilterChain._doFilter(WebAppFilterChain.java:77) com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:908) com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:997) com.ibm.ws.webcontainer.extension.DefaultExtensionProcessor.invokeFilters(DefaultExtensionProcessor.java:1062) com.ibm.ws.webcontainer.extension.DefaultExtensionProcessor.handleRequest(DefaultExtensionProcessor.java:982) com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3935) com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:276) com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:931) com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1583) com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:186) com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:452) com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:511) com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:305) com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:276) com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214) com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113) com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165) com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217) com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161) com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138) com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204) com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775) com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905) com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1604)

    Read the article

  • How to access struts interceptor parameters in Java?

    - by Ricardo
    I have the following code in struts.xml: <interceptor-ref name="checkTabsStack"> <param name="tabName">availability</param> </interceptor-ref> and I want to access the parameter tabName in the interceptor routine, how do i do that? i tried Map params = ActionContext.getContext().getParameters(); but params comes empty... Thanks!

    Read the article

  • NHibernate AssertException: Interceptor.OnPrepareStatement(SqlString) returned null or empty SqlString.

    - by jwynveen
    I am trying to switch a table from being a many-to-one mapping to being many-to-many with an intermediate mapping table. However, when I switched it over and tried to do a query on it with NHibernate, it's giving me this error: "Interceptor.OnPrepareStatement(SqlString) returned null or empty SqlString." My query was originally something more complex, but I switched it to a basic fetch all and I'm still having the problem: Session.QueryOver<T>().Future(); It would seem to either be a problem in my model mapping files or something in my database. Here are my model mappings: <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="GBI.Core" namespace="GBI.Core.Models"> <class name="Market" table="gbi_Market"> <id name="Id" column="MarketId"> <generator class="identity" /> </id> <property name="Name" /> <property name="Url" /> <property name="Description" type="StringClob" /> <property name="Rating" /> <property name="RatingComment" /> <property name="RatingCommentedOn" /> <many-to-one name="RatingCommentedBy" column="RatingCommentedBy" lazy="proxy"></many-to-one> <property name="ImageFilename" /> <property name="CreatedOn" /> <property name="ModifiedOn" /> <property name="IsDeleted" /> <many-to-one name="CreatedBy" column="CreatedBy" lazy="proxy"></many-to-one> <many-to-one name="ModifiedBy" column="ModifiedBy" lazy="proxy"></many-to-one> <set name="Content" where="IsDeleted=0 and ParentContentId is NULL" order-by="Ordering asc, CreatedOn asc, Name asc" lazy="extra"> <key column="MarketId" /> <one-to-many class="MarketContent" /> </set> <set name="FastFacts" where="IsDeleted=0" order-by="Ordering asc, CreatedOn asc, Name asc" lazy="extra"> <key column="MarketId" /> <one-to-many class="MarketFastFact" /> </set> <set name="NewsItems" table="gbi_NewsItem_Market_Map" lazy="true"> <key column="MarketId" /> <many-to-many class="NewsItem" fetch="join" column="NewsItemId" where="IsDeleted=0"/> </set> <!--<set name="MarketUpdates" table="gbi_Market_MarketUpdate_Map" lazy="extra"> <key column="MarketId" /> <many-to-many class="MarketUpdate" fetch="join" column="MarketUpdateId" where="IsDeleted=0" order-by="CreatedOn desc" /> </set>--> <set name="Documents" table="gbi_Market_Document_Map" lazy="true"> <key column="MarketId" /> <many-to-many class="Document" fetch="join" column="DocumentId" where="IsDeleted=0"/> </set> </class> <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="GBI.Core" namespace="GBI.Core.Models"> <class name="MarketUpdate" table="gbi_MarketUpdate"> <id name="Id" column="MarketUpdateId"> <generator class="identity" /> </id> <property name="Description" /> <property name="CreatedOn" /> <property name="ModifiedOn" /> <property name="IsDeleted" /> <!--<many-to-one name="Market" column="MarketId" lazy="proxy"></many-to-one>--> <set name="Comments" where="IsDeleted=0" order-by="CreatedOn desc" lazy="extra"> <key column="MarketUpdateId" /> <one-to-many class="MarketUpdateComment" /> </set> <many-to-one name="CreatedBy" column="CreatedBy" lazy="proxy"></many-to-one> <many-to-one name="ModifiedBy" column="ModifiedBy" lazy="proxy"></many-to-one> </class> <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="GBI.Core" namespace="GBI.Core.Models"> <class name="MarketUpdateMarketMap" table="gbi_Market_MarketUpdate_Map"> <id name="Id" column="MarketUpdateMarketMapId"> <generator class="identity" /> </id> <property name="CreatedOn" /> <property name="ModifiedOn" /> <property name="IsDeleted" /> <many-to-one name="CreatedBy" column="CreatedBy" lazy="proxy"></many-to-one> <many-to-one name="ModifiedBy" column="ModifiedBy" lazy="proxy"></many-to-one> <many-to-one name="MarketUpdate" column="MarketUpdateId" lazy="proxy"></many-to-one> <many-to-one name="Market" column="MarketId" lazy="proxy"></many-to-one> </class> As I mentioned, MarketUpdate was originally a many-to-one with Market (MarketId column is still in there, but I'm ignoring it. Could this be a problem?). But I've added in the Market_MarketUpdate_Map table to make it a many-to-many. I'm running in circles trying to figure out what this could be. I couldn't find any reference to this error when searching. And it doesn't provide much detail. Using: NHibernate 2.2 .NET 4.0 SQL Server 2005

    Read the article

  • Struts 2 TypeConversion problem

    - by Parhs
    Hello... i have a big problem... i have this map HashMap<Long, String> examValues; It gets populated by textboxes automatically with name="examValues[id]" Although i explicily defined the element as String , it doesnt care!!! I want everything to be a String... The result is to get a java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String when i try to System.out.print(examValues.get(examValue.getExam().getId()).getClass().getName()); INFO: java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String at gr.medilab.logic.action.exams.Exams.fill_edit(Exams.java:204) at gr.medilab.logic.action.exams.Exams.fill(Exams.java:95) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441) at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243) at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488) at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:277) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97) at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:332) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:233) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791) at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693) at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954) at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57) at com.sun.grizzly.ContextTask.run(ContextTask.java:69) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309) at java.lang.Thread.run(Thread.java:619) Any idea?

    Read the article

  • Problem implementing Interceptor pattern

    - by ph0enix
    I'm attempting to develop an Interceptor framework (in C#) where I can simply implement some interfaces, and through the use of some static initialization, register all my Interceptors with a common Dispatcher to be invoked at a later time. The problem lies in the fact that my Interceptor implementations are never actually referenced by my application so the static constructors never get called, and as a result, the Interceptors are never registered. If possible, I would like to keep all references to my Interceptor libraries out of my application, as this is my way of (hopefully) enforcing loose coupling across different modules. Hopefully this makes some sense. Let me know if there's anything I can clarify... Does anyone have any ideas, or perhaps a better way to go about implementing my Interceptor pattern? Update: I came across Spring.NET. I've heard of it before, but never really looked into it. It sounds like it has a lot of great features that would be very useful for what I'm trying to do. Does anyone have any experience with Spring.NET? TIA, Jeremy

    Read the article

  • Custom spring interceptor

    - by Hari
    Hi, I want to convert some of our internal API into a spring bean spring interceptor that we can use in other projects. This API needs some instantiation and other logic which I want to encapsulate in this bean so that we can just put the bean into our app context with necessary propoerties alone, and this will then apply the logic. I remember having read an article on this somewhere in the past - but cant find it now. Any pointers to something similar will be helpful EDIT: Sorry, I meant a spring interceptor, not a bean - my bad - please see my edit. I want to apply this interceptor to another bean dealing in XML messages.

    Read the article

  • Custom spring <strike>bean</strike> interceptor

    - by Hari
    Hi, I want to convert some of our internal API into a spring bean spring interceptor that we can use in other projects. This API needs some instantiation and other logic which I want to encapsulate in this bean so that we can just put the bean into our app context with necessary propoerties alone, and this will then apply the logic. I remember having read an article on this somewhere in the past - but cant find it now. Any pointers to something similar will be helpful EDIT: Sorry, I meant a spring interceptor, not a bean - my bad - please see my edit. I want to apply this interceptor to another bean dealing in XML messages.

    Read the article

  • Castle Interceptor Live Cycle and Memory Leak

    - by ktutnik
    Hello all, im new to castle dynamic proxy, and a bit curious.. when creating proxy of my object i save all the original value of its property on the interceptor (class scope) using dictionary and return the new value. now i wandering, when will this data get collected by GC?? can i control it or depends on the interceptor live cycle? Regards Kin

    Read the article

  • Bean is not instantiating while using hibernate interceptor

    - by amit sharma
    I am using hibernate interceptor with spring framework,but when i pass a bean reference of DAO class its not instantiating the bean. My interceptor class has: private IMyService myService; // and getters and setters while application-context.xml having entries: <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="entityInterceptor" ref="logInterceptor"></property> </bean> <bean name="logInterceptor" class="com.amit.project.Utility.TableLogInterceptor" > <property name="myService" ref="myService"/> </bean> <bean name="myService" class="com.amit.project.service.impl.MyService"> But my bean is not instantiating in class, showing null. entityInterceptor is not allowing to do that or anything else? plz suggest a way if anybody knows.

    Read the article

  • Spring WS & Validator interceptor

    - by mada
    I have a endpoint mapping a webservice which is used to insert in the dabatabase some keywords: @Transactional(readOnly = false,isolation= Isolation.SERIALIZABLE) public Source saveKW(...). The input is a request. I would like to add an interceptor on the method in order to validate the parameters. this one will read some values from the DB. i would like that this interceptor is EMBED in the transaction declared for the endpoint (or this opposite). In other words, i want them to be in the same transaction. Ideally im looking for something like this with annotation: @Transactional(readOnly = false,isolation= Isolation.SERIALIZABLE) @validator("KeyWordValidaor.class") public Source saveKW(...) where KeyWordValidaor will be class validating the parameters. Have you any idea or short examples to implements this like this way or in a other real way?

    Read the article

  • problem in interceptor executing before action in struts2

    - by vivmal
    Hi All, I am working on struts2. I have an interceptor that executes before my action claas. Now when I submit on a jsp page control goes to interceptor and after some processing there the control goes to action class. This complete flow is running well. But I found two things – 1) Control does not go to action-validation.xml before going to action class. 2) Its not getting the values of textfield or etc that uses has entered into jsp page before submitting. Can anyone tell me how to find solution for these two points. Thanks in advance.

    Read the article

1 2 3 4 5 6 7 8 9  | Next Page >