Search in sources :

Example 26 with InvocationManager

use of org.glassfish.api.invocation.InvocationManager in project Payara by payara.

the class AppTest method testCachingNamingObjectFactory.

@Test
public void testCachingNamingObjectFactory() {
    GlassfishNamingManagerImpl nm = null;
    try {
        InvocationManager im = new InvocationManagerImpl();
        InitialContext ic = newInitialContext();
        nm = new GlassfishNamingManagerImpl(ic);
        nm.publishObject("foo", "Hello: foo", false);
        System.out.println("**lookup() ==> " + ic.lookup("foo"));
        NamingObjectFactory factory = new NamingObjectFactory() {

            private int counter = 1;

            public boolean isCreateResultCacheable() {
                return true;
            }

            public Object create(Context ic) {
                return ("FACTORY_Created: " + counter++);
            }

            public String toString() {
                return "Huh? ";
            }
        };
        nm.publishObject("bar", factory, false);
        System.out.println("**lookup() ==> " + ic.lookup("bar"));
        System.out.println("**lookup() ==> " + ic.lookup("bar"));
        assert (true);
    } catch (Exception ex) {
        ex.printStackTrace();
        assert (false);
    } finally {
        try {
            nm.unpublishObject("foo");
            nm.unpublishObject("bar");
        } catch (Exception ex) {
        // ignore
        }
    }
}
Also used : InitialContext(javax.naming.InitialContext) Context(javax.naming.Context) InvocationManagerImpl(org.glassfish.api.invocation.InvocationManagerImpl) InvocationManager(org.glassfish.api.invocation.InvocationManager) NamingObjectFactory(com.sun.enterprise.naming.spi.NamingObjectFactory) InitialContext(javax.naming.InitialContext) NamingException(javax.naming.NamingException) InvocationException(org.glassfish.api.invocation.InvocationException)

Example 27 with InvocationManager

use of org.glassfish.api.invocation.InvocationManager in project Payara by payara.

the class AppTest method testEmptyJavaCompEnv.

@Test
public void testEmptyJavaCompEnv() {
    GlassfishNamingManagerImpl nm = null;
    InvocationManager im = new InvocationManagerImpl();
    ComponentInvocation inv = null;
    try {
        InitialContext ic = newInitialContext();
        triggerLoadingNamedProxies(ic);
        nm = new GlassfishNamingManagerImpl(ic);
        nm.setInvocationManager(im);
        inv = new ComponentInvocation("comp1", ComponentInvocation.ComponentInvocationType.EJB_INVOCATION, null, null, null);
        im.preInvoke(inv);
        nm.bindToComponentNamespace("app1", "mod1", "comp1", false, new ArrayList<Binding>());
        Context ctx = (Context) ic.lookup("java:comp/env");
        System.out.println("**lookup(java:comp/env) ==> " + ctx);
    } catch (javax.naming.NamingException nnfEx) {
        nnfEx.printStackTrace();
        assert (false);
    }
}
Also used : JNDIBinding(org.glassfish.api.naming.JNDIBinding) InitialContext(javax.naming.InitialContext) Context(javax.naming.Context) InvocationManagerImpl(org.glassfish.api.invocation.InvocationManagerImpl) ComponentInvocation(org.glassfish.api.invocation.ComponentInvocation) InvocationManager(org.glassfish.api.invocation.InvocationManager) NamingException(javax.naming.NamingException) InitialContext(javax.naming.InitialContext)

Example 28 with InvocationManager

use of org.glassfish.api.invocation.InvocationManager in project Payara by payara.

the class AppTest method testNonCachingNamingObjectFactory.

@Test
public void testNonCachingNamingObjectFactory() {
    GlassfishNamingManagerImpl nm = null;
    InvocationManager im = new InvocationManagerImpl();
    ComponentInvocation inv = null;
    try {
        InitialContext ic = newInitialContext();
        triggerLoadingNamedProxies(ic);
        nm = new GlassfishNamingManagerImpl(ic);
        nm.setInvocationManager(im);
        List<Binding> bindings = new ArrayList<Binding>();
        NamingObjectFactory intFactory = new NamingObjectFactory() {

            private int counter = 1;

            public boolean isCreateResultCacheable() {
                return false;
            }

            public Object create(Context ic) {
                return new Integer(++counter);
            }

            public String toString() {
                return "Huh? ";
            }
        };
        bindings.add(new Binding("conf/area", intFactory));
        bindings.add(new Binding("conf/location", "Santa Clara"));
        nm.bindToComponentNamespace("app1", "mod1", "comp1", false, bindings);
        inv = new ComponentInvocation("comp1", ComponentInvocation.ComponentInvocationType.EJB_INVOCATION, null, null, null);
        im.preInvoke(inv);
        System.out.println("**lookup(java:comp/env/conf/area) ==> " + ic.lookup("java:comp/env/conf/area"));
        System.out.println("**lookup(java:comp/env/conf/location) ==> " + ic.lookup("java:comp/env/conf/location"));
        NamingObjectFactory floatFactory = new NamingObjectFactory() {

            private int counter = 1;

            public boolean isCreateResultCacheable() {
                return false;
            }

            public Object create(Context ic) {
                return Float.valueOf(("7" + (++counter)) + "." + 2323);
            }

            public String toString() {
                return "Huh? ";
            }
        };
        List<Binding> bindings2 = new ArrayList<Binding>();
        bindings2.add(new Binding("conf/area", floatFactory));
        bindings2.add(new Binding("conf/location", "Santa Clara[14]"));
        nm.bindToComponentNamespace("app1", "mod1", "comp2", false, bindings2);
        inv = new ComponentInvocation("comp2", ComponentInvocation.ComponentInvocationType.EJB_INVOCATION, null, null, null);
        im.preInvoke(inv);
        System.out.println("**lookup(java:comp/env/conf/area) ==> " + ic.lookup("java:comp/env/conf/area"));
        System.out.println("**lookup(java:comp/env/conf/location) ==> " + ic.lookup("java:comp/env/conf/location"));
        assert (true);
    } catch (InvocationException inEx) {
        inEx.printStackTrace();
        assert (false);
    } catch (Exception ex) {
        ex.printStackTrace();
        assert (false);
    } finally {
        try {
            im.postInvoke(inv);
            nm.unbindComponentObjects("comp1");
        } catch (InvocationException inEx) {
        } catch (Exception ex) {
        }
    }
}
Also used : JNDIBinding(org.glassfish.api.naming.JNDIBinding) InitialContext(javax.naming.InitialContext) Context(javax.naming.Context) ComponentInvocation(org.glassfish.api.invocation.ComponentInvocation) InvocationManager(org.glassfish.api.invocation.InvocationManager) ArrayList(java.util.ArrayList) InitialContext(javax.naming.InitialContext) NamingException(javax.naming.NamingException) InvocationException(org.glassfish.api.invocation.InvocationException) InvocationManagerImpl(org.glassfish.api.invocation.InvocationManagerImpl) InvocationException(org.glassfish.api.invocation.InvocationException) NamingObjectFactory(com.sun.enterprise.naming.spi.NamingObjectFactory)

Example 29 with InvocationManager

use of org.glassfish.api.invocation.InvocationManager in project Payara by payara.

the class BulkheadInterceptor method intercept.

@AroundInvoke
public Object intercept(InvocationContext invocationContext) throws Exception {
    Object proceededInvocationContext = null;
    FaultToleranceService faultToleranceService = Globals.getDefaultBaseServiceLocator().getService(FaultToleranceService.class);
    InvocationManager invocationManager = Globals.getDefaultBaseServiceLocator().getService(InvocationManager.class);
    Config config = null;
    try {
        config = ConfigProvider.getConfig();
    } catch (IllegalArgumentException ex) {
        logger.log(Level.INFO, "No config could be found", ex);
    }
    try {
        String appName = faultToleranceService.getApplicationName(invocationManager, invocationContext);
        // Attempt to proceed the InvocationContext with Bulkhead semantics if Fault Tolerance is enabled
        if (faultToleranceService.isFaultToleranceEnabled(appName, config)) {
            logger.log(Level.FINER, "Proceeding invocation with bulkhead semantics");
            proceededInvocationContext = bulkhead(invocationContext);
        } else {
            // If fault tolerance isn't enabled, just proceed as normal
            logger.log(Level.FINE, "Fault Tolerance not enabled for {0}, proceeding normally without bulkhead.", faultToleranceService.getApplicationName(invocationManager, invocationContext));
            proceededInvocationContext = invocationContext.proceed();
        }
    } catch (Exception ex) {
        Retry retry = FaultToleranceCdiUtils.getAnnotation(beanManager, Retry.class, invocationContext);
        if (retry != null) {
            logger.log(Level.FINE, "Retry annotation found on method, propagating error upwards.");
            throw ex;
        } else {
            // If an exception was thrown, check if the method is annotated with @Fallback
            Fallback fallback = FaultToleranceCdiUtils.getAnnotation(beanManager, Fallback.class, invocationContext);
            // If the method was annotated with Fallback, attempt it, otherwise just propagate the exception upwards
            if (fallback != null) {
                logger.log(Level.FINE, "Fallback annotation found on method, and no Retry annotation - " + "falling back from Bulkhead");
                FallbackPolicy fallbackPolicy = new FallbackPolicy(fallback, config, invocationContext);
                proceededInvocationContext = fallbackPolicy.fallback(invocationContext);
            } else {
                logger.log(Level.FINE, "Fallback annotation not found on method, propagating error upwards.", ex);
                throw ex;
            }
        }
    }
    return proceededInvocationContext;
}
Also used : FallbackPolicy(fish.payara.microprofile.faulttolerance.interceptors.fallback.FallbackPolicy) Config(org.eclipse.microprofile.config.Config) InvocationManager(org.glassfish.api.invocation.InvocationManager) Fallback(org.eclipse.microprofile.faulttolerance.Fallback) Retry(org.eclipse.microprofile.faulttolerance.Retry) FaultToleranceService(fish.payara.microprofile.faulttolerance.FaultToleranceService) BulkheadException(org.eclipse.microprofile.faulttolerance.exceptions.BulkheadException) AroundInvoke(javax.interceptor.AroundInvoke)

Example 30 with InvocationManager

use of org.glassfish.api.invocation.InvocationManager in project Payara by payara.

the class CircuitBreakerInterceptor method circuitBreak.

private Object circuitBreak(InvocationContext invocationContext) throws Exception {
    Object proceededInvocationContext = null;
    FaultToleranceService faultToleranceService = Globals.getDefaultBaseServiceLocator().getService(FaultToleranceService.class);
    CircuitBreaker circuitBreaker = FaultToleranceCdiUtils.getAnnotation(beanManager, CircuitBreaker.class, invocationContext);
    Config config = null;
    try {
        config = ConfigProvider.getConfig();
    } catch (IllegalArgumentException ex) {
        logger.log(Level.INFO, "No config could be found", ex);
    }
    Class<? extends Throwable>[] failOn = circuitBreaker.failOn();
    try {
        String failOnString = ((String) FaultToleranceCdiUtils.getOverrideValue(config, Retry.class, "failOn", invocationContext, String.class).get());
        List<Class> classList = new ArrayList<>();
        // Remove any curly or square brackets from the string, as well as any spaces and ".class"es and loop
        for (String className : failOnString.replaceAll("[\\{\\[ \\]\\}]", "").replaceAll("\\.class", "").split(",")) {
            // Get a class object
            classList.add(Class.forName(className));
        }
        failOn = classList.toArray(failOn);
    } catch (NoSuchElementException nsee) {
        logger.log(Level.FINER, "Could not find element in config", nsee);
    } catch (ClassNotFoundException cnfe) {
        logger.log(Level.INFO, "Could not find class from failOn config, defaulting to annotation. " + "Make sure you give the full canonical class name.", cnfe);
    }
    long delay = (Long) FaultToleranceCdiUtils.getOverrideValue(config, CircuitBreaker.class, "value", invocationContext, Long.class).orElse(circuitBreaker.delay());
    ChronoUnit delayUnit = (ChronoUnit) FaultToleranceCdiUtils.getOverrideValue(config, CircuitBreaker.class, "delayUnit", invocationContext, ChronoUnit.class).orElse(circuitBreaker.delayUnit());
    int requestVolumeThreshold = (Integer) FaultToleranceCdiUtils.getOverrideValue(config, CircuitBreaker.class, "requestVolumeThreshold", invocationContext, Integer.class).orElse(circuitBreaker.requestVolumeThreshold());
    double failureRatio = (Double) FaultToleranceCdiUtils.getOverrideValue(config, CircuitBreaker.class, "failureRatio", invocationContext, Double.class).orElse(circuitBreaker.failureRatio());
    int successThreshold = (Integer) FaultToleranceCdiUtils.getOverrideValue(config, CircuitBreaker.class, "successThreshold", invocationContext, Integer.class).orElse(circuitBreaker.successThreshold());
    long delayMillis = Duration.of(delay, delayUnit).toMillis();
    InvocationManager invocationManager = Globals.getDefaultBaseServiceLocator().getService(InvocationManager.class);
    CircuitBreakerState circuitBreakerState = faultToleranceService.getCircuitBreakerState(faultToleranceService.getApplicationName(invocationManager, invocationContext), invocationContext.getMethod(), circuitBreaker);
    switch(circuitBreakerState.getCircuitState()) {
        case OPEN:
            logger.log(Level.FINER, "CircuitBreaker is Open, throwing exception");
            // If open, immediately throw an error
            throw new CircuitBreakerOpenException("CircuitBreaker for method " + invocationContext.getMethod().getName() + "is in state OPEN.");
        case CLOSED:
            // If closed, attempt to proceed the invocation context
            try {
                logger.log(Level.FINER, "Proceeding CircuitBreaker context");
                proceededInvocationContext = invocationContext.proceed();
            } catch (Exception ex) {
                logger.log(Level.FINE, "Exception executing CircuitBreaker context");
                // Check if the exception is something that should record a failure
                if (shouldFail(failOn, ex)) {
                    logger.log(Level.FINE, "Caught exception is included in CircuitBreaker failOn, " + "recording failure against CircuitBreaker");
                    // Add a failure result to the queue
                    circuitBreakerState.recordClosedResult(Boolean.FALSE);
                    // Calculate the failure threshold
                    long failureThreshold = Math.round(requestVolumeThreshold * failureRatio);
                    // If we're over the failure threshold, open the circuit
                    if (circuitBreakerState.isOverFailureThreshold(failureThreshold)) {
                        logger.log(Level.FINE, "CircuitBreaker is over failure threshold {0}, opening circuit", failureThreshold);
                        circuitBreakerState.setCircuitState(CircuitBreakerState.CircuitState.OPEN);
                        // Kick off a thread that will half-open the circuit after the specified delay
                        scheduleHalfOpen(delayMillis, circuitBreakerState);
                    }
                }
                // Finally, propagate the error upwards
                throw ex;
            }
            // If everything is bon, just add a success value
            circuitBreakerState.recordClosedResult(Boolean.TRUE);
            break;
        case HALF_OPEN:
            // If half-open, attempt to proceed the invocation context
            try {
                logger.log(Level.FINER, "Proceeding half open CircuitBreaker context");
                proceededInvocationContext = invocationContext.proceed();
            } catch (Exception ex) {
                logger.log(Level.FINE, "Exception executing CircuitBreaker context");
                // Check if the exception is something that should record a failure
                if (shouldFail(failOn, ex)) {
                    logger.log(Level.FINE, "Caught exception is included in CircuitBreaker failOn, " + "reopening half open circuit");
                    // Open the circuit again, and reset the half-open result counter
                    circuitBreakerState.setCircuitState(CircuitBreakerState.CircuitState.OPEN);
                    circuitBreakerState.resetHalfOpenSuccessfulResultCounter();
                    scheduleHalfOpen(delayMillis, circuitBreakerState);
                }
                throw ex;
            }
            // If the invocation context hasn't thrown an error, record a success
            circuitBreakerState.incrementHalfOpenSuccessfulResultCounter();
            logger.log(Level.FINER, "Number of consecutive successful circuitbreaker executions = {0}", circuitBreakerState.getHalfOpenSuccessFulResultCounter());
            // If we've hit the success threshold, close the circuit
            if (circuitBreakerState.getHalfOpenSuccessFulResultCounter() == successThreshold) {
                logger.log(Level.FINE, "Number of consecutive successful CircuitBreaker executions is above " + "threshold {0}, closing circuit", successThreshold);
                circuitBreakerState.setCircuitState(CircuitBreakerState.CircuitState.CLOSED);
                // Reset the counter for when we next need to use it
                circuitBreakerState.resetHalfOpenSuccessfulResultCounter();
                // Reset the rolling results window
                circuitBreakerState.resetResults();
            }
            break;
    }
    return proceededInvocationContext;
}
Also used : CircuitBreaker(org.eclipse.microprofile.faulttolerance.CircuitBreaker) Config(org.eclipse.microprofile.config.Config) CircuitBreakerState(fish.payara.microprofile.faulttolerance.state.CircuitBreakerState) ArrayList(java.util.ArrayList) InvocationManager(org.glassfish.api.invocation.InvocationManager) CircuitBreakerOpenException(org.eclipse.microprofile.faulttolerance.exceptions.CircuitBreakerOpenException) FaultToleranceService(fish.payara.microprofile.faulttolerance.FaultToleranceService) NamingException(javax.naming.NamingException) NoSuchElementException(java.util.NoSuchElementException) CircuitBreakerOpenException(org.eclipse.microprofile.faulttolerance.exceptions.CircuitBreakerOpenException) Retry(org.eclipse.microprofile.faulttolerance.Retry) NoSuchElementException(java.util.NoSuchElementException) ChronoUnit(java.time.temporal.ChronoUnit)

Aggregations

InvocationManager (org.glassfish.api.invocation.InvocationManager)40 ComponentInvocation (org.glassfish.api.invocation.ComponentInvocation)13 FaultToleranceService (fish.payara.microprofile.faulttolerance.FaultToleranceService)9 NamingException (javax.naming.NamingException)9 Config (org.eclipse.microprofile.config.Config)8 InvocationException (org.glassfish.api.invocation.InvocationException)7 FallbackPolicy (fish.payara.microprofile.faulttolerance.interceptors.fallback.FallbackPolicy)5 AroundInvoke (javax.interceptor.AroundInvoke)5 Fallback (org.eclipse.microprofile.faulttolerance.Fallback)5 Retry (org.eclipse.microprofile.faulttolerance.Retry)5 ServiceLocator (org.glassfish.hk2.api.ServiceLocator)5 PoolingException (com.sun.appserv.connectors.internal.api.PoolingException)4 ArrayList (java.util.ArrayList)4 NoSuchElementException (java.util.NoSuchElementException)4 EJBInvocation (org.glassfish.ejb.api.EJBInvocation)4 JavaEETransactionManager (com.sun.enterprise.transaction.api.JavaEETransactionManager)3 RequestTraceSpan (fish.payara.notification.requesttracing.RequestTraceSpan)3 Method (java.lang.reflect.Method)3 Context (javax.naming.Context)3 InitialContext (javax.naming.InitialContext)3