repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/EJBSecurityMetaData.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Set; import org.jboss.as.ee.component.ComponentConfiguration; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.component.EJBComponentDescription; import org.jboss.metadata.javaee.spec.SecurityRolesMetaData; /** * Holds the Jakarta Enterprise Beans component level security metadata. * <p/> * For per method specific security metadata, take a look at {@link EJBMethodSecurityAttribute} * <p/> * User: Jaikiran Pai */ public class EJBSecurityMetaData { /** * The security domain for this Jakarta Enterprise Beans component */ private final String securityDomainName; /** * The run-as role (if any) for this Jakarta Enterprise Beans component */ private final String runAsRole; /** * The roles declared (via @DeclareRoles) on this Jakarta Enterprise Beans component */ private final Set<String> declaredRoles; /** * The run-as principal (if any) for this Jakarta Enterprise Beans component */ private final String runAsPrincipal; /** * Roles mapped with security-role */ private final SecurityRolesMetaData securityRoles; /** * Security role links. The key is the "from" role name and the value is a collection of "to" role names of the link. */ private final Map<String, Collection<String>> securityRoleLinks; /** * @param componentConfiguration Component configuration of the Jakarta Enterprise Beans component */ public EJBSecurityMetaData(final ComponentConfiguration componentConfiguration) { if (componentConfiguration.getComponentDescription() instanceof EJBComponentDescription == false) { throw EjbLogger.ROOT_LOGGER.invalidComponentConfiguration(componentConfiguration.getComponentName()); } final EJBComponentDescription ejbComponentDescription = (EJBComponentDescription) componentConfiguration.getComponentDescription(); this.runAsRole = ejbComponentDescription.getRunAs(); this.securityDomainName = ejbComponentDescription.getResolvedSecurityDomain(); this.runAsPrincipal = ejbComponentDescription.getRunAsPrincipal(); this.securityRoles = ejbComponentDescription.getSecurityRoles(); final Map<String, Collection<String>> links = ejbComponentDescription.getSecurityRoleLinks(); // security role links configured via <security-role-ref> this.securityRoleLinks = links == null ? Collections.<String, Collection<String>>emptyMap() : Collections.unmodifiableMap(links); // @DeclareRoles final Set<String> roles = ejbComponentDescription.getDeclaredRoles(); this.declaredRoles = roles == null ? Collections.<String>emptySet() : Collections.unmodifiableSet(roles); } /** * Returns the roles that have been declared by the bean. Returns an empty set if there are no declared roles. * * @return */ public Set<String> getDeclaredRoles() { return declaredRoles; } /** * Returns the run-as role associated with this bean. Returns null if there's no run-as role associated. * * @return */ public String getRunAs() { return this.runAsRole; } /** * Returns the security domain associated with the bean * * @return */ public String getSecurityDomainName() { return this.securityDomainName; } /** * Returns the run-as principal associated with this bean. Returns 'anonymous' if no principal was set. * * @return */ public String getRunAsPrincipal() { return runAsPrincipal; } /** * Returns the security-role mapping. * * @return */ public SecurityRolesMetaData getSecurityRoles() { return securityRoles; } /** * Returns the security role links (configured via <security-role-ref>) applicable for the * Jakarta Enterprise Beans. Returns an empty map if no role links are configured * * @return */ public Map<String, Collection<String>> getSecurityRoleLinks() { return this.securityRoleLinks; } }
5,281
34.449664
139
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/SecurityDomainInterceptor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security; import org.jboss.invocation.Interceptor; import org.jboss.invocation.InterceptorContext; import org.wildfly.security.auth.server.SecurityDomain; /** * An interceptor which sets the security domain of the invocation. * * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ final class SecurityDomainInterceptor implements Interceptor { private final SecurityDomain securityDomain; SecurityDomainInterceptor(final SecurityDomain securityDomain) { this.securityDomain = securityDomain; } public Object processInvocation(final InterceptorContext context) throws Exception { final SecurityDomain oldDomain = context.putPrivateData(SecurityDomain.class, securityDomain); try { return context.proceed(); } finally { context.putPrivateData(SecurityDomain.class, oldDomain); } } }
1,942
37.86
102
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/PolicyContextIdInterceptor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security; import jakarta.security.jacc.PolicyContext; import org.jboss.invocation.Interceptor; import org.jboss.invocation.InterceptorContext; import org.wildfly.security.ParametricPrivilegedAction; import org.wildfly.security.manager.WildFlySecurityManager; /** * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ public class PolicyContextIdInterceptor implements Interceptor { private final String policyContextID; public PolicyContextIdInterceptor(final String policyContextID) { this.policyContextID = policyContextID; } public Object processInvocation(final InterceptorContext context) throws Exception { final String oldId = PolicyContext.getContextID(); setContextID(policyContextID); try { return context.proceed(); } finally { setContextID(oldId); } } private static void setContextID(final String contextID) { WildFlySecurityManager.doPrivilegedWithParameter(contextID, (ParametricPrivilegedAction<Void, String>) PolicyContextIdInterceptor::doSetContextID); } private static Void doSetContextID(final String policyContextID) { PolicyContext.setContextID(policyContextID); return null; } }
2,311
36.901639
155
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/RoleAddingInterceptor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security; import java.security.PrivilegedActionException; import org.jboss.invocation.Interceptor; import org.jboss.invocation.InterceptorContext; import org.wildfly.common.Assert; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.auth.server.SecurityIdentity; import org.wildfly.security.authz.RoleMapper; /** * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ public class RoleAddingInterceptor implements Interceptor { private final String category; private final RoleMapper roleMapper; public RoleAddingInterceptor(final String category, final RoleMapper roleMapper) { this.category = category; this.roleMapper = roleMapper; } public Object processInvocation(final InterceptorContext context) throws Exception { final SecurityDomain securityDomain = context.getPrivateData(SecurityDomain.class); Assert.checkNotNullParam("securityDomain", securityDomain); final SecurityIdentity currentIdentity = securityDomain.getCurrentSecurityIdentity(); final RoleMapper mergeMapper = roleMapper.or((roles) -> currentIdentity.getRoles(category)); final SecurityIdentity newIdentity = currentIdentity.withRoleMapper(category, mergeMapper); try { return newIdentity.runAs(context); } catch (PrivilegedActionException e) { Throwable cause = e.getCause(); if(cause != null) { if(cause instanceof Exception) { throw (Exception) cause; } else { throw new RuntimeException(e); } } else { throw e; } } } }
2,770
39.75
100
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/IdentityOutflowInterceptor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security; import java.util.Set; import java.util.function.Function; import org.jboss.invocation.Interceptor; import org.jboss.invocation.InterceptorContext; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.auth.server.SecurityIdentity; import org.wildfly.security.authz.RoleMapper; /** * @author <a href="mailto:[email protected]">Farah Juma</a> */ final class IdentityOutflowInterceptor implements Interceptor { private final Function<SecurityIdentity, Set<SecurityIdentity>> identityOutflowFunction; private final String category; private final RoleMapper roleMapper; IdentityOutflowInterceptor(final Function<SecurityIdentity, Set<SecurityIdentity>> identityOutflowFunction) { this(identityOutflowFunction, null, null); } IdentityOutflowInterceptor(final Function<SecurityIdentity, Set<SecurityIdentity>> identityOutflowFunction, final String category, final RoleMapper roleMapper) { this.identityOutflowFunction = identityOutflowFunction; this.category = category; this.roleMapper = roleMapper; } public Object processInvocation(final InterceptorContext context) throws Exception { if (identityOutflowFunction != null) { final SecurityDomain securityDomain = context.getPrivateData(SecurityDomain.class); final SecurityIdentity currentIdentity = securityDomain.getCurrentSecurityIdentity(); Set<SecurityIdentity> outflowedIdentities = identityOutflowFunction.apply(currentIdentity); SecurityIdentity[] newIdentities; if (category != null && roleMapper != null) { // Propagate the runAsRole or any extra principal roles that are configured // (TODO: ensure this is the desired behaviour) newIdentities = outflowedIdentities.stream().map(outflowedIdentity -> { final RoleMapper mergeMapper = roleMapper.or((roles) -> outflowedIdentity.getRoles(category)); return outflowedIdentity.withRoleMapper(category, mergeMapper); }).toArray(SecurityIdentity[]::new); } else { newIdentities = outflowedIdentities.toArray(new SecurityIdentity[outflowedIdentities.size()]); } return SecurityIdentity.runAsAll(context, newIdentities); } else { return context.proceed(); } } }
3,503
44.506494
165
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/ApplicationSecurityDomainConfig.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security; import java.util.Objects; /** * @author <a href="mailto:[email protected]">Pedro Igor</a> */ public class ApplicationSecurityDomainConfig { private String name; private boolean enableJacc; private boolean legacyCompliantPrincipalPropagation; public ApplicationSecurityDomainConfig(String name, boolean enableJacc, boolean legacyCompliantPrincipalPropagation) { this.name = name; this.enableJacc = enableJacc; this.legacyCompliantPrincipalPropagation = legacyCompliantPrincipalPropagation; } public boolean isSameDomain(String other) { return name.equals(other); } public boolean isEnableJacc() { return enableJacc; } public boolean isLegacyCompliantPrincipalPropagation() { return legacyCompliantPrincipalPropagation; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ApplicationSecurityDomainConfig that = (ApplicationSecurityDomainConfig) o; return Objects.equals(name, that.name); } @Override public int hashCode() { return Objects.hash(name); } }
2,261
32.761194
122
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/EJBMethodSecurityAttribute.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security; import org.jboss.as.ejb3.logging.EjbLogger; import java.util.Collections; import java.util.Set; /** * Holds security metadata of a method corresponding to an Jakarta Enterprise Beans's view. * <p/> * For security metadata that's applicable at Jakarta Enterprise Beans component level (for ex: security domain) take a look at {@link EJBSecurityMetaData} * <p/> * User: Jaikiran Pai */ public class EJBMethodSecurityAttribute { public static final EJBMethodSecurityAttribute PERMIT_ALL = new EJBMethodSecurityAttribute(true, false, Collections.<String>emptySet()); public static final EJBMethodSecurityAttribute DENY_ALL = new EJBMethodSecurityAttribute(false, true, Collections.<String>emptySet()); public static final EJBMethodSecurityAttribute NONE = new EJBMethodSecurityAttribute(false, false, Collections.<String>emptySet()); private final boolean permitAll; private final boolean denyAll; private final Set<String> rolesAllowed; private EJBMethodSecurityAttribute(final boolean permitAll, final boolean denyAll, final Set<String> rolesAllowed) { if (rolesAllowed == null) throw EjbLogger.ROOT_LOGGER.paramCannotBeNull("rolesAllowed"); this.permitAll = permitAll; this.denyAll = denyAll; this.rolesAllowed = rolesAllowed; } public static EJBMethodSecurityAttribute none() { return NONE; } public static EJBMethodSecurityAttribute permitAll() { return PERMIT_ALL; } public static EJBMethodSecurityAttribute denyAll() { return DENY_ALL; } public static EJBMethodSecurityAttribute rolesAllowed(final Set<String> roles) { return new EJBMethodSecurityAttribute(false, false, roles); } public boolean isPermitAll() { return permitAll; } public boolean isDenyAll() { return denyAll; } public Set<String> getRolesAllowed() { return rolesAllowed; } }
3,014
34.892857
155
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/service/EJBViewMethodSecurityAttributesService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security.service; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Map; import org.jboss.as.ejb3.security.EJBMethodSecurityAttribute; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; /** * A {@link Service} which can be used by other components like WS to get the security metadata associated with methods on an Jakarta Enterprise Beans view. * * @author: Jaikiran Pai * @see https://issues.jboss.org/browse/WFLY-308 for more details. */ public class EJBViewMethodSecurityAttributesService implements Service<EJBViewMethodSecurityAttributesService> { private static final ServiceName BASE_SERVICE_NAME = ServiceName.JBOSS.append("ejb").append("view-method-security-attributes"); private final Map<Method, EJBMethodSecurityAttribute> methodSecurityAttributes; public EJBViewMethodSecurityAttributesService(final Map<Method, EJBMethodSecurityAttribute> securityAttributes) { this.methodSecurityAttributes = Collections.unmodifiableMap(new HashMap<>(securityAttributes)); } @Override public void start(StartContext startContext) throws StartException { } @Override public void stop(StopContext stopContext) { } @Override public EJBViewMethodSecurityAttributesService getValue() throws IllegalStateException, IllegalArgumentException { return this; } /** * Returns the {@link EJBMethodSecurityAttribute} associated with the passed view method. This method returns null if no security attribute is applicable for the passed method * * @param viewMethod * @return */ public EJBMethodSecurityAttribute getSecurityAttributes(final Method viewMethod) { return methodSecurityAttributes.get(viewMethod); } /** * Returns a {@link ServiceName} for the {@link EJBViewMethodSecurityAttributesService} * * @param appName The application name to which the bean belongs. Can be null if the bean is <b>not</b> deployed in a .ear * @param moduleName The module name to which the bean belongs * @param beanName The bean name * @param viewClassName The fully qualified class name of the EJB view * @return */ public static ServiceName getServiceName(final String appName, final String moduleName, final String beanName, final String viewClassName) { final ServiceName serviceName; if (appName != null) { serviceName = BASE_SERVICE_NAME.append(appName); } else { serviceName = BASE_SERVICE_NAME; } return serviceName.append(moduleName).append(beanName).append(viewClassName); } public static class Builder { private final Map<Method, EJBMethodSecurityAttribute> methodSecurityAttributes = new IdentityHashMap<>(); public void addMethodSecurityMetadata(final Method viewMethod, final EJBMethodSecurityAttribute securityAttribute) { methodSecurityAttributes.put(viewMethod, securityAttribute); } public EJBViewMethodSecurityAttributesService build() { return new EJBViewMethodSecurityAttributesService(methodSecurityAttributes); } } }
4,446
40.175926
179
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/parser/EJBBoundSecurityMetaDataParser20.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security.parser; import org.jboss.as.ejb3.security.metadata.EJBBoundSecurityMetaData; import org.jboss.metadata.ejb.parser.jboss.ejb3.AbstractEJBBoundMetaDataParser; import org.jboss.metadata.property.PropertyReplacer; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; /** * Parses 2.0 version of urn:security namespace. * * @author Emmanuel Hugonnet (c) 2022 Red Hat, Inc. */ public class EJBBoundSecurityMetaDataParser20 extends AbstractEJBBoundMetaDataParser<EJBBoundSecurityMetaData> { public static final EJBBoundSecurityMetaDataParser20 INSTANCE = new EJBBoundSecurityMetaDataParser20(); public static final String NAMESPACE_URI_2_0 = "urn:security:2.0"; protected EJBBoundSecurityMetaDataParser20() { } @Override public EJBBoundSecurityMetaData parse(XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException { EJBBoundSecurityMetaData metaData = new EJBBoundSecurityMetaData(); processElements(metaData, reader, propertyReplacer); return metaData; } @Override protected void processElement(EJBBoundSecurityMetaData metaData, XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException { if (reader.getNamespaceURI().equals(NAMESPACE_URI_2_0)) { final String localName = reader.getLocalName(); switch (localName) { case "security-domain": metaData.setSecurityDomain(getElementText(reader, propertyReplacer)); break; case "run-as-principal": metaData.setRunAsPrincipal(getElementText(reader, propertyReplacer)); break; case "missing-method-permissions-deny-access": final String val = getElementText(reader, propertyReplacer); metaData.setMissingMethodPermissionsDenyAccess(Boolean.valueOf(val.trim())); break; default: throw unexpectedElement(reader); } } else { super.processElement(metaData, reader, propertyReplacer); } } }
3,257
40.769231
161
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/parser/SecurityRoleMetaDataParser.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security.parser; import java.util.HashSet; import java.util.Set; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.jboss.metadata.ejb.parser.spec.AbstractMetaDataParser; import org.jboss.metadata.javaee.spec.SecurityRoleMetaData; import org.jboss.metadata.parser.ee.Element; import org.jboss.metadata.property.PropertyReplacer; /** * Parser for security-role elements * * @author <a href="mailto:[email protected]">Marcus Moyses</a> */ public class SecurityRoleMetaDataParser extends AbstractMetaDataParser<SecurityRoleMetaData> { public static final String LEGACY_NAMESPACE_URI = "urn:security-role"; public static final String NAMESPACE_URI_1_0 = "urn:security-role:1.0"; public static final String NAMESPACE_URI_2_0 = "urn:security-role:2.0"; public static final SecurityRoleMetaDataParser INSTANCE = new SecurityRoleMetaDataParser(); private SecurityRoleMetaDataParser() { } @Override public SecurityRoleMetaData parse(XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException { SecurityRoleMetaData metaData = new SecurityRoleMetaData(); processElements(metaData, reader, propertyReplacer); return metaData; } @Override protected void processElement(SecurityRoleMetaData metaData, XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException { if (LEGACY_NAMESPACE_URI.equals(reader.getNamespaceURI()) || NAMESPACE_URI_2_0.equals(reader.getNamespaceURI()) || NAMESPACE_URI_1_0.equals(reader.getNamespaceURI())) { final String localName = reader.getLocalName(); if (localName.equals(Element.ROLE_NAME.getLocalName())) { metaData.setRoleName(getElementText(reader, propertyReplacer)); } else if (localName.equals(Element.PRINCIPAL_NAME.getLocalName())) { Set<String> principalNames = metaData.getPrincipals(); if (principalNames == null) { principalNames = new HashSet<String>(); metaData.setPrincipals(principalNames); } principalNames.add(getElementText(reader, propertyReplacer)); } else throw unexpectedElement(reader); } else { super.processElement(metaData, reader, propertyReplacer); } } }
3,510
41.301205
157
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/parser/EJBBoundSecurityMetaDataParser11.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security.parser; import org.jboss.as.ejb3.security.metadata.EJBBoundSecurityMetaData; import org.jboss.metadata.ejb.parser.jboss.ejb3.AbstractEJBBoundMetaDataParser; import org.jboss.metadata.property.PropertyReplacer; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; /** * Parses 1.1 version of urn:security namespace * * @author Jaikiran Pai */ public class EJBBoundSecurityMetaDataParser11 extends AbstractEJBBoundMetaDataParser<EJBBoundSecurityMetaData> { public static final EJBBoundSecurityMetaDataParser11 INSTANCE = new EJBBoundSecurityMetaDataParser11(); public static final String NAMESPACE_URI_1_1 = "urn:security:1.1"; protected EJBBoundSecurityMetaDataParser11() { } @Override public EJBBoundSecurityMetaData parse(XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException { EJBBoundSecurityMetaData metaData = new EJBBoundSecurityMetaData(); processElements(metaData, reader, propertyReplacer); return metaData; } @Override protected void processElement(EJBBoundSecurityMetaData metaData, XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException { if (reader.getNamespaceURI().equals(NAMESPACE_URI_1_1)) { final String localName = reader.getLocalName(); if (localName.equals("security-domain")) { metaData.setSecurityDomain(getElementText(reader, propertyReplacer)); } else if (localName.equals("run-as-principal")) { metaData.setRunAsPrincipal(getElementText(reader, propertyReplacer)); } else if (localName.equals("missing-method-permissions-deny-access")) { final String val = getElementText(reader, propertyReplacer); metaData.setMissingMethodPermissionsDenyAccess(Boolean.parseBoolean(val.trim())); } else { throw unexpectedElement(reader); } } else { super.processElement(metaData, reader, propertyReplacer); } } }
3,154
41.635135
161
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/parser/EJBBoundSecurityMetaDataParser.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security.parser; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.jboss.as.ejb3.security.metadata.EJBBoundSecurityMetaData; import org.jboss.metadata.ejb.parser.jboss.ejb3.AbstractEJBBoundMetaDataParser; import org.jboss.metadata.property.PropertyReplacer; /** * Parser for EJBBoundSecurityMetaData components. * * @author <a href="mailto:[email protected]">Marcus Moyses</a> */ public class EJBBoundSecurityMetaDataParser extends AbstractEJBBoundMetaDataParser<EJBBoundSecurityMetaData> { public static final String LEGACY_NAMESPACE_URI = "urn:security"; public static final String NAMESPACE_URI_1_0 = "urn:security:1.0"; public static final EJBBoundSecurityMetaDataParser INSTANCE = new EJBBoundSecurityMetaDataParser(); protected EJBBoundSecurityMetaDataParser() { } @Override public EJBBoundSecurityMetaData parse(XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException { EJBBoundSecurityMetaData metaData = new EJBBoundSecurityMetaData(); processElements(metaData, reader, propertyReplacer); return metaData; } @Override protected void processElement(EJBBoundSecurityMetaData metaData, XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException { if (reader.getNamespaceURI().equals(LEGACY_NAMESPACE_URI) || reader.getNamespaceURI().equals(NAMESPACE_URI_1_0)) { final String localName = reader.getLocalName(); if (localName.equals("security-domain")) metaData.setSecurityDomain(getElementText(reader, propertyReplacer)); else if (localName.equals("run-as-principal")) metaData.setRunAsPrincipal(getElementText(reader, propertyReplacer)); else throw unexpectedElement(reader); } else { super.processElement(metaData, reader, propertyReplacer); } } }
3,049
41.361111
161
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/security/metadata/EJBBoundSecurityMetaData.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.security.metadata; import org.jboss.metadata.ejb.parser.jboss.ejb3.AbstractEJBBoundMetaData; /** * Metadata for security related information of EJB components * * @author <a href="mailto:[email protected]">Marcus Moyses</a> */ public class EJBBoundSecurityMetaData extends AbstractEJBBoundMetaData { private static final long serialVersionUID = 1350796966752920231L; private String securityDomain; private String runAsPrincipal; private Boolean missingMethodPermissionsDenyAccess; public String getSecurityDomain() { return securityDomain; } public void setSecurityDomain(String securityDomain) { this.securityDomain = securityDomain; } public String getRunAsPrincipal() { return runAsPrincipal; } public void setRunAsPrincipal(String runAsPrincipal) { this.runAsPrincipal = runAsPrincipal; } public Boolean getMissingMethodPermissionsDenyAccess() { return this.missingMethodPermissionsDenyAccess; } public void setMissingMethodPermissionsDenyAccess(Boolean missingMethodPermissionsDenyAccess) { this.missingMethodPermissionsDenyAccess = missingMethodPermissionsDenyAccess; } }
2,257
33.212121
99
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/interceptor/ContainerInterceptorsParser.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.interceptor; import org.jboss.metadata.ejb.parser.spec.AbstractMetaDataParser; import org.jboss.metadata.ejb.parser.spec.InterceptorBindingMetaDataParser; import org.jboss.metadata.ejb.spec.InterceptorBindingMetaData; import org.jboss.metadata.property.PropertyReplacer; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; /** * Responsible for parsing the <code>container-interceptors</code> in jboss-ejb3.xml * * @author Jaikiran Pai */ public class ContainerInterceptorsParser extends AbstractMetaDataParser<ContainerInterceptorsMetaData> { public static final ContainerInterceptorsParser INSTANCE = new ContainerInterceptorsParser(); public static final String NAMESPACE_URI_1_0 = "urn:container-interceptors:1.0"; public static final String NAMESPACE_URI_2_0 = "urn:container-interceptors:2.0"; private static final String ELEMENT_CONTAINER_INTERCEPTORS = "container-interceptors"; private static final String ELEMENT_INTERCEPTOR_BINDING = "interceptor-binding"; @Override public ContainerInterceptorsMetaData parse(XMLStreamReader reader, PropertyReplacer propertyReplacer) throws XMLStreamException { // make sure it's the right namespace if (!NAMESPACE_URI_1_0.equals(reader.getNamespaceURI()) && !NAMESPACE_URI_2_0.equals(reader.getNamespaceURI())) { throw unexpectedElement(reader); } // only process relevant elements if (!reader.getLocalName().equals(ELEMENT_CONTAINER_INTERCEPTORS)) { throw unexpectedElement(reader); } final ContainerInterceptorsMetaData metaData = new ContainerInterceptorsMetaData(); processElements(metaData, reader, propertyReplacer); return metaData; } @Override protected void processElement(final ContainerInterceptorsMetaData containerInterceptorsMetadata, final XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException { final String localName = reader.getLocalName(); if (!localName.equals(ELEMENT_INTERCEPTOR_BINDING)) { throw unexpectedElement(reader); } // parse the interceptor-binding final InterceptorBindingMetaData interceptorBinding = this.readInterceptorBinding(reader, propertyReplacer); // add the interceptor binding to the container interceptor metadata containerInterceptorsMetadata.addInterceptorBinding(interceptorBinding); } /** * Parses the <code>interceptor-binding</code> element and returns the corresponding {@link InterceptorBindingMetaData} * * @param reader * @param propertyReplacer * @return * @throws XMLStreamException */ private InterceptorBindingMetaData readInterceptorBinding(final XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException { return InterceptorBindingMetaDataParser.INSTANCE.parse(reader, propertyReplacer); } }
4,029
45.321839
199
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/interceptor/ContainerInterceptorsMetaData.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.interceptor; import org.jboss.metadata.ejb.spec.InterceptorBindingMetaData; import org.jboss.metadata.ejb.spec.InterceptorBindingsMetaData; /** * Holds the interceptor bindings information configured within a <code>container-interceptors</code> * element of jboss-ejb3.xml * * @author Jaikiran Pai */ public class ContainerInterceptorsMetaData { private final InterceptorBindingsMetaData interceptorBindings = new InterceptorBindingsMetaData(); public InterceptorBindingsMetaData getInterceptorBindings() { return this.interceptorBindings; } void addInterceptorBinding(final InterceptorBindingMetaData interceptorBinding) { this.interceptorBindings.add(interceptorBinding); } }
1,774
37.586957
102
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/interceptor/server/ServerInterceptorCache.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.interceptor.server; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import jakarta.interceptor.AroundInvoke; import jakarta.interceptor.AroundTimeout; import jakarta.interceptor.InvocationContext; import org.jboss.as.ee.logging.EeLogger; import org.jboss.as.ee.utils.ClassLoadingUtils; import org.jboss.as.ejb3.component.ContainerInterceptorMethodInterceptorFactory; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.naming.ManagedReference; import org.jboss.as.naming.ValueManagedReference; import org.jboss.invocation.InterceptorFactory; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationTarget; import org.jboss.jandex.DotName; import org.jboss.jandex.Index; import org.jboss.jandex.Indexer; import org.jboss.jandex.MethodInfo; import org.jboss.modules.Module; import org.jboss.modules.ModuleLoadException; /** * @author <a href="mailto:[email protected]">Tomasz Adamski</a> */ public class ServerInterceptorCache { private final List<ServerInterceptorMetaData> serverInterceptorMetaData; private List<InterceptorFactory> serverInterceptorsAroundInvoke = null; private List<InterceptorFactory> serverInterceptorsAroundTimeout = null; public ServerInterceptorCache(final List<ServerInterceptorMetaData> interceptorsMetaData){ this.serverInterceptorMetaData = interceptorsMetaData; } public List<InterceptorFactory> getServerInterceptorsAroundInvoke() { synchronized(this) { if (serverInterceptorsAroundInvoke == null) { loadServerInterceptors(); } } return serverInterceptorsAroundInvoke; } public List<InterceptorFactory> getServerInterceptorsAroundTimeout() { synchronized(this) { if (serverInterceptorsAroundTimeout == null) { loadServerInterceptors(); } } return serverInterceptorsAroundTimeout; } private void loadServerInterceptors(){ serverInterceptorsAroundInvoke = new ArrayList<>(); serverInterceptorsAroundTimeout = new ArrayList<>(); for (final ServerInterceptorMetaData si: serverInterceptorMetaData) { final Class<?> interceptorClass; final String moduleId = si.getModule(); try { final Module module = Module.getCallerModuleLoader().loadModule(moduleId); interceptorClass = ClassLoadingUtils.loadClass(si.getClazz(), module); } catch (ModuleLoadException e) { throw EjbLogger.ROOT_LOGGER.cannotLoadServerInterceptorModule(moduleId, e); } catch (ClassNotFoundException e) { throw EeLogger.ROOT_LOGGER.cannotLoadInterceptor(e, si.getClazz()); } final Index index = buildIndexForClass(interceptorClass); serverInterceptorsAroundInvoke.addAll(findAnnotatedMethods(interceptorClass, index, AroundInvoke.class)); serverInterceptorsAroundTimeout.addAll(findAnnotatedMethods(interceptorClass, index, AroundTimeout.class)); } } private Index buildIndexForClass(final Class<?> interceptorClass) { try { final String classNameAsResource = interceptorClass.getName().replaceAll("\\.", "/").concat(".class"); final InputStream stream = interceptorClass.getClassLoader().getResourceAsStream(classNameAsResource); final Indexer indexer = new Indexer(); indexer.index(stream); stream.close(); return indexer.complete(); } catch (IOException e) { throw EjbLogger.ROOT_LOGGER.cannotBuildIndexForServerInterceptor(interceptorClass.getName(), e); } } private List<InterceptorFactory> findAnnotatedMethods(final Class<?> interceptorClass, final Index index, final Class<?> annotationClass){ final List<InterceptorFactory> interceptorFactories = new ArrayList<>(); final DotName annotationName = DotName.createSimple(annotationClass.getName()); final List<AnnotationInstance> annotations = index.getAnnotations(annotationName); for (final AnnotationInstance annotation : annotations) { if (annotation.target().kind() == AnnotationTarget.Kind.METHOD) { final MethodInfo methodInfo = annotation.target().asMethod(); final Constructor<?> constructor; try { constructor = interceptorClass.getConstructor(); } catch (NoSuchMethodException e) { throw EjbLogger.ROOT_LOGGER.serverInterceptorNoEmptyConstructor(interceptorClass.toString(), e); } try { final Method annotatedMethod = interceptorClass.getMethod(methodInfo.name(), new Class[]{InvocationContext.class}); final InterceptorFactory interceptorFactory = createInterceptorFactoryForServerInterceptor(annotatedMethod, constructor); interceptorFactories.add(interceptorFactory); } catch (NoSuchMethodException e) { throw EjbLogger.ROOT_LOGGER.serverInterceptorInvalidMethod(methodInfo.name(), interceptorClass.toString(), annotationClass.toString(), e); } } } return interceptorFactories; } private InterceptorFactory createInterceptorFactoryForServerInterceptor(final Method method, final Constructor interceptorConstructor) { // we *don't* create multiple instances of the container-interceptor class, but we just reuse a single instance and it's *not* // tied to the Jakarta Enterprise Beans component instance lifecycle. final ManagedReference interceptorInstanceRef = new ValueManagedReference(newInstance(interceptorConstructor)); // return the ContainerInterceptorMethodInterceptorFactory which is responsible for creating an Interceptor // which can invoke the container-interceptor's around-invoke/around-timeout methods return new ContainerInterceptorMethodInterceptorFactory(interceptorInstanceRef, method); } private static Object newInstance(final Constructor ctor) { try { return ctor.newInstance(new Object[] {}); } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } }
7,540
46.13125
158
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/interceptor/server/ServerInterceptorMetaData.java
package org.jboss.as.ejb3.interceptor.server; public class ServerInterceptorMetaData { private final String module; private final String clazz; public ServerInterceptorMetaData(final String module, final String clazz){ this.module = module; this.clazz = clazz; } public String getModule() { return module; } public String getClazz() { return clazz; } }
421
20.1
78
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/interceptor/server/ClientInterceptorCache.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.interceptor.server; import java.util.ArrayList; import java.util.List; import org.jboss.as.ee.logging.EeLogger; import org.jboss.as.ee.utils.ClassLoadingUtils; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.ejb.client.EJBClientInterceptor; import org.jboss.modules.Module; import org.jboss.modules.ModuleLoadException; /** * @author <a href="mailto:[email protected]">Tomasz Adamski</a> */ public class ClientInterceptorCache { private final List<ServerInterceptorMetaData> serverInterceptorMetaData; private List<Class<? extends EJBClientInterceptor>> clientInterceptors = null; public ClientInterceptorCache(final List<ServerInterceptorMetaData> interceptorsMetaData){ this.serverInterceptorMetaData = interceptorsMetaData; } public List<Class<? extends EJBClientInterceptor>> getClientInterceptors() { synchronized(this) { if (clientInterceptors == null) { loadClientInterceptors(); } } return clientInterceptors; } private void loadClientInterceptors(){ clientInterceptors = new ArrayList<>(); for (final ServerInterceptorMetaData si: serverInterceptorMetaData) { final String moduleId = si.getModule(); try { final Module module = Module.getCallerModuleLoader().loadModule(moduleId); clientInterceptors.add(ClassLoadingUtils.loadClass(si.getClazz(), module).asSubclass(EJBClientInterceptor.class)); } catch (ModuleLoadException e) { throw EjbLogger.ROOT_LOGGER.cannotLoadServerInterceptorModule(moduleId, e); } catch (ClassNotFoundException e) { throw EeLogger.ROOT_LOGGER.cannotLoadInterceptor(e, si.getClazz()); } } } }
2,860
38.191781
130
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/TimerState.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice; import java.util.Collections; import java.util.EnumSet; import java.util.Set; /** * Timer states. * <p/> * <p/> * Following is the possible timer state transitions: * <p/> * <ul> * <li> {@link #CREATED} - on create</li> * <li> {@link #CREATED} -> {@link #ACTIVE} - when started without Tx</li> * <li> {@link #ACTIVE} -> {@link #CANCELED} - on cancel() without Tx</li> * <li> {@link #ACTIVE} -> {@link #IN_TIMEOUT} - on TimerTask run</li> * <li> {@link #IN_TIMEOUT} -> {@link #ACTIVE} - on Tx commit if intervalDuration > 0</li> * <li> {@link #IN_TIMEOUT} -> {@link #EXPIRED} -> on Tx commit if intervalDuration == 0</li> * <li> {@link #IN_TIMEOUT} -> {@link #RETRY_TIMEOUT} -> on Tx rollback</li> * <li> {@link #RETRY_TIMEOUT} -> {@link #ACTIVE} -> on Tx commit/rollback if intervalDuration > 0</li> * <li> {@link #RETRY_TIMEOUT} -> {@link #EXPIRED} -> on Tx commit/rollback if intervalDuration == 0</li> * </ul> * * @author Jaikiran Pai * @version $Revision: $ */ public enum TimerState { /** * State indicating that a timer has been created. */ CREATED, /** * State indicating that the timer is active and will receive * any timeout notifications */ ACTIVE, /** * State indicating that the timer has been cancelled and will not * receive any future timeout notifications */ CANCELED, /** * State indicating that there aren't any scheduled timeouts for this timer */ EXPIRED, /** * State indicating that the timer has received a timeout notification * and is processing the timeout task */ IN_TIMEOUT, /** * State indicating that the timeout task has to be retried */ RETRY_TIMEOUT, ; /** * An unmodifiable set that contains timer states {@link #IN_TIMEOUT}, {@link #RETRY_TIMEOUT}, * {@link #CREATED} and {@link #ACTIVE}. */ public static final Set<TimerState> CREATED_ACTIVE_IN_TIMEOUT_RETRY_TIMEOUT = Collections.unmodifiableSet(EnumSet.of(IN_TIMEOUT, RETRY_TIMEOUT, CREATED, ACTIVE)); /** * An unmodifiable set that contains timer states {@link #EXPIRED} and {@link #CANCELED}. */ public static final Set<TimerState> EXPIRED_CANCELED = Collections.unmodifiableSet(EnumSet.of(EXPIRED, CANCELED)); }
3,399
33.693878
105
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/TimerServiceMetaDataSchema.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice; import java.util.List; import org.jboss.as.controller.xml.IntVersionSchema; import org.jboss.as.controller.xml.VersionedNamespace; import org.jboss.staxmapper.IntVersion; /** * @author Paul Ferraro */ public enum TimerServiceMetaDataSchema implements IntVersionSchema<TimerServiceMetaDataSchema> { VERSION_1_0(1, 0), VERSION_2_0(2, 0), ; static final TimerServiceMetaDataSchema CURRENT = VERSION_2_0; private final VersionedNamespace<IntVersion, TimerServiceMetaDataSchema> namespace; TimerServiceMetaDataSchema(int major, int minor) { this.namespace = IntVersionSchema.createURN(List.of(this.getLocalName()), new IntVersion(major, minor)); } @Override public String getLocalName() { return "timer-service"; } @Override public VersionedNamespace<IntVersion, TimerServiceMetaDataSchema> getNamespace() { return this.namespace; } }
1,979
34.357143
112
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/NonFunctionalTimerService.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 021101301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice; import java.util.Collection; import java.util.Collections; import java.util.Date; import jakarta.ejb.EJBException; import jakarta.ejb.ScheduleExpression; import jakarta.ejb.Timer; import jakarta.ejb.TimerConfig; import org.jboss.as.ejb3.timerservice.spi.ManagedTimer; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerService; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerServiceConfiguration; import org.jboss.as.ejb3.timerservice.spi.TimedObjectInvoker; import org.jboss.as.ejb3.timerservice.spi.TimerServiceRegistry; /** * Non-functional timer service that is bound when the timer service is disabled. */ public class NonFunctionalTimerService implements ManagedTimerService { private final String message; private final TimerServiceRegistry timerServiceRegistry; private final TimedObjectInvoker invoker; public NonFunctionalTimerService(final String message, ManagedTimerServiceConfiguration configuration) { this.message = message; this.timerServiceRegistry = configuration.getTimerServiceRegistry(); this.invoker = configuration.getInvoker(); } @Override public void start() { } @Override public void stop() { } @Override public ManagedTimer findTimer(String id) { return null; } @Override public TimedObjectInvoker getInvoker() { return this.invoker; } @Override public Timer createCalendarTimer(ScheduleExpression schedule, TimerConfig timerConfig) { throw new IllegalStateException(this.message); } @Override public Timer createIntervalTimer(Date initialExpiration, long intervalDuration, TimerConfig timerConfig) { throw new IllegalStateException(this.message); } @Override public Timer createSingleActionTimer(Date expiration, TimerConfig timerConfig) { throw new IllegalStateException(this.message); } @Override public Collection<Timer> getTimers() { this.validateInvocationContext(); return Collections.emptySet(); } @Override public Collection<jakarta.ejb.Timer> getAllTimers() throws IllegalStateException, EJBException { this.validateInvocationContext(); return this.timerServiceRegistry.getAllTimers(); } }
3,336
32.039604
110
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/TimerHandleImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice; import jakarta.ejb.TimerHandle; import org.jboss.as.ejb3.component.EJBComponent; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.timerservice.spi.ManagedTimer; import org.jboss.as.server.CurrentServiceContainer; import org.jboss.msc.service.ServiceName; import org.wildfly.security.manager.WildFlySecurityManager; /** * Serializable handle for an EJB timer. * @author <a href="mailto:[email protected]">Carlo de Wolf</a> * @author Paul Ferraro */ public class TimerHandleImpl implements TimerHandle { private static final long serialVersionUID = 1L; // Unused, but remains in order to retain serialization compatibility // We can use this field to determine if this handle instance was serialized from a legacy handle private final String timedObjectId = null; private final String serviceName; private final String id; private transient EJBComponent component; private transient ManagedTimer timer; /** * Creates a {@link TimerHandleImpl} * * @param timer The managed timer instance * @param component The EJB component associated with the timer */ public TimerHandleImpl(ManagedTimer timer, EJBComponent component) { this.timer = timer; this.component = component; this.id = timer.getId(); this.serviceName = component.getCreateServiceName().getCanonicalName(); } @SuppressWarnings("deprecation") @Override public synchronized jakarta.ejb.Timer getTimer() { if (this.component == null) { ServiceName serviceName = ServiceName.parse(this.serviceName); // Is this a legacy timer handle? if (this.timedObjectId != null) { // If so, figure out the component create service name from the legacy TimerServiceImpl ServiceName serviceName = serviceName.getParent().getParent().append("CREATE"); } this.component = (EJBComponent) WildFlySecurityManager.doUnchecked(CurrentServiceContainer.GET_ACTION).getRequiredService(serviceName).getValue(); } if (this.timer == null) { this.timer = this.component.getTimerService().findTimer(this.id); } if ((this.timer == null) || !this.timer.isActive()) { throw EjbLogger.EJB3_TIMER_LOGGER.timerHandleIsNotActive(this.id, this.component.getTimerService().getInvoker().getTimedObjectId()); } return this.timer; } @Override public int hashCode() { return this.id.hashCode(); } @Override public boolean equals(Object object) { if (!(object instanceof TimerHandleImpl)) return false; TimerHandleImpl handle = (TimerHandleImpl) object; return this.id.equals(handle.id) && this.serviceName.equals(handle.serviceName); } @Override public String toString() { return this.id; } }
3,973
37.582524
158
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/TimerTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice; import static org.jboss.as.ejb3.logging.EjbLogger.EJB3_TIMER_LOGGER; import java.util.Date; import org.wildfly.security.manager.WildFlySecurityManager; /** * A timer task which will be invoked at appropriate intervals based on a {@link jakarta.ejb.Timer} * schedule. * <p/> * <p> * A {@link TimerTask} is responsible for invoking the timeout method on the target, through * the use of {@link org.jboss.as.ejb3.timerservice.spi.TimedObjectInvoker} * </p> * <p> * For calendar timers, this {@link TimerTask} is additionally responsible for creating and * scheduling the next round of timer task. * </p> * * @author Jaikiran Pai * @author Wolf-Dieter Fink * @version $Revision: $ */ public class TimerTask implements Runnable { protected final String timedObjectId; protected final String timerId; /** * {@link org.jboss.as.ejb3.timerservice.TimerServiceImpl} to which this {@link TimerTask} belongs */ protected final TimerServiceImpl timerService; private volatile boolean cancelled = false; /** * Creates a {@link TimerTask} for the timer * * @param timer The timer for which this task is being created. * @throws IllegalStateException If the passed timer is null */ public TimerTask(TimerImpl timer) { if (timer == null) { throw EJB3_TIMER_LOGGER.timerIsNull(); } this.timedObjectId = timer.getTimedObjectId(); timerId = timer.getId(); timerService = timer.getTimerService(); } /** * Invokes the timeout method through the {@link org.jboss.as.ejb3.timerservice.spi.TimedObjectInvoker} corresponding * to the {@link org.jboss.as.ejb3.timerservice.TimerImpl} to which this {@link TimerTask} belongs. * <p> * This method also sets other attributes on the {@link org.jboss.as.ejb3.timerservice.TimerImpl} including the * next timeout of the timer and the timer state. * </p> * <p> * Additionally, for calendar timers, this method even schedules the next timeout timer task * before calling the timeout method for the current timeout. * </p> */ @Override public void run() { ClassLoader old = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(getClass()); try { final TimerImpl timer = timerService.getTimer(timerId); try { if (timer == null || cancelled) { EJB3_TIMER_LOGGER.debugf("Timer task was cancelled for %s", timer); return; } Date now = new Date(); EJB3_TIMER_LOGGER.debugf("Timer task invoked at: %s for timer %s", now, timer); //we lock the timer for this check, because if a cancel is in progress or a running timeout is about to finish //and try to update the timer state after finish the inTimeout method, //we do not want to do the isActive check, but wait for the other transaction to finish //one way or another timer.lock(); try { // If a retry thread is in progress, we don't want to allow another // interval to execute until the retry is complete. See JIRA-1926. if (timer.isInRetry()) { EJB3_TIMER_LOGGER.skipInvokeTimeoutDuringRetry(timer, now); // compute the next timeout, See JIRA AS7-2995. timer.setNextTimeout(calculateNextTimeout(timer)); timerService.persistTimer(timer, false); scheduleTimeoutIfRequired(timer); return; } // Check whether the timer is running local // If the recurring timer running longer than the interval is, we don't want to allow another // execution until it is complete. See JIRA AS7-3119 if (timer.getState() == TimerState.IN_TIMEOUT || timer.getState() == TimerState.RETRY_TIMEOUT) { EJB3_TIMER_LOGGER.skipOverlappingInvokeTimeout(timer, now); if (EJB3_TIMER_LOGGER.isDebugEnabled()) { // WFLY-10542 log thread stack trace which is processing timer task in debug level to diagnose timer overlap Thread otherThread = timer.getExecutingThread(); // can be null for clustered timers if the timer is executing on another node. if (otherThread != null) { final StringBuilder debugMsg = new StringBuilder() .append("Thread: ") .append(otherThread.getName()) .append(" Id: ") .append(otherThread.getId()) .append(" of group ") .append(otherThread.getThreadGroup()) .append(" is in state: ") .append(otherThread.getState()); for (StackTraceElement ste : otherThread.getStackTrace()) { debugMsg.append(System.lineSeparator()).append(ste.toString()); } EJB3_TIMER_LOGGER.debugf(debugMsg.toString()); } } Date newD = this.calculateNextTimeout(timer); timer.setNextTimeout(newD); timerService.persistTimer(timer, false); scheduleTimeoutIfRequired(timer); return; } // Check whether we want to run the timer if (!timerService.shouldRun(timer)) { EJB3_TIMER_LOGGER.debugf("Skipping execution of timer for %s as it is being run on another node or the execution is suppressed by configuration", timer.getTimedObjectId()); timer.setNextTimeout(calculateNextTimeout(timer)); scheduleTimeoutIfRequired(timer); return; } // ensure timer service is started, and the timer has not expired or been cancelled. // Execution got here after this TimerTask instance has been scheduled on TimerServiceImpl#timer, // and TimerTask instance saved in TimerServiceImpl#scheduledTimerFutures if (timer.timerState == TimerState.CANCELED || timer.timerState == TimerState.EXPIRED || !timer.timerService.isStarted()) { EJB3_TIMER_LOGGER.debug("Timer is not active, skipping this scheduled execution at: " + now + "for " + timer); return; } // timer state is now either CREATED or ACTIVE // set the current date as the "previous run" of the timer. timer.setPreviousRun(new Date()); Date nextTimeout = this.calculateNextTimeout(timer); timer.setNextTimeout(nextTimeout); // change the state to mark it as in timeout method timer.setTimerState(TimerState.IN_TIMEOUT, Thread.currentThread()); // persist changes timerService.persistTimer(timer, false); } finally { timer.unlock(); } try { // invoke timeout this.callTimeout(timer); } catch (Exception e) { EJB3_TIMER_LOGGER.errorInvokeTimeout(timer, e); try { EJB3_TIMER_LOGGER.timerRetried(timer); retryTimeout(timer); } catch (Exception retryException) { // that's it, we can't do anything more. Let's just log the exception // and return EJB3_TIMER_LOGGER.errorDuringRetryTimeout(timer, retryException); } } finally { this.postTimeoutProcessing(timer); } } catch (Exception e) { EJB3_TIMER_LOGGER.exceptionRunningTimerTask(timer, timedObjectId, e); } } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(old); } } protected void scheduleTimeoutIfRequired(TimerImpl timer) { } protected void callTimeout(TimerImpl timer) throws Exception { invokeBeanMethod(timer); } protected void invokeBeanMethod(TimerImpl timer) throws Exception { timerService.getInvoker().callTimeout(timer); } protected Date calculateNextTimeout(TimerImpl timer) { long intervalDuration = timer.getInterval(); if (intervalDuration > 0) { long now = System.currentTimeMillis(); long nextExpiration = timer.getNextExpiration().getTime(); // compute skipped number of interval int periods = (int) ((now - nextExpiration) / intervalDuration); // compute the next timeout date return new Date(nextExpiration + (periods * intervalDuration) + intervalDuration); } return null; } /** * After a timeout failed the timer need to retried. * The method must lock the timer for state check and update but not during callTimeout run. * * @param timer timer to retry and state updates * @throws Exception */ protected void retryTimeout(TimerImpl timer) throws Exception { boolean callTimeout = false; timer.lock(); try { if (timer.isActive()) { EJB3_TIMER_LOGGER.retryingTimeout(timer); timer.setTimerState(TimerState.RETRY_TIMEOUT, Thread.currentThread()); timerService.persistTimer(timer, false); callTimeout = true; } else { EJB3_TIMER_LOGGER.timerNotActive(timer); } } finally { timer.unlock(); } if(callTimeout) { this.callTimeout(timer); } } /** * After running the timer calculate the new state or expire the timer and persist it if changed. * The method must lock the timer for state check and updates if overridden. * * @param timer timer to post processing and persist */ protected void postTimeoutProcessing(TimerImpl timer) throws InterruptedException { timer.lock(); try { TimerState timerState = timer.getState(); if (timerState != TimerState.CANCELED && timerState != TimerState.EXPIRED) { if (timer.getInterval() == 0) { timerService.expireTimer(timer); } else { timer.setTimerState(TimerState.ACTIVE, null); } timerService.persistTimer(timer, false); } } finally { timer.unlock(); } } public void cancel() { cancelled = true; } }
12,567
42.487889
196
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/TimerServiceBindingSource.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice; import org.jboss.as.ee.component.Component; import org.jboss.as.ee.component.InjectionSource; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.component.EJBComponent; import org.jboss.as.ejb3.context.CurrentInvocationContext; import org.jboss.as.naming.ContextListManagedReferenceFactory; import org.jboss.as.naming.ManagedReference; import org.jboss.as.naming.ManagedReferenceFactory; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.invocation.InterceptorContext; import org.jboss.msc.inject.Injector; import org.jboss.msc.service.ServiceBuilder; /** * An {@link InjectionSource} which returns a {@link ManagedReference reference} to a {@link jakarta.ejb.TimerService} * <p/> * @author Jaikiran Pai */ public class TimerServiceBindingSource extends InjectionSource { private static final TimerServiceManagedReferenceFactory TIMER_SERVICE_MANAGED_REFERENCE_FACTORY_INSTANCE = new TimerServiceManagedReferenceFactory(); @Override public void getResourceValue(ResolutionContext resolutionContext, ServiceBuilder<?> serviceBuilder, DeploymentPhaseContext phaseContext, Injector<ManagedReferenceFactory> injector) throws DeploymentUnitProcessingException { injector.inject(TIMER_SERVICE_MANAGED_REFERENCE_FACTORY_INSTANCE); } /** * {@link ManagedReferenceFactory} for returning a {@link ManagedReference} to a {@link jakarta.ejb.TimerService} */ private static class TimerServiceManagedReferenceFactory implements ContextListManagedReferenceFactory { private final TimerServiceManagedReference timerServiceManagedReference = new TimerServiceManagedReference(); @Override public ManagedReference getReference() { return timerServiceManagedReference; } @Override public String getInstanceClassName() { return jakarta.ejb.TimerService.class.getName(); } } /** * A {@link ManagedReference} to a {@link jakarta.ejb.TimerService} */ private static class TimerServiceManagedReference implements ManagedReference { @Override public void release() { } @Override public Object getInstance() { // get the current invocation context and the EJBComponent out of it final InterceptorContext currentInvocationContext = CurrentInvocationContext.get(); final EJBComponent ejbComponent = (EJBComponent) currentInvocationContext.getPrivateData(Component.class); if (ejbComponent == null) { throw EjbLogger.EJB3_TIMER_LOGGER.failToGetEjbComponent(currentInvocationContext); } return ejbComponent.getTimerService(); } } // All Timer bindings are equivalent since they just use a thread local context public boolean equals(Object o) { return o instanceof TimerServiceBindingSource; } public int hashCode() { return 1; } }
4,123
39.038835
227
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/TimerServiceConfiguration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice; import java.util.Timer; import java.util.concurrent.ExecutorService; import org.jboss.as.ejb3.timerservice.persistence.TimerPersistence; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerServiceConfiguration; /** * @author Paul Ferraro */ public interface TimerServiceConfiguration extends ManagedTimerServiceConfiguration { ExecutorService getExecutor(); Timer getTimer(); TimerPersistence getTimerPersistence(); }
1,504
34.833333
85
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/CalendarTimerTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import org.jboss.as.ejb3.timerservice.spi.TimedObjectInvoker; /** * CalendarTimerTask * * @author Jaikiran Pai * @version $Revision: $ */ public class CalendarTimerTask extends TimerTask { public CalendarTimerTask(CalendarTimer calendarTimer) { super(calendarTimer); } @Override protected void callTimeout(TimerImpl timer) throws Exception { // if we have any more schedules remaining, then schedule a new task if (timer.getNextExpiration() != null && !timer.isInRetry()) { timer.scheduleTimeout(false); } invokeBeanMethod(timer); } @Override protected void invokeBeanMethod(TimerImpl timer) throws Exception { // finally invoke the timeout method through the invoker if (timer.isAutoTimer()) { CalendarTimer calendarTimer = (CalendarTimer) timer; TimedObjectInvoker invoker = this.timerService.getInvoker(); // call the timeout method invoker.callTimeout(calendarTimer, calendarTimer.getTimeoutMethod()); } else { this.timerService.getInvoker().callTimeout(timer); } } @Override protected Date calculateNextTimeout(TimerImpl timer) { // The next timeout for the calendar timer will have to be computed using the // current "nextExpiration" Date currentTimeout = timer.getNextExpiration(); if (currentTimeout == null) { return null; } Calendar cal = new GregorianCalendar(); cal.setTime(currentTimeout); // now compute the next timeout date Calendar nextTimeout = ((CalendarTimer) timer).getCalendarTimeout().getNextTimeout(cal); if (nextTimeout != null) { return nextTimeout.getTime(); } return null; } @Override protected void scheduleTimeoutIfRequired(TimerImpl timer) { if (timer.getNextExpiration() != null) { timer.scheduleTimeout(false); } } @Override protected void postTimeoutProcessing(TimerImpl timer) throws InterruptedException { timer.lock(); try { final TimerState timerState = timer.getState(); if (timerState != TimerState.CANCELED && timerState != TimerState.EXPIRED) { if (timer.getNextExpiration() == null) { timerService.expireTimer(timer); } else { timer.setTimerState(TimerState.ACTIVE, null); // persist changes timerService.persistTimer(timer, false); } } } finally { timer.unlock(); } } }
3,876
34.245455
96
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/TimerServiceMetaDataParser.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.metadata.ejb.parser.jboss.ejb3.AbstractEJBBoundMetaDataParser; import org.jboss.metadata.property.PropertyReplacer; /** * Parser for timer service EJB meta data. * @author Stuart Douglas * @author Paul Ferraro */ public class TimerServiceMetaDataParser extends AbstractEJBBoundMetaDataParser<TimerServiceMetaData> { private final TimerServiceMetaDataSchema schema; public TimerServiceMetaDataParser(TimerServiceMetaDataSchema schema) { this.schema = schema; } @Override public TimerServiceMetaData parse(XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException { if (this.schema != TimerServiceMetaDataSchema.CURRENT) { EjbLogger.ROOT_LOGGER.deprecatedNamespace(reader.getNamespaceURI(), reader.getLocalName()); } TimerServiceMetaData metaData = new TimerServiceMetaData(); processElements(metaData, reader, propertyReplacer); return metaData; } @Override protected void processElement(TimerServiceMetaData metaData, XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException { if (this.schema.getNamespace().getUri().equals(reader.getNamespaceURI())) { switch (reader.getLocalName()) { case "persistence-store-name": metaData.setDataStoreName(getElementText(reader, propertyReplacer)); break; case "persistent-timer-management": if (this.schema.since(TimerServiceMetaDataSchema.VERSION_2_0)) { metaData.setPersistentTimerManagementProvider(getElementText(reader, propertyReplacer)); break; } case "transient-timer-management": if (this.schema.since(TimerServiceMetaDataSchema.VERSION_2_0)) { metaData.setTransientTimerManagementProvider(getElementText(reader, propertyReplacer)); break; } default: throw unexpectedElement(reader); } } else { super.processElement(metaData, reader, propertyReplacer); } } }
3,451
41.617284
157
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/NonFunctionalTimerServiceFactoryServiceConfigurator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice; import java.util.function.Predicate; import jakarta.ejb.TimerConfig; import org.jboss.as.ejb3.component.EJBComponent; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerService; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerServiceConfiguration; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerServiceFactory; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerServiceFactoryConfiguration; import org.jboss.as.ejb3.timerservice.spi.TimedObjectInvoker; import org.jboss.as.ejb3.timerservice.spi.TimedObjectInvokerFactory; import org.jboss.as.ejb3.timerservice.spi.TimerListener; import org.jboss.as.ejb3.timerservice.spi.TimerServiceRegistry; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.wildfly.clustering.service.ServiceConfigurator; import org.wildfly.clustering.service.SimpleServiceNameProvider; /** * Configures a service that provides a non-function TimerService factory. * @author Paul Ferraro */ public class NonFunctionalTimerServiceFactoryServiceConfigurator extends SimpleServiceNameProvider implements ServiceConfigurator, ManagedTimerServiceFactory { private final String message; private final TimerServiceRegistry registry; private final TimedObjectInvokerFactory invokerFactory; private final TimerListener listener; public NonFunctionalTimerServiceFactoryServiceConfigurator(ServiceName name, String message, ManagedTimerServiceFactoryConfiguration configuration) { super(name); this.message = message; this.invokerFactory = configuration.getInvokerFactory(); this.registry = configuration.getTimerServiceRegistry(); this.listener = configuration.getTimerListener(); } @Override public ServiceBuilder<?> build(ServiceTarget target) { ServiceName name = this.getServiceName(); ServiceBuilder<?> builder = target.addService(name); return builder.setInstance(Service.newInstance(builder.provides(name), this)); } @Override public ManagedTimerService createTimerService(EJBComponent component) { TimedObjectInvoker invoker = this.invokerFactory.createInvoker(component); TimerServiceRegistry registry = this.registry; TimerListener listener = this.listener; return new NonFunctionalTimerService(this.message, new ManagedTimerServiceConfiguration() { @Override public TimedObjectInvoker getInvoker() { return invoker; } @Override public TimerServiceRegistry getTimerServiceRegistry() { return registry; } @Override public TimerListener getTimerListener() { return listener; } @Override public Predicate<TimerConfig> getTimerFilter() { return TimerFilter.ALL; } }); } }
4,066
40.080808
159
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/TimedObjectInvokerFactoryImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice; import org.jboss.as.ejb3.component.EJBComponent; import org.jboss.as.ejb3.timerservice.spi.TimedObjectInvoker; import org.jboss.as.ejb3.timerservice.spi.TimedObjectInvokerFactory; import org.jboss.modules.Module; /** * @author Paul Ferraro */ public class TimedObjectInvokerFactoryImpl implements TimedObjectInvokerFactory { private final Module module; private final String deploymentName; public TimedObjectInvokerFactoryImpl(Module module, String deploymentName) { this.module = module; this.deploymentName = deploymentName; } @Override public TimedObjectInvoker createInvoker(EJBComponent component) { return new TimedObjectInvokerImpl(this.module, this.deploymentName, component); } }
1,813
36.791667
87
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/TimerServiceFactoryServiceConfigurator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice; import java.util.Timer; import java.util.concurrent.ExecutorService; import java.util.function.Consumer; import java.util.function.Predicate; import jakarta.ejb.TimerConfig; import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; import org.jboss.as.controller.capability.CapabilityServiceSupport; import org.jboss.as.ejb3.component.EJBComponent; import org.jboss.as.ejb3.subsystem.TimerServiceResourceDefinition; import org.jboss.as.ejb3.timerservice.persistence.TimerPersistence; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerService; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerServiceConfiguration.TimerFilter; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerServiceFactory; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerServiceFactoryConfiguration; import org.jboss.as.ejb3.timerservice.spi.TimedObjectInvoker; import org.jboss.as.ejb3.timerservice.spi.TimedObjectInvokerFactory; import org.jboss.as.ejb3.timerservice.spi.TimerListener; import org.jboss.as.ejb3.timerservice.spi.TimerServiceRegistry; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.wildfly.clustering.service.CompositeDependency; import org.wildfly.clustering.service.ServiceConfigurator; import org.wildfly.clustering.service.ServiceSupplierDependency; import org.wildfly.clustering.service.SimpleServiceNameProvider; import org.wildfly.clustering.service.SupplierDependency; /** * Configures a service that provides a local timer service factory. * @author Paul Ferraro */ public class TimerServiceFactoryServiceConfigurator extends SimpleServiceNameProvider implements CapabilityServiceConfigurator, ManagedTimerServiceFactory { private final TimerServiceRegistry registry; private final TimerListener listener; private final String threadPoolName; private final String store; private final TimedObjectInvokerFactory invokerFactory; private volatile SupplierDependency<Timer> timer; private volatile SupplierDependency<ExecutorService> executor; private volatile SupplierDependency<TimerPersistence> persistence; private volatile Predicate<TimerConfig> timerFilter = TimerFilter.ALL; public TimerServiceFactoryServiceConfigurator(ServiceName name, ManagedTimerServiceFactoryConfiguration configuration, String threadPoolName, String store) { super(name); this.invokerFactory = configuration.getInvokerFactory(); this.registry = configuration.getTimerServiceRegistry(); this.listener = configuration.getTimerListener(); this.threadPoolName = threadPoolName; this.store = store; } public TimerServiceFactoryServiceConfigurator filter(Predicate<TimerConfig> timerFilter) { this.timerFilter = timerFilter; return this; } @Override public ServiceConfigurator configure(CapabilityServiceSupport support) { this.timer = new ServiceSupplierDependency<>(support.getCapabilityServiceName(TimerServiceResourceDefinition.TIMER_SERVICE_CAPABILITY_NAME)); this.executor = new ServiceSupplierDependency<>(support.getCapabilityServiceName(TimerServiceResourceDefinition.THREAD_POOL_CAPABILITY_NAME, this.threadPoolName)); this.persistence = (this.store != null) ? new ServiceSupplierDependency<>(support.getCapabilityServiceName(TimerServiceResourceDefinition.TIMER_PERSISTENCE_CAPABILITY_NAME, this.store)) : null; return this; } @Override public ServiceBuilder<?> build(ServiceTarget target) { ServiceName name = this.getServiceName(); ServiceBuilder<?> builder = target.addService(name); Consumer<ManagedTimerServiceFactory> factory = new CompositeDependency(this.timer, this.executor, this.persistence).register(builder).provides(name); return builder.setInstance(Service.newInstance(factory, this)).setInitialMode(ServiceController.Mode.ON_DEMAND); } @Override public ManagedTimerService createTimerService(EJBComponent component) { TimedObjectInvoker invoker = this.invokerFactory.createInvoker(component); TimerServiceRegistry registry = this.registry; TimerListener listener = this.listener; ExecutorService executor = this.executor.get(); Timer timer = this.timer.get(); TimerPersistence persistence = (this.persistence != null) ? this.persistence.get() : null; Predicate<TimerConfig> timerFilter = this.timerFilter; return new TimerServiceImpl(new TimerServiceConfiguration() { @Override public TimedObjectInvoker getInvoker() { return invoker; } @Override public TimerServiceRegistry getTimerServiceRegistry() { return registry; } @Override public TimerListener getTimerListener() { return listener; } @Override public ExecutorService getExecutor() { return executor; } @Override public Timer getTimer() { return timer; } @Override public TimerPersistence getTimerPersistence() { return persistence; } @Override public Predicate<TimerConfig> getTimerFilter() { return timerFilter; } }); } }
6,618
43.126667
201
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/TimerImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice; import java.io.Serializable; import java.util.Date; import java.util.concurrent.Semaphore; import jakarta.ejb.EJBException; import jakarta.ejb.ScheduleExpression; import jakarta.ejb.TimerHandle; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.timerservice.spi.ManagedTimer; import org.jboss.as.ejb3.timerservice.spi.TimedObjectInvoker; /** * Local implementation of {@link ManagedTimer}. * * @author <a href="mailto:[email protected]">Carlo de Wolf</a> */ public class TimerImpl implements ManagedTimer { /** * The output format with the cached final values, after the first toString() invocation */ private String toStringTemplate; /** * Unique id for this timer instance */ protected final String id; /** * The timer state */ protected volatile TimerState timerState; /** * The {@link jakarta.ejb.TimerService} through which this timer was created */ protected final TimerServiceImpl timerService; /** * The {@link TimedObjectInvoker} to which this timer corresponds */ protected final TimedObjectInvoker timedObjectInvoker; /** * The info which was passed while creating the timer. */ protected Serializable info; /** * Indicates whether the timer is persistent */ protected final boolean persistent; /** * The initial (first) expiry date of this timer */ protected final Date initialExpiration; /** * The duration in milli sec. between timeouts */ protected final long intervalDuration; /** * Next expiry date of this timer */ protected volatile Date nextExpiration; /** * The date of the previous run of this timer */ protected volatile Date previousRun; private final String timedObjectId; /** * In use lock. This is held by timer invocations and cancellation within the scope of a transaction, all changes * to timer state after creation should be done within this lock, to prevent state being overwritten by multiple * threads. * <p/> * If the timer cancelled, but then rolled back we do not want the timer task to see this cancellation. * * todo: we can probably just use a sync block here */ private final Semaphore inUseLock = new Semaphore(1); /** * The executing thread which is processing the timeout task This is only set to executing thread for TimerState.IN_TIMEOUT * and TimerState.RETRY_TIMEOUT */ private volatile Thread executingThread; /** * Creates a {@link TimerImpl} * * @param builder The builder with the timer information * @param service The timer service through which this timer was created */ protected TimerImpl(Builder builder, TimerServiceImpl service) { assert builder.id != null : "id is null"; this.id = builder.id; this.timedObjectId = builder.timedObjectId; this.info = builder.info; this.persistent = builder.persistent; this.initialExpiration = builder.initialDate; this.intervalDuration = builder.repeatInterval; if (builder.newTimer && builder.nextDate == null) { this.nextExpiration = initialExpiration; } else { this.nextExpiration = builder.nextDate; } this.previousRun = builder.previousRun; this.timerState = builder.timerState; this.timerService = service; this.timedObjectInvoker = service.getInvoker(); } /** * {@inheritDoc} */ @Override public void cancel() throws IllegalStateException, EJBException { try { timerService.cancelTimer(this); } catch (InterruptedException e) { throw new EJBException(e); } } /** * Returns the id of this timer * * @return */ @Override public String getId() { return this.id; } /** * {@inheritDoc} */ @Override public boolean isCalendarTimer() throws IllegalStateException, EJBException { // first check whether this timer has expired or cancelled this.validateInvocationContext(); return false; } /** * {@inheritDoc} */ @Override public TimerHandle getHandle() throws IllegalStateException, EJBException { // make sure it's in correct state this.validateInvocationContext(); // for non-persistent timers throws an exception (mandated by Enterprise Beans 3 spec) if (!persistent) { throw EjbLogger.EJB3_TIMER_LOGGER.invalidTimerHandlersForPersistentTimers("Enterprise Beans 3.1 Spec 18.2.6"); } return new TimerHandleImpl(this, timedObjectInvoker.getComponent()); } /** * {@inheritDoc} */ @Override public boolean isPersistent() throws IllegalStateException, EJBException { // make sure the call is allowed in the current timer state this.validateInvocationContext(); return this.persistent; } /** * {@inheritDoc} * * @see #getTimerInfo() */ @Override public Serializable getInfo() throws IllegalStateException, EJBException { // make sure this call is allowed this.validateInvocationContext(); return getTimerInfo(); } /** * This method is similar to {@link #getInfo()}, except that this method does <i>not</i> check the timer state * and hence does <i>not</i> throw either {@link IllegalStateException} or {@link jakarta.ejb.NoSuchObjectLocalException} * or {@link jakarta.ejb.EJBException}. * * @return the timer info; if not available in-memory, retrieve it from persistence */ public Serializable getTimerInfo() { if (info != Object.class) { return info; } return timerService.getPersistedTimerInfo(this); } /** * Obtains the timer info cached in memory, without checking the persistent store. * * @return the cached timer info */ public Serializable getCachedTimerInfo() { return info; } /** * Sets the timer info to a new value. * The purpose of this method is for {@code DatabaseTimerPersistence} to reset * the cached timer info. It should not be used for other purposes. * * @param newInfo the new timer info, typically null or an empty holder value */ public void setCachedTimerInfo(final Serializable newInfo) { info = newInfo; } /** * {@inheritDoc} * * @see #getNextExpiration() */ @Override public Date getNextTimeout() throws IllegalStateException, EJBException { // first check the validity of the timer state this.validateInvocationContext(); if (this.nextExpiration == null) { throw EjbLogger.EJB3_TIMER_LOGGER.noMoreTimeoutForTimer(this); } return this.nextExpiration; } /** * This method is similar to {@link #getNextTimeout()}, except that this method does <i>not</i> check the timer state * and hence does <i>not</i> throw either {@link IllegalStateException} or {@link jakarta.ejb.NoSuchObjectLocalException} * or {@link jakarta.ejb.EJBException}. * * @return */ public Date getNextExpiration() { return this.nextExpiration; } /** * Sets the next timeout of this timer * * @param next The next scheduled timeout of this timer */ public void setNextTimeout(Date next) { if(next == null) { setTimerState(TimerState.EXPIRED, null); } this.nextExpiration = next; } /** * {@inheritDoc} */ @Override public ScheduleExpression getSchedule() throws IllegalStateException, EJBException { this.validateInvocationContext(); throw EjbLogger.EJB3_TIMER_LOGGER.invalidTimerNotCalendarBaseTimer(this); } /** * {@inheritDoc} */ @Override public long getTimeRemaining() throws IllegalStateException, EJBException { // TODO: Rethink this implementation // first check the validity of the timer state this.validateInvocationContext(); if (this.nextExpiration == null) { throw EjbLogger.EJB3_TIMER_LOGGER.noMoreTimeoutForTimer(this); } long currentTimeInMillis = System.currentTimeMillis(); long nextTimeoutInMillis = this.nextExpiration.getTime(); // if the next expiration is *not* in future and the repeat interval isn't // a positive number (i.e. no repeats) then there won't be any more timeouts. // So throw a NoMoreTimeoutsException. // NOTE: We check for intervalDuration and not just nextExpiration because, // it's a valid case where the nextExpiration is in past (maybe the server was // down when the timeout was expected) // if (nextTimeoutInMillis < currentTimeInMillis && this.intervalDuration <= 0) // { // throw new NoMoreTimeoutsException("No more timeouts for timer " + this); // } return nextTimeoutInMillis - currentTimeInMillis; } public boolean isAutoTimer() { return false; } /** * Returns the initial (first) timeout date of this timer * * @return */ public Date getInitialExpiration() { return this.initialExpiration; } /** * Returns the interval (in milliseconds), between timeouts, of this timer. * * @return */ public long getInterval() { return this.intervalDuration; } /** * Returns the timed object id to which this timer belongs * * @return */ public String getTimedObjectId() { return timedObjectId; } /** * Returns the timer service through which this timer was created * * @return */ public TimerServiceImpl getTimerService() { return this.timerService; } /** * Returns true if this timer is active. Else returns false. * <p> * A timer is considered to be "active", if its {@link TimerState} * is neither of the following: * <ul> * <li>{@link TimerState#CANCELED}</li> * <li>{@link TimerState#EXPIRED}</li> * <li>has not been suspended</li> * </ul> * <p/> * And if the corresponding timer service is still up * <p/> * </p> * * @return */ @Override public boolean isActive() { return timerService.isStarted() && !isCanceled() && !isExpired() && (timerState == TimerState.CREATED || timerService.isScheduled(getId())); } /** * Returns true if this timer is in {@link TimerState#CANCELED} state. Else returns false. * * @return */ @Override public boolean isCanceled() { return timerState == TimerState.CANCELED; } /** * Returns true if this timer is in {@link TimerState#EXPIRED} state. Else returns false * * @return */ @Override public boolean isExpired() { return timerState == TimerState.EXPIRED; } /** * Returns true if this timer is in {@link TimerState#RETRY_TIMEOUT}. Else returns false. * * @return */ public boolean isInRetry() { return timerState == TimerState.RETRY_TIMEOUT; } /** * Returns the {@link java.util.Date} of the previous timeout of this timer * * @return */ public Date getPreviousRun() { return this.previousRun; } /** * Sets the {@link java.util.Date} of the previous timeout of this timer * * @param previousRun */ public void setPreviousRun(Date previousRun) { this.previousRun = previousRun; } /** * Returns the current state of this timer * * @return */ public TimerState getState() { return this.timerState; } /** * Returns the executing thread which is processing the timeout task * * @return the executingThread */ protected Thread getExecutingThread() { return executingThread; } /** * Sets the state and timer task executing thread of this timer * * @param state The state of this timer * @param thread The executing thread which is processing the timeout task */ public void setTimerState(TimerState state, Thread thread) { assert ((state == TimerState.IN_TIMEOUT || state == TimerState.RETRY_TIMEOUT) && thread != null) || thread == null : "Invalid to set timer state " + state + " with executing Thread " + thread; this.timerState = state; this.executingThread = thread; } @Override public void activate() { this.scheduleTimeout(true); } /** * Suspends any currently scheduled task for this timer * <p> * Note that, suspend does <b>not</b> cancel the {@link Timer}. Instead, * it just cancels the <b>next scheduled timeout</b>. So once the {@link Timer} * is restored (whenever that happens), the {@link Timer} will continue to * timeout at appropriate times. * </p> */ // TODO: Revisit this method, we probably don't need this any more. // In terms of implementation, this is just equivalent to cancelTimeout() method @Override public void suspend() { // cancel any scheduled timer task (Future) for this timer // delegate to the timerservice, so that it can cancel any scheduled Future // for this timer this.timerService.cancelTimeout(this); } /** * Triggers timer, outside of normal expiration. Only used when running an explicit management trigger operation. * * The tigger operation simply runs the callback, it does not modify the timer state in any way, and there is no * protection against overlapping events when running it. This is the expected behaviour, as otherwise the semantics * of dealing with concurrent execution is complex and kinda weird. */ @Override public void invoke() throws Exception { this.getTimerTask().invokeBeanMethod(this); } /** * Creates and schedules a {@link TimerTask} for the next timeout of this timer * * @param newTimer <code>true</code> if this is a new timer being scheduled, and not a re-schedule due to a timeout */ public void scheduleTimeout(boolean newTimer) { // just delegate to timerservice, for it to do the actual scheduling this.timerService.scheduleTimeout(this, newTimer); } /** * Returns the task which handles the timeouts of this {@link TimerImpl} * * @return * @see TimerTask */ protected TimerTask getTimerTask() { return new TimerTask(this); } public void lock() throws InterruptedException { inUseLock.acquire(); } public void unlock() { inUseLock.release(); } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || this.getClass() != o.getClass()) return false; final TimerImpl otherTimer = (TimerImpl) o; if (!id.equals(otherTimer.id)) return false; return timedObjectId.equals(otherTimer.timedObjectId); } @Override public int hashCode() { return id.hashCode(); } /** * A nice formatted string output for this timer * {@inheritDoc} */ @Override public String toString() { if (this.toStringTemplate == null) { // initialize with the first invocation StringBuilder sb = new StringBuilder(); sb.append("[id="); sb.append(this.id); sb.append(" timedObjectId="); sb.append(timedObjectId); sb.append(" auto-timer?:"); sb.append(this.isAutoTimer()); sb.append(" persistent?:"); sb.append(this.persistent); sb.append(" timerService="); sb.append(this.timerService); sb.append(" previousRun="); sb.append(this.previousRun); sb.append(" initialExpiration="); sb.append(this.initialExpiration); sb.append(" intervalDuration(in milli sec)="); sb.append(this.intervalDuration); this.toStringTemplate = sb.toString(); } // complete with the dynamic values StringBuilder sb = new StringBuilder(this.toStringTemplate); sb.append(" nextExpiration="); sb.append(this.nextExpiration); sb.append(" timerState="); sb.append(this.timerState); sb.append(" info="); sb.append(this.info); sb.append("]"); return sb.toString(); } public static Builder builder() { return new Builder(); } public static class Builder { protected String id; protected String timedObjectId; protected Date initialDate; protected long repeatInterval; protected Date nextDate; protected Date previousRun; protected Serializable info; protected TimerState timerState; protected boolean persistent; protected boolean newTimer; public Builder setId(final String id) { this.id = id; return this; } public Builder setTimedObjectId(final String timedObjectId) { this.timedObjectId = timedObjectId; return this; } public Builder setInitialDate(final Date initialDate) { this.initialDate = initialDate; return this; } public Builder setRepeatInterval(final long repeatInterval) { this.repeatInterval = repeatInterval; return this; } public Builder setNextDate(final Date nextDate) { this.nextDate = nextDate; return this; } public Builder setPreviousRun(final Date previousRun) { this.previousRun = previousRun; return this; } public Builder setInfo(final Serializable info) { this.info = info; return this; } public Builder setTimerState(final TimerState timerState) { this.timerState = timerState; return this; } public Builder setPersistent(final boolean persistent) { this.persistent = persistent; return this; } public Builder setNewTimer(final boolean newTimer) { this.newTimer = newTimer; return this; } public String getId() { return id; } public String getTimedObjectId() { return timedObjectId; } public TimerImpl build(final TimerServiceImpl timerService) { return new TimerImpl(this, timerService); } } }
20,080
29.658015
200
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/TimerServiceMetaData.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice; import org.jboss.metadata.ejb.parser.jboss.ejb3.AbstractEJBBoundMetaData; /** * Encapsulates timer service meta data for an EJB component. * @author Stuart Douglas * @author Paul Ferraro */ public class TimerServiceMetaData extends AbstractEJBBoundMetaData { private static final long serialVersionUID = 8290412083429128705L; private String dataStoreName; private String persistentProvider; private String transientProvider; public String getDataStoreName() { return dataStoreName; } public void setDataStoreName(final String dataStoreName) { this.dataStoreName = dataStoreName; } public String getPersistentTimerManagementProvider() { return this.persistentProvider; } public void setPersistentTimerManagementProvider(String persistentProvider) { this.persistentProvider = persistentProvider; } public String getTransientTimerManagementProvider() { return this.transientProvider; } public void setTransientTimerManagementProvider(String transientProvider) { this.transientProvider = transientProvider; } @Override public String toString() { return String.format("data-store=%s, persistent-provider=%s, transient-provider=%s", this.dataStoreName, this.persistentProvider, this.transientProvider); } }
2,411
34.470588
162
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/CalendarTimer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice; import java.lang.reflect.Method; import java.util.Calendar; import java.util.Date; import jakarta.ejb.EJBException; import jakarta.ejb.ScheduleExpression; import jakarta.ejb.Timer; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.timerservice.persistence.TimeoutMethod; import org.jboss.as.ejb3.timerservice.schedule.CalendarBasedTimeout; /** * Represents a {@link jakarta.ejb.Timer} which is created out a calendar expression * * @author Jaikiran Pai * @version $Revision: $ */ public class CalendarTimer extends TimerImpl { /** * The calendar based timeout for this timer */ private final CalendarBasedTimeout calendarTimeout; /** * Represents whether this is an auto-timer or a normal * programmatically created timer */ private final boolean autoTimer; private final Method timeoutMethod; public CalendarTimer(Builder builder, TimerServiceImpl timerService) { super(builder, timerService); this.autoTimer = builder.autoTimer; if (autoTimer) { assert builder.timeoutMethod != null; this.timeoutMethod = builder.timeoutMethod; } else { assert builder.timeoutMethod == null; this.timeoutMethod = null; } this.calendarTimeout = new CalendarBasedTimeout(builder.scheduleExpression); if (builder.nextDate == null && builder.newTimer) { // compute the next timeout (from "now") Calendar nextTimeout = this.calendarTimeout.getNextTimeout(); if (nextTimeout != null) { this.nextExpiration = nextTimeout.getTime(); } } } /** * {@inheritDoc} * * @see #getScheduleExpression() */ @Override public ScheduleExpression getSchedule() throws IllegalStateException, EJBException { this.validateInvocationContext(); return this.calendarTimeout.getScheduleExpression(); } /** * This method is similar to {@link #getSchedule()}, except that this method does <i>not</i> check the timer state * and hence does <i>not</i> throw either {@link IllegalStateException} or {@link jakarta.ejb.NoSuchObjectLocalException} * or {@link jakarta.ejb.EJBException}. * * @return */ public ScheduleExpression getScheduleExpression() { return this.calendarTimeout.getScheduleExpression(); } /** * {@inheritDoc} */ @Override public boolean isCalendarTimer() throws IllegalStateException, EJBException { this.validateInvocationContext(); return true; } /** * Returns the {@link CalendarBasedTimeout} corresponding to this * {@link CalendarTimer} * * @return */ public CalendarBasedTimeout getCalendarTimeout() { return this.calendarTimeout; } /** * Returns true if this is an auto-timer. Else returns false. */ @Override public boolean isAutoTimer() { return autoTimer; } /** * Returns the task which handles the timeouts on this {@link CalendarTimer} * * @see CalendarTimerTask */ @Override protected CalendarTimerTask getTimerTask() { return new CalendarTimerTask(this); } public Method getTimeoutMethod() { if (!this.autoTimer) { throw EjbLogger.EJB3_TIMER_LOGGER.failToInvokegetTimeoutMethod(); } return this.timeoutMethod; } public static Builder builder() { return new Builder(); } /** * Makes sure that the timer is only run once after being restored. */ public void handleRestorationCalculation() { if(nextExpiration == null) { return; } //next expiration in the future, we don't care if(nextExpiration.getTime() >= System.currentTimeMillis()) { return; } //just set the next expiration to 1ms in the past //this means it will run to catch up the missed expiration //and then the next calculated expiration will be in the future nextExpiration = new Date(System.currentTimeMillis() - 1); } public static class Builder extends TimerImpl.Builder { private ScheduleExpression scheduleExpression; private boolean autoTimer; private Method timeoutMethod; public Builder setScheduleExpression(final ScheduleExpression scheduleExpression) { this.scheduleExpression = scheduleExpression; return this; } public Builder setAutoTimer(final boolean autoTimer) { this.autoTimer = autoTimer; return this; } public Builder setTimeoutMethod(final Method timeoutMethod) { this.timeoutMethod = timeoutMethod; return this; } public CalendarTimer build(final TimerServiceImpl timerService) { return new CalendarTimer(this, timerService); } } /** * Returns the {@link java.lang.reflect.Method}, represented by the {@link org.jboss.as.ejb3.timerservice.persistence.TimeoutMethod} * <p> * Note: This method uses the {@link Thread#getContextClassLoader()} to load the * relevant classes while getting the {@link java.lang.reflect.Method} * </p> * * @param timeoutMethodInfo The timeout method * @param classLoader The class loader * @return timeout method matching {@code timeoutMethodInfo} */ public static Method getTimeoutMethod(TimeoutMethod timeoutMethodInfo, ClassLoader classLoader) { if(timeoutMethodInfo == null) { return null; } Class<?> timeoutMethodDeclaringClass; try { timeoutMethodDeclaringClass = Class.forName(timeoutMethodInfo.getDeclaringClass(), false, classLoader); } catch (ClassNotFoundException cnfe) { throw EjbLogger.EJB3_TIMER_LOGGER.failToLoadDeclaringClassOfTimeOut(timeoutMethodInfo.getDeclaringClass()); } // now start looking for the method String timeoutMethodName = timeoutMethodInfo.getMethodName(); Class<?> klass = timeoutMethodDeclaringClass; while (klass != null) { Method[] methods = klass.getDeclaredMethods(); for (Method method : methods) { if (method.getName().equals(timeoutMethodName)) { if (timeoutMethodInfo.hasTimerParameter()) { if (method.getParameterCount() == 1 && method.getParameterTypes()[0] == Timer.class) { return method; } } else if (method.getParameterCount() == 0) { return method; } } // end: method name matching } // end: all methods in current klass klass = klass.getSuperclass(); } // no match found return null; } /** * {@inheritDoc}. For calendar-based timer, the string output also includes its schedule expression value. * * @return a string representation of calendar-based timer */ @Override public String toString() { return super.toString() + " " + getScheduleExpression(); } }
8,358
32.842105
136
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/TimerServiceRegistryImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice; import java.util.Collection; import java.util.Collections; import java.util.IdentityHashMap; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import jakarta.ejb.Timer; import jakarta.ejb.TimerService; import org.jboss.as.ejb3.timerservice.spi.TimerServiceRegistry; /** * A registry to which individual {@link jakarta.ejb.TimerService timer services} can register to (and un-register from). The main purpose * of this registry is to provide an implementation of {@link #getAllActiveTimers()} which returns all * {@link jakarta.ejb.TimerService#getTimers() active timers} after querying each of the {@link jakarta.ejb.TimerService timer services} registered * with this {@link TimerServiceRegistry registry}. * <p/> * Typical use of this registry is to maintain one instance of this registry, per deployment unit (also known as Jakarta Enterprise Beans module) and register the timer * services of all Jakarta Enterprise Beans components that belong to that deployment unit. Effectively, such an instance can then be used to fetch all active timers * that are applicable to that deployment unit (a.k.a Jakarta Enterprise Beans module). * * @author Jaikiran Pai */ public class TimerServiceRegistryImpl implements TimerServiceRegistry { private static final Function<TimerService, Collection<Timer>> GET_TIMERS = TimerService::getTimers; private static final Function<Collection<Timer>, Stream<Timer>> STREAM = Collection::stream; private final Set<TimerService> services = Collections.synchronizedSet(Collections.newSetFromMap(new IdentityHashMap<>())); @Override public void registerTimerService(TimerService service) { this.services.add(service); } @Override public void unregisterTimerService(TimerService service) { this.services.remove(service); } @Override public Collection<Timer> getAllTimers() { synchronized (this.services) { return Collections.unmodifiableCollection(this.services.stream().map(GET_TIMERS).flatMap(STREAM).collect(Collectors.toList())); } } }
3,221
42.540541
168
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/TimedObjectInvokerImpl.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice; import static org.jboss.as.ejb3.util.MethodInfoHelper.EMPTY_STRING_ARRAY; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import jakarta.ejb.Timer; import org.jboss.as.ee.component.Component; import org.jboss.as.ee.component.interceptors.InvocationType; import org.jboss.as.ejb3.component.EJBComponent; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.timerservice.spi.TimedObjectInvoker; import org.jboss.invocation.Interceptor; import org.jboss.invocation.InterceptorContext; import org.jboss.invocation.InterceptorFactory; import org.jboss.invocation.InterceptorFactoryContext; import org.jboss.invocation.SimpleInterceptorFactoryContext; import org.jboss.metadata.ejb.spec.MethodInterfaceType; import org.jboss.modules.Module; import org.wildfly.extension.requestcontroller.ControlPoint; import org.wildfly.extension.requestcontroller.RunResult; /** * Timed object invoker for an enterprise bean. This is analogous to a view service for timer invocations * * @author Stuart Douglas * @author Paul Ferraro */ public class TimedObjectInvokerImpl implements TimedObjectInvoker { private final String timedObjectId; private final EJBComponent component; private final Module module; private final Map<Method, Interceptor> interceptors = new HashMap<>(); public TimedObjectInvokerImpl(Module module, String deploymentName, EJBComponent component) { this.module = module; this.timedObjectId = deploymentName + '.' + component.getComponentName(); this.component = component; InterceptorFactoryContext factoryContext = new SimpleInterceptorFactoryContext(); factoryContext.getContextData().put(Component.class, component); for (Map.Entry<Method, InterceptorFactory> entry : component.getTimeoutInterceptors().entrySet()) { this.interceptors.put(entry.getKey(), entry.getValue().create(factoryContext)); } } @Override public void callTimeout(Timer timer, Method method) throws Exception { ControlPoint controlPoint = this.component.getControlPoint(); if (controlPoint != null) { if (controlPoint.beginRequest() == RunResult.REJECTED) { throw EjbLogger.EJB3_TIMER_LOGGER.containerSuspended(); } try { this.invoke(timer, method); } finally { controlPoint.requestComplete(); } } else { this.invoke(timer, method); } } private void invoke(Timer timer, Method method) throws Exception { Interceptor interceptor = this.interceptors.get(method); if (interceptor == null) { throw EjbLogger.EJB3_TIMER_LOGGER.failToInvokeTimeout(method); } InterceptorContext context = new InterceptorContext(); context.setContextData(new HashMap<>()); context.setMethod(method); context.setParameters(method.getParameterCount() == 0 ? EMPTY_STRING_ARRAY : new Object[] { timer }); context.setTimer(timer); context.putPrivateData(Component.class, this.component); context.putPrivateData(MethodInterfaceType.class, MethodInterfaceType.Timer); context.putPrivateData(InvocationType.class, InvocationType.TIMER); interceptor.processInvocation(context); } @Override public EJBComponent getComponent() { return this.component; } @Override public String getTimedObjectId() { return this.timedObjectId; } @Override public ClassLoader getClassLoader() { return this.module.getClassLoader(); } @Override public int hashCode() { return this.timedObjectId.hashCode(); } @Override public boolean equals(Object object) { if (!(object instanceof TimedObjectInvoker)) return false; return this.timedObjectId.equals(((TimedObjectInvoker) object).getTimedObjectId()); } @Override public String toString() { return this.timedObjectId; } }
5,120
36.654412
109
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/TimerServiceImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice; import static org.jboss.as.ejb3.logging.EjbLogger.EJB3_TIMER_LOGGER; import java.io.Closeable; import java.io.Serializable; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.function.Predicate; import jakarta.ejb.EJBException; import jakarta.ejb.ScheduleExpression; import jakarta.ejb.Timer; import jakarta.ejb.TimerConfig; import jakarta.transaction.RollbackException; import jakarta.transaction.Status; import jakarta.transaction.Synchronization; import jakarta.transaction.SystemException; import jakarta.transaction.Transaction; import jakarta.transaction.TransactionSynchronizationRegistry; import org.jboss.as.ejb3.context.CurrentInvocationContext; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.timerservice.persistence.TimerPersistence; import org.jboss.as.ejb3.timerservice.persistence.database.DatabaseTimerPersistence; import org.jboss.as.ejb3.timerservice.schedule.CalendarBasedTimeout; import org.jboss.as.ejb3.timerservice.spi.AutoTimer; import org.jboss.as.ejb3.timerservice.spi.ManagedTimer; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerService; import org.jboss.as.ejb3.timerservice.spi.TimedObjectInvoker; import org.jboss.as.ejb3.timerservice.spi.TimerListener; import org.jboss.as.ejb3.timerservice.spi.TimerServiceRegistry; import org.jboss.invocation.InterceptorContext; import org.wildfly.extension.requestcontroller.ControlPoint; import org.wildfly.transaction.client.ContextTransactionManager; /** * MK2 implementation of Enterprise Beans 3.1 {@link ManagedTimerService} * * @author <a href="mailto:[email protected]">Carlo de Wolf</a> * @version $Revision: $ */ public class TimerServiceImpl implements ManagedTimerService { /** * Flag to enable programmatic timer refresh from database timer persistence. * When set to true, {@link #getAllTimers()} method programmatically refreshes * from the database timer persistence before returning all timers. */ private static final String PROGRAMMATIC_TIMER_REFRESH_ENABLED = "wildfly.ejb.timer.refresh.enabled"; /** * All timers which were created by this {@link ManagedTimerService} */ private final ConcurrentMap<String, TimerImpl> timers = new ConcurrentHashMap<>(); /** * Holds the {@link java.util.concurrent.Future} of each of the timer tasks that have been scheduled */ private final ConcurrentMap<String, java.util.TimerTask> scheduledTimerFutures = new ConcurrentHashMap<>(); /** * Key that is used to store timers that are waiting on transaction completion in the transaction local */ private final Object waitingOnTxCompletionKey = new Object(); private final ExecutorService executor; private final java.util.Timer timer; private final TimedObjectInvoker invoker; private final TimerPersistence persistence; private final TimerServiceRegistry timerServiceRegistry; private final TimerListener timerListener; private final Predicate<TimerConfig> timerFilter; private Closeable listenerHandle; private volatile boolean started = false; private static final Integer MAX_RETRY = Integer.getInteger("jboss.timer.TaskPostPersist.maxRetry", 10); /** * Creates a {@link TimerServiceImpl}. * @param configuration the configuration of this timer service */ public TimerServiceImpl(TimerServiceConfiguration configuration) { this.invoker = configuration.getInvoker(); this.executor = configuration.getExecutor(); this.timer = configuration.getTimer(); this.persistence = configuration.getTimerPersistence(); this.timerServiceRegistry = configuration.getTimerServiceRegistry(); this.timerListener = configuration.getTimerListener(); this.timerFilter = configuration.getTimerFilter(); } @Override public synchronized void start() { if (EJB3_TIMER_LOGGER.isDebugEnabled()) { EJB3_TIMER_LOGGER.debug("Starting timerservice for timedObjectId: " + getInvoker().getTimedObjectId()); } started = true; if (this.persistence != null) { this.persistence.timerDeployed(this.invoker.getTimedObjectId()); } this.timerServiceRegistry.registerTimerService(this); if (this.persistence != null) { this.listenerHandle = this.persistence.registerChangeListener(this.invoker.getTimedObjectId(), new TimerRefreshListener()); } Map<Method, List<AutoTimer>> autoTimers = this.invoker.getComponent().getComponentDescription().getScheduleMethods(); final List<AutoTimer> timers; if (autoTimers.isEmpty()) { timers = Collections.emptyList(); } else { timers = new ArrayList<>(); for (Map.Entry<Method, List<AutoTimer>> entry : autoTimers.entrySet()) { for (AutoTimer timer : entry.getValue()) { if (this.timerFilter.test(timer.getTimerConfig())) { timers.add(new AutoTimer(timer.getScheduleExpression(), timer.getTimerConfig(), entry.getKey())); } } } } // restore the timers restoreTimers(timers); } @Override public synchronized void stop() { suspendTimers(); this.timerServiceRegistry.unregisterTimerService(this); if (this.persistence != null) { this.persistence.timerUndeployed(this.invoker.getTimedObjectId()); } started = false; safeClose(listenerHandle); listenerHandle = null; this.timer.purge(); //WFLY-3823 } @Override public Timer createCalendarTimer(ScheduleExpression schedule, TimerConfig timerConfig) { this.validateInvocationContext(); if (schedule == null) { throw EJB3_TIMER_LOGGER.invalidTimerParameter("schedule", null); } final ScheduleExpression scheduleClone = new ScheduleExpression() .second(schedule.getSecond()) .minute(schedule.getMinute()) .hour(schedule.getHour()) .dayOfMonth(schedule.getDayOfMonth()) .dayOfWeek(schedule.getDayOfWeek()) .month(schedule.getMonth()) .year(schedule.getYear()) .timezone(schedule.getTimezone()) .start(schedule.getStart()) .end(schedule.getEnd()); Serializable info = timerConfig == null ? null : timerConfig.getInfo(); boolean persistent = timerConfig == null || timerConfig.isPersistent(); return this.createCalendarTimer(scheduleClone, info, persistent, null); } @Override public Timer createIntervalTimer(Date initialExpiration, long intervalDuration, TimerConfig timerConfig) { this.validateInvocationContext(); if (initialExpiration == null) { throw EJB3_TIMER_LOGGER.invalidTimerParameter("initialExpiration", null); } if (initialExpiration.getTime() < 0) { throw EJB3_TIMER_LOGGER.invalidTimerParameter("initialExpiration.getTime()", Long.toString(initialExpiration.getTime())); } if (intervalDuration < 0) { throw EJB3_TIMER_LOGGER.invalidTimerParameter("intervalDuration", Long.toString(intervalDuration)); } return this.createTimer(initialExpiration, intervalDuration, timerConfig.getInfo(), timerConfig.isPersistent()); } @Override public Timer createSingleActionTimer(Date expiration, TimerConfig timerConfig) { this.validateInvocationContext(); if (expiration == null) { throw EJB3_TIMER_LOGGER.invalidTimerParameter("expiration", null); } if (expiration.getTime() < 0) { throw EJB3_TIMER_LOGGER.invalidTimerParameter("expiration.getTime", Long.toString(expiration.getTime())); } return this.createTimer(expiration, 0, timerConfig.getInfo(), timerConfig.isPersistent()); } public TimerImpl loadAutoTimer(ScheduleExpression schedule,TimerConfig timerConfig, Method timeoutMethod) { return this.createCalendarTimer(schedule, timerConfig.getInfo(), timerConfig.isPersistent(), timeoutMethod); } @Override public Collection<Timer> getTimers() { this.validateInvocationContext(); // get all active timers for this timerservice final Collection<TimerImpl> values = this.timers.values(); final List<Timer> activeTimers = new ArrayList<>(values.size() + 10); for (final TimerImpl timer : values) { // Less disruptive way to get WFLY-8457 fixed. if (timer.isActive() || timer.getState() == TimerState.ACTIVE) { activeTimers.add(timer); } } // get all active timers which are persistent, but haven't yet been // persisted (waiting for tx to complete) that are in the current transaction for (final TimerImpl timer : getWaitingOnTxCompletionTimers().values()) { if (timer.isActive()) { activeTimers.add(timer); } } return activeTimers; } /** * {@inheritDoc} * <p> * When {@link #PROGRAMMATIC_TIMER_REFRESH_ENABLED} is set to true, * this method programmatically refreshes from the database timer persistence * before returning all timers. */ @Override public Collection<Timer> getAllTimers() throws IllegalStateException, EJBException { if (this.persistence instanceof DatabaseTimerPersistence) { final InterceptorContext currentInvocationContext = CurrentInvocationContext.get(); if (currentInvocationContext != null) { try { final Map<String, Object> contextData = currentInvocationContext.getContextData(); final Object flag = contextData.get(PROGRAMMATIC_TIMER_REFRESH_ENABLED); if (Boolean.TRUE.equals(flag) || "true".equals(flag)) { ((DatabaseTimerPersistence) this.persistence).refreshTimers(); } } catch (IllegalStateException e) { //ignore, context data is not set } } } return this.timerServiceRegistry.getAllTimers(); } /** * Create a {@link jakarta.ejb.Timer}. Caller of this method should already have checked for allowed operations, * and validated parameters. * * @param initialExpiration The {@link java.util.Date} at which the first timeout should occur. * <p>If the date is in the past, then the timeout is triggered immediately * when the timer moves to {@link TimerState#ACTIVE}</p> * @param intervalDuration The interval (in milliseconds) between consecutive timeouts for the newly created timer. * <p>Cannot be a negative value. A value of 0 indicates a single timeout action</p> * @param info {@link java.io.Serializable} info that will be made available through the newly created timer's {@link jakarta.ejb.Timer#getInfo()} method * @param persistent True if the newly created timer has to be persistent * @return Returns the newly created timer */ private Timer createTimer(Date initialExpiration, long intervalDuration, Serializable info, boolean persistent) { // allowed method check and parameter validation are already done in all code paths before reaching here. // create an id for the new timer instance UUID uuid = UUID.randomUUID(); // create the timer TimerImpl timer = TimerImpl.builder() .setNewTimer(true) .setId(uuid.toString()) .setInitialDate(initialExpiration) .setRepeatInterval(intervalDuration) .setInfo(info) .setPersistent(persistent) .setTimerState(TimerState.CREATED) .setTimedObjectId(getInvoker().getTimedObjectId()) .build(this); // now "start" the timer. This involves, moving the timer to an ACTIVE state // and scheduling the timer task this.persistTimer(timer, true); this.startTimer(timer); // return the newly created timer return timer; } /** * Creates a calendar based {@link jakarta.ejb.Timer}. Caller of this method should * already have checked for allowed operations, and validated parameters. * * @param schedule The {@link jakarta.ejb.ScheduleExpression} which will be used for creating scheduled timer tasks * for a calendar based timer * @param info {@link java.io.Serializable} info that will be made available through the newly created timer's {@link jakarta.ejb.Timer#getInfo()} method * @param persistent True if the newly created timer has to be persistent * @return Returns the newly created timer */ private TimerImpl createCalendarTimer(ScheduleExpression schedule, Serializable info, boolean persistent, Method timeoutMethod) { // allowed method check and parameter validation are already done in all code paths before reaching here. // generate an id for the timer UUID uuid = UUID.randomUUID(); // create the timer TimerImpl timer = CalendarTimer.builder() .setAutoTimer(timeoutMethod != null) .setScheduleExpression(schedule) .setTimeoutMethod(timeoutMethod) .setTimerState(TimerState.CREATED) .setId(uuid.toString()) .setPersistent(persistent) .setTimedObjectId(getInvoker().getTimedObjectId()) .setInfo(info) .setNewTimer(true) .build(this); this.persistTimer(timer, true); // now "start" the timer. This involves, moving the timer to an ACTIVE state // and scheduling the timer task // If an auto timer has been persisted by another node, it will be marked as CANCELED // during the persistTimer(timer, true) call above. This timer will be created or started. if (timeoutMethod != null && timer.getState() == TimerState.CANCELED) { EJB3_TIMER_LOGGER.debugv("The auto timer was already created by other node: {0}", timer); return timer; } this.startTimer(timer); // return the timer return timer; } public TimerImpl getTimer(final String timerId) { return this.timers.get(timerId); } /** * Retrieves the timer info from the timer database. * * @param timer the timer whose info to be retrieved * @return the timer info from database; cached timer info if the timer persistence store is not database */ public Serializable getPersistedTimerInfo(final TimerImpl timer) { if (this.persistence instanceof DatabaseTimerPersistence) { final DatabaseTimerPersistence databasePersistence = (DatabaseTimerPersistence) this.persistence; return databasePersistence.getPersistedTimerInfo(timer); } return timer.getCachedTimerInfo(); } /** * Returns the {@link TimedObjectInvoker} to which this timer service belongs * * @return */ @Override public TimedObjectInvoker getInvoker() { return this.invoker; } /** * Returns the timer corresponding to the passed timer id and timed object id. * * @param timerId timer id * @param timedObjectId timed object id * @return the {@code TimerImpl} corresponding to the passed timer id and timed object id */ @Override public ManagedTimer findTimer(final String timerId) { TimerImpl timer; timer = this.timers.get(timerId); if (timer != null) { return timer; } timer = getWaitingOnTxCompletionTimers().get(timerId); if (timer != null) { return timer; } if (this.persistence instanceof DatabaseTimerPersistence) { timer = ((DatabaseTimerPersistence) this.persistence).loadTimer(this.getInvoker().getTimedObjectId(), timerId, this); } return timer; } /** * @return Returns the current transaction, if any. Else returns null. * @throws jakarta.ejb.EJBException If there is any system level exception */ protected Transaction getTransaction() { return ContextTransactionManager.getInstance().getTransaction(); } /** * Persists the passed <code>timer</code>. * <p/> * <p> * If the passed timer is null or is non-persistent (i.e. {@link jakarta.ejb.Timer#isPersistent()} returns false), * then this method acts as a no-op * </p> * * @param timer */ public void persistTimer(final TimerImpl timer, boolean newTimer) { if (timer == null) { return; } if (timer.persistent) { try { if (this.persistence == null) { EJB3_TIMER_LOGGER.timerPersistenceNotEnable(); return; } final ContextTransactionManager transactionManager = ContextTransactionManager.getInstance(); Transaction clientTX = transactionManager.getTransaction(); if (newTimer || timer.isCanceled()) { if (clientTX == null) { transactionManager.begin(); } try { if (newTimer) this.persistence.addTimer(timer); else this.persistence.persistTimer(timer); if (clientTX == null) transactionManager.commit(); } catch (Exception e) { if (clientTX == null) { try { transactionManager.rollback(); } catch (Exception ee) { EjbLogger.EJB3_TIMER_LOGGER.timerUpdateFailedAndRollbackNotPossible(ee); } } throw e; } } else { new TaskPostPersist(timer).persistTimer(); } } catch (Throwable t) { this.setRollbackOnly(); throw new RuntimeException(t); } } } public void cancelTimer(final TimerImpl timer) throws InterruptedException { timer.lock(); boolean release = true; try { timer.validateInvocationContext(); // first check whether the timer has expired or has been cancelled if (timer.getState() != TimerState.EXPIRED) { timer.setTimerState(TimerState.CANCELED, null); } release = removeTimer(timer); // persist changes persistTimer(timer, false); } finally { if (release) { timer.unlock(); } } } private boolean removeTimer(final TimerImpl timer) { boolean startedInTx = getWaitingOnTxCompletionTimers().containsKey(timer.getId()); if (ManagedTimerService.getActiveTransaction() != null && !startedInTx) { registerSynchronization(new TimerRemoveSynchronization(timer)); return false; } else { // cancel any scheduled Future for this timer this.cancelTimeout(timer); this.unregisterTimerResource(timer.getId()); return true; } } public void expireTimer(final TimerImpl timer) { this.cancelTimeout(timer); timer.setTimerState(TimerState.EXPIRED, null); this.unregisterTimerResource(timer.getId()); } /** * Suspends any currently scheduled tasks for {@link jakarta.ejb.Timer}s * <p> * Note that, suspend does <b>not</b> cancel the {@link jakarta.ejb.Timer}. Instead, * it just cancels the <b>next scheduled timeout</b>. So once the {@link jakarta.ejb.Timer} * is restored (whenever that happens), the {@link jakarta.ejb.Timer} will continue to * timeout at appropriate times. * </p> */ public void suspendTimers() { // get all active timers (persistent/non-persistent inclusive) Collection<jakarta.ejb.Timer> timers = this.getTimers(); for (jakarta.ejb.Timer timer : timers) { if (!(timer instanceof TimerImpl)) { continue; } // suspend the timer ((TimerImpl) timer).suspend(); } } /** * Restores persisted timers, corresponding to this timerservice, which are eligible for any new timeouts. * <p> * This includes timers whose {@link TimerState} is <b>neither</b> of the following: * <ul> * <li>{@link TimerState#CANCELED}</li> * <li>{@link TimerState#EXPIRED}</li> * </ul> * </p> * <p> * All such restored timers will be schedule for their next timeouts. * </p> * * @param newAutoTimers */ public void restoreTimers(final List<AutoTimer> newAutoTimers) { // get the persisted timers which are considered active List<TimerImpl> restorableTimers = this.getActivePersistentTimers(); if (EJB3_TIMER_LOGGER.isDebugEnabled()) { EJB3_TIMER_LOGGER.debug("Found " + restorableTimers.size() + " active persistentTimers for timedObjectId: " + getInvoker().getTimedObjectId()); } // now "start" each of the restorable timer. This involves, moving the timer to an ACTIVE state // and scheduling the timer task for (final TimerImpl activeTimer : restorableTimers) { if (activeTimer.isAutoTimer()) { CalendarTimer calendarTimer = (CalendarTimer) activeTimer; boolean found = false; //so we know we have an auto timer. We need to try and match it up with the auto timers. ListIterator<AutoTimer> it = newAutoTimers.listIterator(); while (it.hasNext()) { AutoTimer timer = it.next(); if (doesTimeoutMethodMatch(calendarTimer.getTimeoutMethod(), timer.getMethod())) { //the timers have the same method. //now lets make sure the schedule is the same, info is the same, // and the timer does not change the persistence if (CalendarBasedTimeout.doesScheduleMatch(calendarTimer.getScheduleExpression(), timer.getScheduleExpression()) && Objects.equals(calendarTimer.info, timer.getTimerConfig().getInfo()) && timer.getTimerConfig().isPersistent()) { it.remove(); found = true; break; } } } if (!found) { activeTimer.setTimerState(TimerState.CANCELED, null); } else { // ensure state switch to active if was TIMEOUT in the DB // if the persistence is shared it must be ensured to not update // timers of other nodes in the cluster activeTimer.setTimerState(TimerState.ACTIVE, null); calendarTimer.handleRestorationCalculation(); } try { this.persistTimer(activeTimer, false); } catch (Exception e) { EJB3_TIMER_LOGGER.failedToPersistTimerOnStartup(activeTimer, e); } if (found) { startTimer(activeTimer); EJB3_TIMER_LOGGER.debugv("Started existing auto timer: {0}", activeTimer); } } else if (!TimerState.EXPIRED_CANCELED.contains(activeTimer.getState())) { startTimer(activeTimer); } EJB3_TIMER_LOGGER.debugv("Started timer: {0}", activeTimer); } for (AutoTimer timer : newAutoTimers) { this.loadAutoTimer(timer.getScheduleExpression(), timer.getTimerConfig(), timer.getMethod()); } } /** * Registers a timer with a transaction (if any in progress) and then moves * the timer to an active state, so that it becomes eligible for timeouts */ protected void startTimer(TimerImpl timer) { // if there's no transaction, then trigger a schedule immediately. // Else, the timer will be scheduled on tx synchronization callback if (ManagedTimerService.getActiveTransaction() == null) { // set active if the timer is started if it was read // from persistence as current running to ensure correct schedule here timer.setTimerState(TimerState.ACTIVE, null); // create and schedule a timer task if (!this.registerTimerResource(timer)) { return; } timer.scheduleTimeout(true); } else { addWaitingOnTxCompletionTimer(timer); registerSynchronization(new TimerCreationTransactionSynchronization(timer)); } } private void registerSynchronization(Synchronization synchronization) { try { final Transaction tx = this.getTransaction(); // register for lifecycle events of transaction tx.registerSynchronization(synchronization); } catch (RollbackException e) { throw new EJBException(e); } catch (SystemException e) { throw new EJBException(e); } } /** * Creates and schedules a {@link TimerTask} for the next timeout of the passed <code>timer</code> */ protected void scheduleTimeout(TimerImpl timer, boolean newTimer) { if (!newTimer && !scheduledTimerFutures.containsKey(timer.getId())) { //this timer has been cancelled by another thread. We just return return; } Date nextExpiration = timer.getNextExpiration(); if (nextExpiration == null) { EJB3_TIMER_LOGGER.nextExpirationIsNull(timer); return; } // create the timer task final TimerTask timerTask = timer.getTimerTask(); // find out how long is it away from now final long currentTime = System.currentTimeMillis(); long delay = nextExpiration.getTime() - currentTime; long intervalDuration = timer.getInterval(); final Task task = new Task(timerTask, this.invoker.getComponent().getControlPoint()); // maintain it in timerservice for future use (like cancellation) scheduledTimerFutures.compute(timer.getId(), (k, v) -> timer.isCanceled() ? null : task); // schedule the task if (intervalDuration > 0) { EJB3_TIMER_LOGGER.debugv("Scheduling timer {0} at fixed rate, starting at {1} milliseconds from now with repeated interval={2}", timer, delay, intervalDuration); // if in past, then trigger immediately if (delay < 0) { delay = 0; } this.timer.scheduleAtFixedRate(task, delay, intervalDuration); } else { EJB3_TIMER_LOGGER.debugv("Scheduling a single action timer {0} starting at {1} milliseconds from now", timer, delay); // if in past, then trigger immediately; if overdue by 5 minutes, set next expiration to current time if (delay < 0) { if (delay < -300000) { timer.nextExpiration = new Date(currentTime); } delay = 0; } this.timer.schedule(task, delay); } } /** * Cancels any scheduled {@link java.util.concurrent.Future} corresponding to the passed <code>timer</code> * * @param timer the timer to cancel */ protected void cancelTimeout(final TimerImpl timer) { scheduledTimerFutures.computeIfPresent(timer.getId(), (k, v) -> { v.cancel(); return null; }); } public boolean isScheduled(final String tid) { return this.scheduledTimerFutures.containsKey(tid); } /** * Returns an unmodifiable view of timers in the current transaction that are waiting for the transaction * to finish */ private Map<String, TimerImpl> getWaitingOnTxCompletionTimers() { Map<String, TimerImpl> timers = null; if (getTransaction() != null) { TransactionSynchronizationRegistry tsr = this.invoker.getComponent().getTransactionSynchronizationRegistry(); timers = (Map<String, TimerImpl>) tsr.getResource(waitingOnTxCompletionKey); } return timers == null ? Collections.<String, TimerImpl>emptyMap() : timers; } private void addWaitingOnTxCompletionTimer(final TimerImpl timer) { TransactionSynchronizationRegistry tsr = this.invoker.getComponent().getTransactionSynchronizationRegistry(); Map<String, TimerImpl> timers = (Map<String, TimerImpl>) tsr.getResource(waitingOnTxCompletionKey); if (timers == null) { tsr.putResource(waitingOnTxCompletionKey, timers = new HashMap<String, TimerImpl>()); } timers.put(timer.getId(), timer); } private boolean isSingletonBeanInvocation() { return this.invoker.getComponent().getComponentDescription().isSingleton(); } private List<TimerImpl> getActivePersistentTimers() { // we need only those timers which correspond to the // timed object invoker to which this timer service belongs. So // first get hold of the timed object id final String timedObjectId = this.getInvoker().getTimedObjectId(); // timer states which do *not* represent an active timer if (this.persistence == null) { //if the persistence setting is null then there are no persistent timers return Collections.emptyList(); } final ContextTransactionManager transactionManager = ContextTransactionManager.getInstance(); List<TimerImpl> persistedTimers; try { transactionManager.begin(); persistedTimers = this.persistence.loadActiveTimers(timedObjectId, this); transactionManager.commit(); } catch (Exception e) { try { transactionManager.rollback(); } catch (Exception ee) { // omit; } persistedTimers = Collections.emptyList(); EJB3_TIMER_LOGGER.timerReinstatementFailed(timedObjectId, "unavailable", e); } final List<TimerImpl> activeTimers = new ArrayList<TimerImpl>(); for (final TimerImpl persistedTimer : persistedTimers) { if (TimerState.EXPIRED_CANCELED.contains(persistedTimer.getState())) { continue; } // add it to the list of timers which will be restored activeTimers.add(persistedTimer); } return activeTimers; } private static boolean doesTimeoutMethodMatch(final Method timeoutMethod, final Method method2) { if (timeoutMethod.getName().equals(method2.getName())) { if (timeoutMethod.getParameterCount() == 0 && method2.getParameterCount() == 0) { return true; } if (timeoutMethod.getParameterCount() == 1 && method2.getParameterCount() == 1) { return timeoutMethod.getParameterTypes()[0] == method2.getParameterTypes()[0]; } } return false; } /** * Marks the transaction for rollback * NOTE: This method will soon be removed, once this timer service * implementation becomes "managed" */ private void setRollbackOnly() { try { Transaction tx = ContextTransactionManager.getInstance().getTransaction(); if (tx != null) { tx.setRollbackOnly(); } } catch (IllegalStateException ise) { EJB3_TIMER_LOGGER.ignoringException(ise); } catch (SystemException se) { EJB3_TIMER_LOGGER.ignoringException(se); } } public boolean isStarted() { return started; } @Override public String toString() { return String.format("%s(%s)", this.getClass().getSimpleName(), this.invoker.getTimedObjectId()); } private boolean registerTimerResource(final TimerImpl timer) { final TimerImpl previousValue = this.timers.putIfAbsent(timer.getId(), timer); if (previousValue != null) { return false; } this.timerListener.timerAdded(timer.getId()); return true; } private void unregisterTimerResource(final String timerId) { this.timers.remove(timerId); this.timerListener.timerRemoved(timerId); } /** * Check if a persistent timer is already executed from a different instance * or should be executed. * For non-persistent timer it always return <code>true</code>. * * @param timer the timer which should be checked * @return <code>true</code> if the timer is not persistent or the persistent timer should start */ public boolean shouldRun(TimerImpl timer) { // check peristent without further check to prevent from Exception (WFLY-6152) return !timer.persistent || this.persistence.shouldRun(timer); } /** * Safely closes some resource without throwing an exception. * Any exception will be logged at TRACE level. * * @param resource the resource to close */ public static void safeClose(final AutoCloseable resource) { if (resource != null) { try { resource.close(); } catch (Throwable t) { EjbLogger.EJB3_TIMER_LOGGER.tracef(t, "Closing resource failed"); } } } private class TimerCreationTransactionSynchronization implements Synchronization { /** * The timer being managed in the transaction */ private final TimerImpl timer; public TimerCreationTransactionSynchronization(TimerImpl timer) { if (timer == null) { throw EJB3_TIMER_LOGGER.timerIsNull(); } this.timer = timer; } @Override public void beforeCompletion() { } /** * {@inheritDoc} */ @Override public void afterCompletion(int status) { if (status == Status.STATUS_COMMITTED) { EJB3_TIMER_LOGGER.debugv("commit timer creation: {0}", this.timer); if (!registerTimerResource(timer)) { return; } TimerState timerState = this.timer.getState(); switch (timerState) { case CREATED: this.timer.setTimerState(TimerState.ACTIVE, null); this.timer.scheduleTimeout(true); break; case ACTIVE: this.timer.scheduleTimeout(true); break; } } else if (status == Status.STATUS_ROLLEDBACK) { EJB3_TIMER_LOGGER.debugv("Rolling back timer creation: {0}", this.timer); this.timer.setTimerState(TimerState.CANCELED, null); } } } private class TimerRemoveSynchronization implements Synchronization { private final TimerImpl timer; private TimerRemoveSynchronization(final TimerImpl timer) { this.timer = timer; } @Override public void beforeCompletion() { } @Override public void afterCompletion(final int status) { try { if (status == Status.STATUS_COMMITTED) { cancelTimeout(timer); unregisterTimerResource(timer.getId()); } else { timer.setTimerState(TimerState.ACTIVE, null); } } finally { timer.unlock(); } } } private class TaskPostPersist extends java.util.TimerTask { private final TimerImpl timer; private long delta = 0; private long nextExpirationPristine = 0; TaskPostPersist(TimerImpl timer) { this.timer = timer; if (timer.nextExpiration != null) { this.nextExpirationPristine = timer.nextExpiration.getTime(); } } TaskPostPersist(TimerImpl timer, long delta, long nextExpirationPristine) { this.timer = timer; this.delta = delta; this.nextExpirationPristine = nextExpirationPristine; } @Override public void run() { executor.submit(this::persistTimer); } void persistTimer() { final ContextTransactionManager transactionManager = ContextTransactionManager.getInstance(); try { transactionManager.begin(); persistence.persistTimer(timer); transactionManager.commit(); } catch (Exception e) { try { transactionManager.rollback(); } catch (Exception ee) { // omit; } EJB3_TIMER_LOGGER.exceptionPersistTimerState(timer, e); long nextExpirationDelay; if (nextExpirationPristine > 0 && timer.timerState != TimerState.RETRY_TIMEOUT && (nextExpirationDelay = nextExpirationPristine - System.currentTimeMillis()) > delta) { if (delta == 0L) { delta = nextExpirationDelay / (1L + MAX_RETRY.longValue()); } TimerServiceImpl.this.timer.schedule(new TaskPostPersist(timer, delta, nextExpirationPristine), delta); } else { EJB3_TIMER_LOGGER.exceptionPersistPostTimerState(timer, e); } } } } private class Task extends java.util.TimerTask { private final TimerTask delegate; private final ControlPoint controlPoint; /** * This is true if a task is queued up to be run by the request controller, * used to stop timer tasks banking up when the container is suspended. */ private volatile boolean queued = false; public Task(final TimerTask delegate, ControlPoint controlPoint) { this.delegate = delegate; this.controlPoint = controlPoint; } @Override public void run() { if (executor != null) { if (controlPoint == null) { executor.submit(delegate); } else if (!queued) { queued = true; controlPoint.queueTask(new Runnable() { @Override public void run() { queued = false; delegate.run(); } }, executor, -1, null, false); } else { EjbLogger.EJB3_TIMER_LOGGER.debug("Skipping timer invocation as existing request is already queued."); } } } @Override public boolean cancel() { delegate.cancel(); return super.cancel(); } } private final class TimerRefreshListener implements TimerPersistence.TimerChangeListener { @Override public void timerAdded(TimerImpl timer) { TimerServiceImpl.this.startTimer(timer); } @Override public void timerRemoved(String timerId) { TimerImpl timer = TimerServiceImpl.this.getTimer(timerId); if (timer != null) { TimerServiceImpl.this.cancelTimeout(timer); TimerServiceImpl.this.unregisterTimerResource(timer.getId()); } } @Override public TimerServiceImpl getTimerService() { return TimerServiceImpl.this; } @Override public void timerSync(TimerImpl oldTimer, TimerImpl newTimer) { TimerServiceImpl.this.removeTimer(oldTimer); TimerServiceImpl.this.startTimer(newTimer); } } }
42,392
39.297529
170
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/spi/TimedObjectInvoker.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.spi; import java.lang.reflect.Method; import jakarta.ejb.Timer; import org.jboss.as.ejb3.component.EJBComponent; /** * An implementation can invoke the ejbTimeout method on a TimedObject. * <p/> * The TimedObjectInvoker has knowledge of the TimedObjectId, it * knows which object to invoke. * * @author [email protected] * @author <a href="mailto:[email protected]">Carlo de Wolf</a> */ public interface TimedObjectInvoker { /** * Return the EJB component associated with this invoker * @return an EJB component */ EJBComponent getComponent(); /** * The globally unique identifier for this timed object invoker. * * @return the identifier */ String getTimedObjectId(); /** * Invokes the ejbTimeout method on the TimedObject with the given id. * * @param timer the Timer that is passed to ejbTimeout */ default void callTimeout(Timer timer) throws Exception { this.callTimeout(timer, this.getComponent().getTimeoutMethod()); } /** * Responsible for invoking the timeout method on the target object. * <p/> * <p> * The timerservice implementation invokes this method as a callback when a timeout occurs for the passed * <code>timer</code>. The timerservice implementation will be responsible for passing the correct * timeout method corresponding to the <code>timer</code> on which the timeout has occurred. * </p> * * @param timer the Timer that is passed to ejbTimeout * @param timeoutMethod The timeout method */ void callTimeout(Timer timer, Method timeoutMethod) throws Exception; /** * @return The class loader that should be used to load restore any timers for this object */ ClassLoader getClassLoader(); }
2,889
34.243902
109
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/spi/ManagedTimerServiceFactoryConfiguration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.spi; /** * Enscapsulate the common configuration for a {@ManagedTimerServiceFactory}. * @author Paul Ferraro */ public interface ManagedTimerServiceFactoryConfiguration extends TimerServiceApplicableComponentConfiguration { /** * An invoker factory for the EJB component associated with this timer service * @return an invoker factory */ TimedObjectInvokerFactory getInvokerFactory(); }
1,478
38.972973
111
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/spi/ManagedTimerServiceConfiguration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.spi; import java.util.function.Predicate; import java.util.function.UnaryOperator; import jakarta.ejb.TimerConfig; import org.jboss.msc.service.ServiceName; /** * Encapsulates the common configuration of a managed timer service. * @author Paul Ferraro */ public interface ManagedTimerServiceConfiguration extends TimerServiceApplicableComponentConfiguration { enum TimerFilter implements Predicate<TimerConfig>, UnaryOperator<ServiceName> { ALL() { @Override public boolean test(TimerConfig config) { return true; } @Override public ServiceName apply(ServiceName name) { return name; } }, TRANSIENT() { @Override public boolean test(TimerConfig config) { return !config.isPersistent(); } @Override public ServiceName apply(ServiceName name) { return name.append("transient"); } }, PERSISTENT() { @Override public boolean test(TimerConfig config) { return config.isPersistent(); } @Override public ServiceName apply(ServiceName name) { return name.append("persistent"); } }, ; @Override public ServiceName apply(ServiceName name) { return name.append(this.name()); } } /** * An invoker for the EJB component associated with this timer service * @return an invoker */ TimedObjectInvoker getInvoker(); /** * Returns a filter to determine whether or not to create a given timer. * @return a filter that returns true, if the given timer should be created, false otherwise. */ Predicate<TimerConfig> getTimerFilter(); }
2,949
31.065217
104
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/spi/ManagedTimerServiceFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.spi; import org.jboss.as.ejb3.component.EJBComponent; /** * @author Paul Ferraro */ public interface ManagedTimerServiceFactory { /** * Creates a managed timer service for the specified component. * @param component an EJB component * @return a managed timer service. */ ManagedTimerService createTimerService(EJBComponent component); }
1,433
35.769231
70
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/spi/TimerServiceApplicableComponentConfiguration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.spi; /** * Configuration for a TimerService-aware deployment. * @author Paul Ferraro */ public interface TimerServiceApplicableComponentConfiguration { /** * A registry of timer services associated with the same deployment. * @return a timer service registry */ TimerServiceRegistry getTimerServiceRegistry(); /** * A registrar for timers created by this timer service * @return a timer registrar */ TimerListener getTimerListener(); }
1,551
35.093023
72
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/spi/TimerListener.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.spi; /** * Registrar for timers. * @author Paul Ferraro */ public interface TimerListener { /** * Registers a timer with the specified identifier. * @param id an timer identifier. */ void timerAdded(String id); /** * Unregisters a timer with the specified identifier. * @param id an timer identifier. */ void timerRemoved(String id); }
1,451
32.767442
70
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/spi/ManagedTimer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.spi; import jakarta.ejb.Timer; import org.jboss.as.ejb3.component.allowedmethods.AllowedMethodsInformation; import org.jboss.as.ejb3.component.allowedmethods.MethodType; import org.jboss.as.ejb3.logging.EjbLogger; /** * Interface for managed {@link jakarta.ejb.Timer} implementations. * @author Paul Ferraro */ public interface ManagedTimer extends Timer { /** * The unique identifier of this timer. * @return a unique identifier */ String getId(); /** * Indicates whether this timer is active, i.e. not suspended. * @return true, if this timer is active, false otherwise. */ boolean isActive(); /** * Indicates whether this timer was canceled, i.e. via {@link Timer#cancel()}. * @return true, if this timer was canceled, false otherwise. */ boolean isCanceled(); /** * Indicates whether this timer has expired, i.e. it has no more timeouts. * An interval timer will always return false. * @return true, if this timer has expired, false otherwise. */ boolean isExpired(); /** * Activates a previously suspended timer. Once active, the timer will receive timeout events as usual, including any timeouts missed while inactive. */ void activate(); /** * Suspends a previously active timer. While suspended, the timer will not receive timeout events. */ void suspend(); /** * Invokes the timeout method associated with this timer. Has no impact on this timer's schedule. * @throws Exception */ void invoke() throws Exception; /** * Validates the invocation context of a given specification method. */ default void validateInvocationContext() { if (this.isCanceled()) { throw EjbLogger.EJB3_TIMER_LOGGER.timerWasCanceled(this.getId()); } if (this.isExpired()) { throw EjbLogger.EJB3_TIMER_LOGGER.timerHasExpired(this.getId()); } AllowedMethodsInformation.checkAllowed(MethodType.TIMER_SERVICE_METHOD); } }
3,122
33.318681
154
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/spi/AutoTimer.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.spi; import java.lang.reflect.Method; import jakarta.ejb.ScheduleExpression; import jakarta.ejb.TimerConfig; /** * Holds data about an automatic timer * @author Stuart Douglas */ public final class AutoTimer { private final ScheduleExpression scheduleExpression; private final TimerConfig timerConfig; private Method method; public AutoTimer() { scheduleExpression = new ScheduleExpression(); timerConfig = new TimerConfig(); } public AutoTimer(final ScheduleExpression scheduleExpression, final TimerConfig timerConfig, final Method method) { this.scheduleExpression = scheduleExpression; this.timerConfig = timerConfig; this.method = method; } public ScheduleExpression getScheduleExpression() { return scheduleExpression; } public TimerConfig getTimerConfig() { return timerConfig; } public Method getMethod() { return method; } }
2,015
32.6
119
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/spi/TimedObjectInvokerFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.spi; import org.jboss.as.ejb3.component.EJBComponent; /** * Factory for creating a {@link TimedObjectInvoker} for an EJB component. * @author Paul Ferraro */ public interface TimedObjectInvokerFactory { /** * Creates an invoker for the specified EJB component * @param component an EJB component * @return an invoker */ TimedObjectInvoker createInvoker(EJBComponent component); }
1,477
35.95
74
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/spi/ManagedTimerService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.spi; import static org.jboss.as.ejb3.logging.EjbLogger.EJB3_TIMER_LOGGER; import java.io.Serializable; import java.util.Date; import jakarta.ejb.EJBException; import jakarta.ejb.ScheduleExpression; import jakarta.ejb.Timer; import jakarta.ejb.TimerConfig; import jakarta.ejb.TimerService; import jakarta.transaction.Status; import jakarta.transaction.SystemException; import jakarta.transaction.Transaction; import org.jboss.as.ejb3.component.allowedmethods.AllowedMethodsInformation; import org.jboss.as.ejb3.component.allowedmethods.MethodType; import org.jboss.as.ejb3.component.stateful.CurrentSynchronizationCallback; import org.jboss.as.ejb3.context.CurrentInvocationContext; import org.jboss.invocation.InterceptorContext; import org.wildfly.clustering.ee.Restartable; import org.wildfly.transaction.client.ContextTransactionManager; /** * Interface for managed {@link jakarta.ejb.TimerService} implementations. * @author Paul Ferraro */ public interface ManagedTimerService extends TimerService, Restartable { /** * Returns the managed timer associated with the specified identifier * @param id a timer identifier * @return a managed timer */ ManagedTimer findTimer(String id); /** * Returns the invoker for the timed object associated with this timer service. * @return a timed object invoker */ TimedObjectInvoker getInvoker(); @Override default Timer createCalendarTimer(ScheduleExpression schedule) { return this.createCalendarTimer(schedule, new TimerConfig()); } @Override default Timer createIntervalTimer(long initialDuration, long intervalDuration, TimerConfig config) { if (initialDuration < 0) { throw EJB3_TIMER_LOGGER.invalidTimerParameter("initialDuration", Long.toString(initialDuration)); } return this.createIntervalTimer(new Date(System.currentTimeMillis() + initialDuration), intervalDuration, config); } @Override default Timer createSingleActionTimer(long duration, TimerConfig config) { if (duration < 0) { throw EJB3_TIMER_LOGGER.invalidTimerParameter("duration", Long.toString(duration)); } return this.createSingleActionTimer(new Date(System.currentTimeMillis() + duration), config); } @Override default Timer createTimer(long duration, Serializable info) throws EJBException { if (duration < 0) { throw EJB3_TIMER_LOGGER.invalidTimerParameter("duration", Long.toString(duration)); } return this.createTimer(new Date(System.currentTimeMillis() + duration), info); } @Override default Timer createTimer(long initialDuration, long intervalDuration, Serializable info) { if (initialDuration < 0) { throw EJB3_TIMER_LOGGER.invalidTimerParameter("initialDuration", Long.toString(initialDuration)); } return this.createTimer(new Date(System.currentTimeMillis() + initialDuration), intervalDuration, info); } @Override default Timer createTimer(Date expiration, Serializable info) { return this.createSingleActionTimer(expiration, new TimerConfig(info, true)); } @Override default Timer createTimer(Date initialExpiration, long intervalDuration, Serializable info) { return this.createIntervalTimer(initialExpiration, intervalDuration, new TimerConfig(info, true)); } /** * Validates the invocation context of a given specification method. */ default void validateInvocationContext() { AllowedMethodsInformation.checkAllowed(MethodType.TIMER_SERVICE_METHOD); if (!this.getInvoker().getComponent().getComponentDescription().isSingleton() && isLifecycleCallbackInvocation()) { throw EJB3_TIMER_LOGGER.failToInvokeTimerServiceDoLifecycle(); } } /** * @return true if the transaction is in a state where synchronizations can be registered */ static Transaction getActiveTransaction() { Transaction tx = ContextTransactionManager.getInstance().getTransaction(); if (tx == null) return null; try { int status = tx.getStatus(); switch (status) { case Status.STATUS_COMMITTED: case Status.STATUS_MARKED_ROLLBACK: case Status.STATUS_NO_TRANSACTION: case Status.STATUS_ROLLEDBACK: case Status.STATUS_ROLLING_BACK: case Status.STATUS_UNKNOWN: return null; default: return CurrentSynchronizationCallback.get() != CurrentSynchronizationCallback.CallbackType.BEFORE_COMPLETION ? tx : null; } } catch (SystemException e) { throw new EJBException(e); } } /** * Returns true if the {@link CurrentInvocationContext} represents a lifecycle * callback invocation. Else returns false. * <p> * This method internally relies on {@link CurrentInvocationContext#get()} to obtain * the current invocation context. * <ul> * <li>If the context is available then it looks for the method that was invoked. * The absence of a method indicates a lifecycle callback.</li> * <li>If the context is <i>not</i> available, then this method returns false (i.e. * it doesn't consider the current invocation as a lifecycle callback). This is * for convenience, to allow the invocation of {@link jakarta.ejb.TimerService} methods * in the absence of {@link CurrentInvocationContext}</li> * </ul> * <p/> * </p> * * @return */ static boolean isLifecycleCallbackInvocation() { InterceptorContext currentInvocationContext = CurrentInvocationContext.get(); // If the method in current invocation context is null, // then it represents a lifecycle callback invocation return (currentInvocationContext != null) && currentInvocationContext.getMethod() == null; } }
7,082
39.706897
141
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/spi/TimerServiceRegistry.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.spi; import java.util.Collection; import jakarta.ejb.Timer; import jakarta.ejb.TimerService; /** * Registry of timer services for a given deployment, used to implement {@link TimerService#getAllTimers()}. * @author Paul Ferraro */ public interface TimerServiceRegistry { /** * Registers the specified timer service. * @param service a timer service */ void registerTimerService(TimerService service); /** * Unregisters the specified timer service. * @param service a timer service */ void unregisterTimerService(TimerService service); /** * Returns the timers for all registered timer services. * @return a collection of timers */ Collection<Timer> getAllTimers(); }
1,808
32.5
108
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/composite/CompositeTimerServiceFactoryServiceConfigurator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.composite; import java.util.function.Consumer; import java.util.function.Predicate; import jakarta.ejb.TimerConfig; import org.jboss.as.ejb3.component.EJBComponent; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerService; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerServiceConfiguration.TimerFilter; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerServiceFactory; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerServiceFactoryConfiguration; import org.jboss.as.ejb3.timerservice.spi.TimedObjectInvoker; import org.jboss.as.ejb3.timerservice.spi.TimedObjectInvokerFactory; import org.jboss.as.ejb3.timerservice.spi.TimerListener; import org.jboss.as.ejb3.timerservice.spi.TimerServiceRegistry; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.wildfly.clustering.service.CompositeDependency; import org.wildfly.clustering.service.ServiceConfigurator; import org.wildfly.clustering.service.ServiceSupplierDependency; import org.wildfly.clustering.service.SimpleServiceNameProvider; import org.wildfly.clustering.service.SupplierDependency; /** * Configures a services that provides a composite timer service factory. * @author Paul Ferraro */ public class CompositeTimerServiceFactoryServiceConfigurator extends SimpleServiceNameProvider implements ServiceConfigurator, ManagedTimerServiceFactory { private final TimedObjectInvokerFactory invokerFactory; private final TimerServiceRegistry registry; private final SupplierDependency<ManagedTimerServiceFactory> transientFactory; private final SupplierDependency<ManagedTimerServiceFactory> persistentFactory; public CompositeTimerServiceFactoryServiceConfigurator(ServiceName name, ManagedTimerServiceFactoryConfiguration configuration) { super(name); this.invokerFactory = configuration.getInvokerFactory(); this.registry = configuration.getTimerServiceRegistry(); this.transientFactory = new ServiceSupplierDependency<>(TimerFilter.TRANSIENT.apply(name)); this.persistentFactory = new ServiceSupplierDependency<>(TimerFilter.PERSISTENT.apply(name)); } @Override public ServiceBuilder<?> build(ServiceTarget target) { ServiceName name = this.getServiceName(); ServiceBuilder<?> builder = target.addService(name); Consumer<ManagedTimerServiceFactory> factory = new CompositeDependency(this.transientFactory, this.persistentFactory).register(builder).provides(name); return builder.setInstance(Service.newInstance(factory, this)).setInitialMode(ServiceController.Mode.ON_DEMAND); } @Override public ManagedTimerService createTimerService(EJBComponent component) { TimedObjectInvoker invoker = this.invokerFactory.createInvoker(component); ManagedTimerService transientTimerService = this.transientFactory.get().createTimerService(component); ManagedTimerService persistentTimerService = this.persistentFactory.get().createTimerService(component); TimerServiceRegistry registry = this.registry; return new CompositeTimerService(new CompositeTimerServiceConfiguration() { @Override public TimedObjectInvoker getInvoker() { return invoker; } @Override public TimerServiceRegistry getTimerServiceRegistry() { return registry; } @Override public TimerListener getTimerListener() { return null; } @Override public ManagedTimerService getTransientTimerService() { return transientTimerService; } @Override public ManagedTimerService getPersistentTimerService() { return persistentTimerService; } @Override public Predicate<TimerConfig> getTimerFilter() { return TimerFilter.ALL; } }); } }
5,186
43.715517
159
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/composite/CompositeTimerServiceConfiguration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.composite; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerService; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerServiceConfiguration; /** * @author Paul Ferraro */ public interface CompositeTimerServiceConfiguration extends ManagedTimerServiceConfiguration { ManagedTimerService getTransientTimerService(); ManagedTimerService getPersistentTimerService(); }
1,450
39.305556
94
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/composite/CompositeTimerService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.composite; import static org.jboss.as.ejb3.logging.EjbLogger.EJB3_TIMER_LOGGER; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import jakarta.ejb.ScheduleExpression; import jakarta.ejb.TimerConfig; import org.jboss.as.ejb3.timerservice.spi.ManagedTimer; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerService; import org.jboss.as.ejb3.timerservice.spi.TimedObjectInvoker; import org.jboss.as.ejb3.timerservice.spi.TimerServiceRegistry; /** * A composite timer service that manages persistent vs transient timers separately. * @author Paul Ferraro */ public class CompositeTimerService implements ManagedTimerService { private final TimedObjectInvoker invoker; private final TimerServiceRegistry registry; private final ManagedTimerService transientTimerService; private final ManagedTimerService persistentTimerService; public CompositeTimerService(CompositeTimerServiceConfiguration configuration) { this.invoker = configuration.getInvoker(); this.registry = configuration.getTimerServiceRegistry(); this.transientTimerService = configuration.getTransientTimerService(); this.persistentTimerService = configuration.getPersistentTimerService(); } @Override public TimedObjectInvoker getInvoker() { return this.invoker; } @Override public void start() { this.transientTimerService.start(); this.persistentTimerService.start(); } @Override public void stop() { this.persistentTimerService.stop(); this.transientTimerService.stop(); } private ManagedTimerService getTimerService(TimerConfig config) { return config.isPersistent() ? this.persistentTimerService : this.transientTimerService; } @Override public jakarta.ejb.Timer createCalendarTimer(ScheduleExpression schedule, TimerConfig config) { this.validateInvocationContext(); if (schedule == null) { throw EJB3_TIMER_LOGGER.invalidTimerParameter("schedule", null); } TimerConfig timerConfig = (config != null) ? config : new TimerConfig(); return this.getTimerService(timerConfig).createCalendarTimer(schedule, timerConfig); } @Override public jakarta.ejb.Timer createIntervalTimer(Date initialExpiration, long intervalDuration, TimerConfig config) { this.validateInvocationContext(); if (initialExpiration == null) { throw EJB3_TIMER_LOGGER.invalidTimerParameter("initialExpiration", null); } if (initialExpiration.getTime() < 0) { throw EJB3_TIMER_LOGGER.invalidTimerParameter("initialExpiration.getTime()", Long.toString(initialExpiration.getTime())); } if (intervalDuration < 0) { throw EJB3_TIMER_LOGGER.invalidTimerParameter("intervalDuration", Long.toString(intervalDuration)); } TimerConfig timerConfig = (config != null) ? config : new TimerConfig(); return this.getTimerService(timerConfig).createIntervalTimer(initialExpiration, intervalDuration, timerConfig); } @Override public jakarta.ejb.Timer createSingleActionTimer(Date expiration, TimerConfig config) { this.validateInvocationContext(); if (expiration == null) { throw EJB3_TIMER_LOGGER.invalidTimerParameter("expiration", null); } if (expiration.getTime() < 0) { throw EJB3_TIMER_LOGGER.invalidTimerParameter("expiration.getTime()", Long.toString(expiration.getTime())); } TimerConfig timerConfig = (config != null) ? config : new TimerConfig(); return this.getTimerService(timerConfig).createSingleActionTimer(expiration, timerConfig); } @Override public Collection<jakarta.ejb.Timer> getTimers() { Collection<jakarta.ejb.Timer> transientTimers = this.transientTimerService.getTimers(); Collection<jakarta.ejb.Timer> persistentTimers = this.persistentTimerService.getTimers(); Collection<jakarta.ejb.Timer> result = new ArrayList<>(transientTimers.size() + persistentTimers.size()); result.addAll(transientTimers); result.addAll(persistentTimers); return Collections.unmodifiableCollection(result); } @Override public Collection<jakarta.ejb.Timer> getAllTimers() { return this.registry.getAllTimers(); } @Override public ManagedTimer findTimer(String id) { ManagedTimer timer = this.transientTimerService.findTimer(id); if (timer == null) { timer = this.persistentTimerService.findTimer(id); } return timer; } @Override public String toString() { return String.format("%s(%s)", this.getClass().getSimpleName(), this.invoker.getTimedObjectId()); } }
5,907
39.190476
133
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/schedule/CalendarBasedTimeout.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.schedule; import static org.jboss.as.ejb3.logging.EjbLogger.EJB3_TIMER_LOGGER; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Objects; import java.util.TimeZone; import jakarta.ejb.ScheduleExpression; import org.jboss.as.ejb3.timerservice.schedule.attribute.DayOfMonth; import org.jboss.as.ejb3.timerservice.schedule.attribute.DayOfWeek; import org.jboss.as.ejb3.timerservice.schedule.attribute.Hour; import org.jboss.as.ejb3.timerservice.schedule.attribute.Minute; import org.jboss.as.ejb3.timerservice.schedule.attribute.Month; import org.jboss.as.ejb3.timerservice.schedule.attribute.Second; import org.jboss.as.ejb3.timerservice.schedule.attribute.Year; import org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType; /** * CalendarBasedTimeout * * @author Jaikiran Pai * @author "<a href=\"mailto:[email protected]\">Wolf-Dieter Fink</a>" * @author Eduardo Martins * @version $Revision: $ */ public class CalendarBasedTimeout { private static final TimeZone DEFAULT_TIMEZONE = TimeZone.getDefault(); /** * The {@link jakarta.ejb.ScheduleExpression} from which this {@link CalendarBasedTimeout} * was created */ private ScheduleExpression scheduleExpression; /** * The {@link Second} created out of the {@link jakarta.ejb.ScheduleExpression#getSecond()} value */ private final Second second; /** * The {@link org.jboss.as.ejb3.timerservice.schedule.attribute.Minute} created out of the {@link jakarta.ejb.ScheduleExpression#getMinute()} value */ private final Minute minute; /** * The {@link org.jboss.as.ejb3.timerservice.schedule.attribute.Hour} created out of the {@link jakarta.ejb.ScheduleExpression#getHour()} value */ private final Hour hour; /** * The {@link DayOfWeek} created out of the {@link jakarta.ejb.ScheduleExpression#getDayOfWeek()} value */ private final DayOfWeek dayOfWeek; /** * The {@link org.jboss.as.ejb3.timerservice.schedule.attribute.DayOfMonth} created out of the {@link jakarta.ejb.ScheduleExpression#getDayOfMonth()} value */ private final DayOfMonth dayOfMonth; /** * The {@link Month} created out of the {@link jakarta.ejb.ScheduleExpression#getMonth()} value */ private final Month month; /** * The {@link org.jboss.as.ejb3.timerservice.schedule.attribute.Year} created out of the {@link jakarta.ejb.ScheduleExpression#getYear()} value */ private final Year year; /** * The first timeout relative to the time when this {@link CalendarBasedTimeout} was created * from a {@link jakarta.ejb.ScheduleExpression} */ private final Calendar firstTimeout; /** * The timezone being used for this {@link CalendarBasedTimeout} */ private final TimeZone timezone; private final Date start; private final Date end; /** * Creates a {@link CalendarBasedTimeout} from the passed <code>schedule</code>. * <p> * This constructor parses the passed {@link jakarta.ejb.ScheduleExpression} and sets up * its internal representation of the same. * </p> * * @param schedule The schedule */ public CalendarBasedTimeout(ScheduleExpression schedule) { this(new Second(schedule.getSecond()), new Minute(schedule.getMinute()), new Hour(schedule.getHour()), new DayOfMonth(schedule.getDayOfMonth()), new Month(schedule.getMonth()), new DayOfWeek(schedule.getDayOfWeek()), new Year(schedule.getYear()), getTimeZone(schedule.getTimezone()), schedule.getStart(), schedule.getEnd()); // store the original expression from which this // CalendarBasedTimeout was created. Since the ScheduleExpression // is mutable, we will have to store a clone copy of the schedule, // so that any subsequent changes after the CalendarBasedTimeout construction, // do not affect this internal schedule expression. // The caller of this constructor already passes a new instance of ScheduleExpression // exclusively for this purpose, so no need to clone here. this.scheduleExpression = schedule; } public CalendarBasedTimeout(Second second, Minute minute, Hour hour, DayOfMonth dayOfMonth, Month month, DayOfWeek dayOfWeek, Year year, TimeZone timezone, Date start, Date end) { this.second = second; this.minute = minute; this.hour = hour; this.dayOfMonth = dayOfMonth; this.month = month; this.dayOfWeek = dayOfWeek; this.year = year; this.timezone = timezone; this.start = start; this.end = end; // Now that we have parsed the values from the ScheduleExpression, // determine and set the first timeout (relative to the current time) // of this CalendarBasedTimeout this.firstTimeout = this.calculateFirstTimeout(); } private static TimeZone getTimeZone(String id) { if (id != null) { TimeZone zone = TimeZone.getTimeZone(id); // If the timezone ID wasn't valid, then Timezone.getTimeZone returns // GMT, which may not always be desirable. if (zone.getID().equals("GMT") && !id.equalsIgnoreCase("GMT")) { EJB3_TIMER_LOGGER.unknownTimezoneId(id, DEFAULT_TIMEZONE.getID()); } else { return zone; } } // use server's timezone return DEFAULT_TIMEZONE; } public static boolean doesScheduleMatch(final ScheduleExpression expression1, final ScheduleExpression expression2) { return Objects.equals(expression1.getHour(), expression2.getHour()) && Objects.equals(expression1.getMinute(), expression2.getMinute()) && Objects.equals(expression1.getMonth(), expression2.getMonth()) && Objects.equals(expression1.getSecond(), expression2.getSecond()) && Objects.equals(expression1.getDayOfMonth(), expression2.getDayOfMonth()) && Objects.equals(expression1.getDayOfWeek(), expression2.getDayOfWeek()) && Objects.equals(expression1.getYear(), expression2.getYear()) && Objects.equals(expression1.getTimezone(), expression2.getTimezone()) && Objects.equals(expression1.getEnd(), expression2.getEnd()) && Objects.equals(expression1.getStart(), expression2.getStart()); } public Calendar getNextTimeout() { return getNextTimeout(new GregorianCalendar(this.timezone), true); } /** * @return */ public Calendar getFirstTimeout() { return this.firstTimeout; } private Calendar calculateFirstTimeout() { Calendar currentCal = new GregorianCalendar(this.timezone); if (this.start != null) { currentCal.setTime(this.start); } else { resetTimeToFirstValues(currentCal); } return getNextTimeout(currentCal, false); } /** * Returns the original {@link jakarta.ejb.ScheduleExpression} from which this {@link CalendarBasedTimeout} * was created. * * @return */ public ScheduleExpression getScheduleExpression() { return this.scheduleExpression; } public Calendar getNextTimeout(Calendar currentCal) { return getNextTimeout(currentCal, true); } private Calendar getNextTimeout(Calendar currentCal, boolean increment) { if (this.noMoreTimeouts(currentCal)) { return null; } Calendar nextCal = (Calendar) currentCal.clone(); nextCal.setTimeZone(this.timezone); if (this.start != null && currentCal.getTime().before(this.start)) { //this may result in a millisecond component, however that is ok //otherwise WFLY-6561 will rear its only head //also as the start time may include milliseconds this is technically correct nextCal.setTime(this.start); } else { if (increment) { // increment the current second by 1 nextCal.add(Calendar.SECOND, 1); } nextCal.add(Calendar.MILLISECOND, -nextCal.get(Calendar.MILLISECOND)); } nextCal.setFirstDayOfWeek(Calendar.SUNDAY); nextCal = this.computeNextTime(nextCal); if (nextCal == null) { return null; } nextCal = this.computeNextMonth(nextCal); if (nextCal == null) { return null; } nextCal = this.computeNextDate(nextCal); if (nextCal == null) { return null; } nextCal = this.computeNextYear(nextCal); if (nextCal == null) { return null; } // one final check if (this.noMoreTimeouts(nextCal)) { return null; } return nextCal; } private Calendar computeNextTime(Calendar nextCal) { int currentSecond = nextCal.get(Calendar.SECOND); int currentMinute = nextCal.get(Calendar.MINUTE); int currentHour = nextCal.get(Calendar.HOUR_OF_DAY); final int currentTimeInSeconds = currentHour*3600 + currentMinute*60 + currentSecond; // compute next second Integer nextSecond = this.second.getNextMatch(currentSecond); if (nextSecond == null) { return null; } // compute next minute if (nextSecond < currentSecond) { currentMinute++; } Integer nextMinute = this.minute.getNextMatch(currentMinute < 60 ? currentMinute : 0); if (nextMinute == null) { return null; } // reset second if minute was changed (Fix WFLY-5955) if( nextMinute != currentMinute) { nextSecond = this.second.getNextMatch(0); } // compute next hour if (nextMinute < currentMinute) { currentHour++; } Integer nextHour = this.hour.getNextMatch(currentHour < 24 ? currentHour : 0); if (nextHour == null) { return null; } if(nextHour != currentHour) { // reset second/minute if hour changed (Fix WFLY-5955) nextSecond = this.second.getNextMatch(0); nextMinute = this.minute.getNextMatch(0); } final int nextTimeInSeconds = nextHour*3600 + nextMinute*60 + nextSecond; if (nextTimeInSeconds == currentTimeInSeconds) { // no change in time return nextCal; } // Set the time before adding the a day. If we do it after, // we could be using an invalid DST value in setTime method setTime(nextCal, nextHour, nextMinute, nextSecond); // time change if (nextTimeInSeconds < currentTimeInSeconds) { // advance to next day nextCal.add(Calendar.DATE, 1); } return nextCal; } private Calendar computeNextDayOfWeek(Calendar nextCal) { Integer nextDayOfWeek = this.dayOfWeek.getNextMatch(nextCal); if (nextDayOfWeek == null) { return null; } int currentDayOfWeek = nextCal.get(Calendar.DAY_OF_WEEK); // if the current day-of-week is a match, then nothing else to // do. Just return back the calendar if (currentDayOfWeek == nextDayOfWeek) { return nextCal; } int currentMonth = nextCal.get(Calendar.MONTH); // At this point, a suitable "next" day-of-week has been identified. // There can be 2 cases // 1) The "next" day-of-week is greater than the current day-of-week : This // implies that the next day-of-week is within the "current" week. // 2) The "next" day-of-week is lesser than the current day-of-week : This implies // that the next day-of-week is in the next week (i.e. current week needs to // be advanced to next week). if (nextDayOfWeek < currentDayOfWeek) { // advance one week nextCal.add(Calendar.WEEK_OF_MONTH, 1); } // set the chosen day of week nextCal.set(Calendar.DAY_OF_WEEK, nextDayOfWeek); // since we are moving to a different day-of-week (as compared to the current day-of-week), // we should reset the second, minute and hour appropriately, to their first possible // values resetTimeToFirstValues(nextCal); if (nextCal.get(Calendar.MONTH) != currentMonth) { nextCal = computeNextMonth(nextCal); } return nextCal; } private Calendar computeNextMonth(Calendar nextCal) { Integer nextMonth = this.month.getNextMatch(nextCal); if (nextMonth == null) { return null; } int currentMonth = nextCal.get(Calendar.MONTH); // if the current month is a match, then nothing else to // do. Just return back the calendar if (currentMonth == nextMonth) { return nextCal; } // At this point, a suitable "next" month has been identified. // There can be 2 cases // 1) The "next" month is greater than the current month : This // implies that the next month is within the "current" year. // 2) The "next" month is lesser than the current month : This implies // that the next month is in the next year (i.e. current year needs to // be advanced to next year). if (nextMonth < currentMonth) { // advance to next year nextCal.add(Calendar.YEAR, 1); } // set the chosen month nextCal.set(Calendar.MONTH, nextMonth); // since we are moving to a different month (as compared to the current month), // we should reset the second, minute, hour, day-of-week and dayofmonth appropriately, to their first possible // values nextCal.set(Calendar.DAY_OF_WEEK, this.dayOfWeek.getFirst()); nextCal.set(Calendar.DAY_OF_MONTH, 1); resetTimeToFirstValues(nextCal); return nextCal; } private Calendar computeNextDate(Calendar nextCal) { if (this.isDayOfMonthWildcard()) { return this.computeNextDayOfWeek(nextCal); } if (this.isDayOfWeekWildcard()) { return this.computeNextDayOfMonth(nextCal); } // both day-of-month and day-of-week are *non-wildcards* Calendar nextDayOfMonthCal = this.computeNextDayOfMonth((Calendar) nextCal.clone()); Calendar nextDayOfWeekCal = this.computeNextDayOfWeek((Calendar) nextCal.clone()); if (nextDayOfMonthCal == null) { return nextDayOfWeekCal; } if (nextDayOfWeekCal == null) { return nextDayOfMonthCal; } return nextDayOfWeekCal.getTime().before(nextDayOfMonthCal.getTime()) ? nextDayOfWeekCal : nextDayOfMonthCal; } private Calendar computeNextDayOfMonth(Calendar nextCal) { Integer nextDayOfMonth = this.dayOfMonth.getNextMatch(nextCal); if (nextDayOfMonth == null) { return null; } int currentDayOfMonth = nextCal.get(Calendar.DAY_OF_MONTH); // if the current day-of-month is a match, then nothing else to // do. Just return back the calendar if (currentDayOfMonth == nextDayOfMonth) { return nextCal; } if (nextDayOfMonth > currentDayOfMonth) { if (this.monthHasDate(nextCal, nextDayOfMonth)) { // set the chosen day-of-month nextCal.set(Calendar.DAY_OF_MONTH, nextDayOfMonth); // since we are moving to a different day-of-month (as compared to the current day-of-month), // we should reset the second, minute and hour appropriately, to their first possible // values resetTimeToFirstValues(nextCal); } else { nextCal = this.advanceTillMonthHasDate(nextCal, nextDayOfMonth); } } else { // since the next day is before the current day we need to shift to the next month nextCal.add(Calendar.MONTH, 1); // also we need to reset the time resetTimeToFirstValues(nextCal); nextCal = this.computeNextMonth(nextCal); if (nextCal == null) { return null; } nextDayOfMonth = this.dayOfMonth.getFirstMatch(nextCal); if (nextDayOfMonth == null) { return null; } // make sure the month can handle the date nextCal = this.advanceTillMonthHasDate(nextCal, nextDayOfMonth); } return nextCal; } private Calendar computeNextYear(Calendar nextCal) { Integer nextYear = this.year.getNextMatch(nextCal); if (nextYear == null || nextYear > Year.MAX_YEAR) { return null; } int currentYear = nextCal.get(Calendar.YEAR); // if the current year is a match, then nothing else to // do. Just return back the calendar if (currentYear == nextYear) { return nextCal; } // If the next year is lesser than the current year, then // we have no more timeouts for the calendar expression if (nextYear < currentYear) { return null; } // at this point we have chosen a year which is greater than the current // year. // set the chosen year nextCal.set(Calendar.YEAR, nextYear); // since we are moving to a different year (as compared to the current year), // we should reset all other calendar attribute expressions appropriately, to their first possible // values nextCal.set(Calendar.MONTH, this.month.getFirstMatch()); nextCal.set(Calendar.DAY_OF_MONTH, 1); resetTimeToFirstValues(nextCal); // recompute date nextCal = this.computeNextDate(nextCal); return nextCal; } private Calendar advanceTillMonthHasDate(Calendar cal, Integer date) { resetTimeToFirstValues(cal); // make sure the month can handle the date while (monthHasDate(cal, date) == false) { if (cal.get(Calendar.YEAR) > Year.MAX_YEAR) { return null; } // this month can't handle the date, so advance month to next month // and get the next suitable matching month cal.add(Calendar.MONTH, 1); cal = this.computeNextMonth(cal); if (cal == null) { return null; } date = this.dayOfMonth.getFirstMatch(cal); if (date == null) { return null; } } cal.set(Calendar.DAY_OF_MONTH, date); return cal; } private boolean monthHasDate(Calendar cal, int date) { return date <= cal.getActualMaximum(Calendar.DAY_OF_MONTH); } private boolean isAfterEnd(Calendar cal) { // check that the next timeout isn't past the end date return (this.end != null) ? cal.getTime().after(this.end) : false; } private boolean noMoreTimeouts(Calendar cal) { if (cal.get(Calendar.YEAR) > Year.MAX_YEAR || isAfterEnd(cal)) { return true; } return false; } private boolean isDayOfWeekWildcard() { return this.dayOfWeek.getType() == ScheduleExpressionType.WILDCARD; } private boolean isDayOfMonthWildcard() { return this.dayOfMonth.getType() == ScheduleExpressionType.WILDCARD; } /** * * @param calendar */ private void resetTimeToFirstValues(Calendar calendar) { final int currentHour = calendar.get(Calendar.HOUR_OF_DAY); final int currentMinute = calendar.get(Calendar.MINUTE); final int currentSecond = calendar.get(Calendar.SECOND); final int firstHour = this.hour.getFirst(); final int firstMinute = this.minute.getFirst(); final int firstSecond = this.second.getFirst(); if (currentHour != firstHour || currentMinute != firstMinute || currentSecond != firstSecond) { setTime(calendar, firstHour, firstMinute, firstSecond); } } private void setTime(Calendar calendar, int hour, int minute, int second) { int dst = calendar.get(Calendar.DST_OFFSET); calendar.clear(Calendar.HOUR_OF_DAY); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.clear(Calendar.MINUTE); calendar.set(Calendar.MINUTE, minute); calendar.clear(Calendar.SECOND); calendar.set(Calendar.SECOND, second); // restore summertime offset WFLY-9537 // this is to avoid to have the standard time (winter) set by GregorianCalendar // after clear and set the time explicit // see comment for computeTime() -> http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/GregorianCalendar.java#2776 calendar.set(Calendar.DST_OFFSET, dst); } }
22,402
37.759516
183
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/schedule/attribute/Month.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.schedule.attribute; import java.util.Calendar; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType; /** * Month * * @author Jaikiran Pai * @version $Revision: $ */ public class Month extends IntegerBasedExpression { public static final Integer MAX_MONTH = 12; public static final Integer MIN_MONTH = 1; private static final Map<String, Integer> MONTH_ALIAS = new HashMap<String, Integer>(); static { MONTH_ALIAS.put("jan", 1); MONTH_ALIAS.put("feb", 2); MONTH_ALIAS.put("mar", 3); MONTH_ALIAS.put("apr", 4); MONTH_ALIAS.put("may", 5); MONTH_ALIAS.put("jun", 6); MONTH_ALIAS.put("jul", 7); MONTH_ALIAS.put("aug", 8); MONTH_ALIAS.put("sep", 9); MONTH_ALIAS.put("oct", 10); MONTH_ALIAS.put("nov", 11); MONTH_ALIAS.put("dec", 12); } private static final int OFFSET = MONTH_ALIAS.get("jan") - Calendar.JANUARY; private SortedSet<Integer> offsetAdjustedMonths = new TreeSet<Integer>(); public Month(String value) { super(value); if (OFFSET != 0) { for (Integer month : this.absoluteValues) { this.offsetAdjustedMonths.add(month - OFFSET); } } else { this.offsetAdjustedMonths = this.absoluteValues; } } @Override protected Integer getMaxValue() { return MAX_MONTH; } @Override protected Integer getMinValue() { return MIN_MONTH; } @Override public boolean isRelativeValue(String value) { // month doesn't support relative values, so always return false return false; } @Override protected boolean accepts(ScheduleExpressionType scheduleExprType) { switch (scheduleExprType) { case RANGE: case LIST: case SINGLE_VALUE: case WILDCARD: return true; // month doesn't support increment case INCREMENT: default: return false; } } @Override protected Integer parseInt(String alias) { try { return super.parseInt(alias); } catch (NumberFormatException nfe) { if (MONTH_ALIAS != null) { String lowerCaseAlias = alias.toLowerCase(Locale.ENGLISH); return MONTH_ALIAS.get(lowerCaseAlias); } } return null; } public Integer getNextMatch(Calendar currentCal) { if (this.scheduleExpressionType == ScheduleExpressionType.WILDCARD) { return currentCal.get(Calendar.MONTH); } if (this.offsetAdjustedMonths.isEmpty()) { return null; } int currentMonth = currentCal.get(Calendar.MONTH); for (Integer month : this.offsetAdjustedMonths) { if (currentMonth == month) { return currentMonth; } if (month > currentMonth) { return month; } } return this.offsetAdjustedMonths.first(); } public Integer getFirstMatch() { if (this.scheduleExpressionType == ScheduleExpressionType.WILDCARD) { return Calendar.JANUARY; } if (this.offsetAdjustedMonths.isEmpty()) { throw EjbLogger.EJB3_TIMER_LOGGER.invalidScheduleValue(Month.class.getSimpleName(), this.origValue); } return this.offsetAdjustedMonths.first(); } }
4,752
30.269737
112
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/schedule/attribute/Second.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.schedule.attribute; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType; /** * Represents the value of a second constructed out of a {@link jakarta.ejb.ScheduleExpression#getSecond()} * <p/> * <p> * A {@link Second} can hold only {@link Integer} as its value. The only exception to this being the wildcard (*) * value. The various ways in which a * {@link Second} value can be represented are: * <ul> * <li>Wildcard. For example, second = "*"</li> * <li>Range. For example, second = "0-34"</li> * <li>List. For example, second = "15, 20, 59"</li> * <li>Single value. For example, second = "12"</li> * <li>Increment. For example, second = "* &#47; 5"</li> * </ul> * </p> * * @author Jaikiran Pai * @version $Revision: $ */ public class Second extends IntegerBasedExpression { /** * The maximum allowed value for a second */ public static final Integer MAX_SECOND = 59; /** * Minimum allowed value for a second */ public static final Integer MIN_SECOND = 0; /** * Creates a {@link Second} by parsing the passed {@link String} <code>value</code> * <p> * Valid values are of type {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#WILDCARD}, {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#RANGE}, * {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#LIST} {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#INCREMENT} or * {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#SINGLE_VALUE} * </p> * * @param value The value to be parsed * @throws IllegalArgumentException If the passed <code>value</code> is neither a {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#WILDCARD}, * {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#RANGE}, {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#LIST}, * {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#INCREMENT} nor {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#SINGLE_VALUE}. */ public Second(String value) { super(value); } public Integer getNextMatch(int currentSecond) { if (this.scheduleExpressionType == ScheduleExpressionType.WILDCARD) { return currentSecond; } if (this.absoluteValues.isEmpty()) { return null; } for (Integer second : this.absoluteValues) { if (currentSecond == second) { return currentSecond; } if (second > currentSecond) { return second; } } return this.absoluteValues.first(); } public int getFirst() { if (this.scheduleExpressionType == ScheduleExpressionType.WILDCARD) { return 0; } if (this.absoluteValues.isEmpty()) { throw EjbLogger.EJB3_TIMER_LOGGER.invalidScheduleValue(Second.class.getSimpleName(), this.origValue); } return this.absoluteValues.first(); } /** * Returns the maximum allowed value for a {@link Second} * * @see Second#MAX_SECOND */ @Override protected Integer getMaxValue() { return MAX_SECOND; } /** * Returns the minimum allowed value for a {@link Second} * * @see Second#MIN_SECOND */ @Override protected Integer getMinValue() { return MIN_SECOND; } @Override public boolean isRelativeValue(String value) { // seconds do not support relative values, so always return false return false; } @Override protected boolean accepts(ScheduleExpressionType scheduleExprType) { switch (scheduleExprType) { case RANGE: case LIST: case SINGLE_VALUE: case WILDCARD: case INCREMENT: return true; default: return false; } } }
5,309
35.875
221
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/schedule/attribute/IntegerBasedExpression.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.schedule.attribute; import java.util.HashSet; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.timerservice.schedule.value.IncrementValue; import org.jboss.as.ejb3.timerservice.schedule.value.ListValue; import org.jboss.as.ejb3.timerservice.schedule.value.RangeValue; import org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType; import org.jboss.as.ejb3.timerservice.schedule.value.ScheduleValue; import org.jboss.as.ejb3.timerservice.schedule.value.SingleValue; /** * Represents a {@link Integer} type value in a {@link jakarta.ejb.ScheduleExpression}. * <p/> * <p> * Examples for {@link IntegerBasedExpression} are the value of seconds, years, months etc... * which allow {@link Integer}. * </p> * * @author Jaikiran Pai * @version $Revision: $ */ public abstract class IntegerBasedExpression { protected abstract Integer getMaxValue(); protected abstract Integer getMinValue(); protected abstract boolean accepts(ScheduleExpressionType scheduleExprType); protected final SortedSet<Integer> absoluteValues = new TreeSet<Integer>(); protected final Set<ScheduleValue> relativeValues = new HashSet<ScheduleValue>(); protected final ScheduleExpressionType scheduleExpressionType; protected final String origValue; public IntegerBasedExpression(String value) { this.origValue = value; // check the type of value this.scheduleExpressionType = ScheduleExpressionType.getType(value); if (!this.accepts(scheduleExpressionType)) { throw EjbLogger.EJB3_TIMER_LOGGER.invalidScheduleExpressionType(value, this.getClass().getName(), this.scheduleExpressionType.toString()); } switch (this.scheduleExpressionType) { case RANGE: RangeValue range = new RangeValue(value); // process the range value this.processRangeValue(range); break; case LIST: ListValue list = new ListValue(value); // process the list value this.processListValue(list); break; case INCREMENT: IncrementValue incrValue = new IncrementValue(value); // process the increment value this.processIncrement(incrValue); break; case SINGLE_VALUE: SingleValue singleValue = new SingleValue(value); // process the single value this.processSingleValue(singleValue); break; case WILDCARD: // a wildcard is equivalent to "all possible" values, so // do nothing break; default: throw EjbLogger.EJB3_TIMER_LOGGER.invalidValueForSecondInScheduleExpression(value); } } protected void processListValue(ListValue list) { for (String listItem : list.getValues()) { this.processListItem(listItem); } } protected void processListItem(String listItem) { // check what type of a value the list item is. // Each item in the list must be an individual attribute value or a range. // List items can not themselves be lists, wild-cards, or increments. ScheduleExpressionType listItemType = ScheduleExpressionType.getType(listItem); switch (listItemType) { case SINGLE_VALUE: SingleValue singleVal = new SingleValue(listItem); this.processSingleValue(singleVal); return; case RANGE: RangeValue range = new RangeValue(listItem); this.processRangeValue(range); return; default: throw EjbLogger.EJB3_TIMER_LOGGER.invalidListValue(listItem); } } protected void processRangeValue(RangeValue range) { String start = range.getStart(); String end = range.getEnd(); if (this.isRelativeValue(start) || this.isRelativeValue(end)) { this.relativeValues.add(range); return; } Integer rangeStart = this.parseInt(start); Integer rangeEnd = this.parseInt(end); // validations this.assertValid(rangeStart); this.assertValid(rangeEnd); // start and end are both the same. So it's just a single value if (rangeStart.equals(rangeEnd)) { this.absoluteValues.add(rangeStart); return; } if (rangeStart > rangeEnd) { // In range "x-y", if x is larger than y, the range is equivalent to // "x-max, min-y", where max is the largest value of the corresponding attribute // and min is the smallest. for (int i = rangeStart; i <= this.getMaxValue(); i++) { this.absoluteValues.add(i); } for (int i = this.getMinValue(); i <= rangeEnd; i++) { this.absoluteValues.add(i); } } else { // just keep adding from range start to range end (both inclusive). for (int i = rangeStart; i <= rangeEnd; i++) { this.absoluteValues.add(i); } } } protected void processIncrement(IncrementValue incr) { Integer start = incr.getStart(); // make sure it's a valid value this.assertValid(start); int interval = incr.getInterval(); this.absoluteValues.add(start); if (interval > 0) { int next = start + interval; int maxValue = this.getMaxValue(); while (next <= maxValue) { this.absoluteValues.add(next); next = next + interval; } } } protected void processSingleValue(SingleValue singleValue) { String value = singleValue.getValue(); if (this.isRelativeValue(value)) { this.relativeValues.add(singleValue); } else { Integer val = this.parseInt(value); this.assertValid(val); this.absoluteValues.add(val); } } protected Integer parseInt(String alias) { if (alias == null) { return null; } return Integer.parseInt(alias.trim()); } protected void assertValid(Integer value) throws IllegalArgumentException { if (value == null) { throw EjbLogger.EJB3_TIMER_LOGGER.invalidScheduleValue("", this.origValue); } int max = this.getMaxValue(); int min = this.getMinValue(); if (value > max || value < min) { throw EjbLogger.EJB3_TIMER_LOGGER.invalidValuesRange(value, min, max); } } /** * Checks if relative value is supported. * @param value non-null value * @return true if relative value is supported */ public abstract boolean isRelativeValue(String value); public ScheduleExpressionType getType() { return this.scheduleExpressionType; } }
8,215
35.353982
150
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/schedule/attribute/DayOfWeek.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.schedule.attribute; import java.util.Calendar; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType; /** * DayOfWeek * * @author Jaikiran Pai * @version $Revision: $ */ public class DayOfWeek extends IntegerBasedExpression { public static final Integer MAX_DAY_OF_WEEK = 7; public static final Integer MIN_DAY_OF_WEEK = 0; static final Map<String, Integer> DAY_OF_WEEK_ALIAS = new HashMap<>(); static { DAY_OF_WEEK_ALIAS.put("sun", 0); DAY_OF_WEEK_ALIAS.put("mon", 1); DAY_OF_WEEK_ALIAS.put("tue", 2); DAY_OF_WEEK_ALIAS.put("wed", 3); DAY_OF_WEEK_ALIAS.put("thu", 4); DAY_OF_WEEK_ALIAS.put("fri", 5); DAY_OF_WEEK_ALIAS.put("sat", 6); } private static final int OFFSET = DAY_OF_WEEK_ALIAS.get("sun") - Calendar.SUNDAY; private SortedSet<Integer> offsetAdjustedDaysOfWeek = new TreeSet<>(); public DayOfWeek(String value) { super(value); for (Integer dayOfWeek : this.absoluteValues) { if (dayOfWeek == 7) { this.absoluteValues.remove(dayOfWeek); this.absoluteValues.add(0); } } if (OFFSET != 0) { for (Integer dayOfWeek : this.absoluteValues) { this.offsetAdjustedDaysOfWeek.add(dayOfWeek - OFFSET); } } else { this.offsetAdjustedDaysOfWeek = this.absoluteValues; } } @Override protected Integer getMaxValue() { return MAX_DAY_OF_WEEK; } @Override protected Integer getMinValue() { return MIN_DAY_OF_WEEK; } public int getFirst() { if (this.scheduleExpressionType == ScheduleExpressionType.WILDCARD) { return Calendar.SUNDAY; } return this.offsetAdjustedDaysOfWeek.first(); } @Override protected boolean accepts(ScheduleExpressionType scheduleExprType) { switch (scheduleExprType) { case RANGE: case LIST: case SINGLE_VALUE: case WILDCARD: return true; // day-of-week doesn't support increment case INCREMENT: default: return false; } } @Override public boolean isRelativeValue(String value) { // day-of-week doesn't support relative values return false; } @Override protected Integer parseInt(String alias) { try { return super.parseInt(alias); } catch (NumberFormatException nfe) { String lowerCaseAlias = alias.toLowerCase(Locale.ENGLISH); return DAY_OF_WEEK_ALIAS.get(lowerCaseAlias); } } public Integer getNextMatch(Calendar currentCal) { if (this.scheduleExpressionType == ScheduleExpressionType.WILDCARD) { return currentCal.get(Calendar.DAY_OF_WEEK); } int currentDayOfWeek = currentCal.get(Calendar.DAY_OF_WEEK); for (Integer dayOfWeek : this.offsetAdjustedDaysOfWeek) { if (currentDayOfWeek == dayOfWeek) { return currentDayOfWeek; } if (dayOfWeek > currentDayOfWeek) { return dayOfWeek; } } return this.offsetAdjustedDaysOfWeek.first(); } }
4,520
30.395833
85
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/schedule/attribute/Minute.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.schedule.attribute; import java.util.SortedSet; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType; /** * Represents the value of a minute constructed out of a {@link jakarta.ejb.ScheduleExpression#getMinute()} * <p/> * <p> * A {@link Minute} can hold only {@link Integer} as its value. The only exception to this being the wildcard (*) * value. The various ways in which a * {@link Minute} value can be represented are: * <ul> * <li>Wildcard. For example, minute = "*"</li> * <li>Range. For example, minute = "0-20"</li> * <li>List. For example, minute = "10, 30, 45"</li> * <li>Single value. For example, minute = "8"</li> * <li>Increment. For example, minute = "10 &#47; 15"</li> * </ul> * </p> * * @author Jaikiran Pai * @version $Revision: $ */ public class Minute extends IntegerBasedExpression { /** * Maximum allowed value for a {@link Minute} */ public static final Integer MAX_MINUTE = 59; /** * Minimum allowed value for a {@link Minute} */ public static final Integer MIN_MINUTE = 0; /** * Creates a {@link Minute} by parsing the passed {@link String} <code>value</code> * <p> * Valid values are of type {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#WILDCARD}, {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#RANGE}, * {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#LIST} {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#INCREMENT} or * {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#SINGLE_VALUE} * </p> * * @param value The value to be parsed * @throws IllegalArgumentException If the passed <code>value</code> is neither a {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#WILDCARD}, * {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#RANGE}, {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#LIST}, * {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#INCREMENT} nor {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#SINGLE_VALUE}. */ public Minute(String value) { super(value); } public int getFirst() { if (this.scheduleExpressionType == ScheduleExpressionType.WILDCARD) { return 0; } SortedSet<Integer> eligibleMinutes = this.getEligibleMinutes(); if (eligibleMinutes.isEmpty()) { throw EjbLogger.EJB3_TIMER_LOGGER.invalidScheduleValue(Minute.class.getSimpleName(), this.origValue); } return eligibleMinutes.first(); } /** * Returns the maximum allowed value for a {@link Minute} * * @see Minute#MAX_MINUTE */ @Override protected Integer getMaxValue() { return MAX_MINUTE; } /** * Returns the minimum allowed value for a {@link Minute} * * @see Minute#MIN_MINUTE */ @Override protected Integer getMinValue() { return MIN_MINUTE; } @Override public boolean isRelativeValue(String value) { // minute doesn't support relative values, hence // return false always return false; } @Override protected boolean accepts(ScheduleExpressionType scheduleExprType) { switch (scheduleExprType) { case RANGE: case LIST: case SINGLE_VALUE: case WILDCARD: case INCREMENT: return true; default: return false; } } private SortedSet<Integer> getEligibleMinutes() { return this.absoluteValues; } public Integer getNextMatch(int currentMinute) { if (this.scheduleExpressionType == ScheduleExpressionType.WILDCARD) { return currentMinute; } if (this.absoluteValues.isEmpty()) { return null; } for (Integer minute : this.absoluteValues) { if (currentMinute == minute) { return currentMinute; } if (minute > currentMinute) { return minute; } } return this.absoluteValues.first(); } }
5,527
35.130719
221
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/schedule/attribute/Year.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.schedule.attribute; import org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType; import java.util.Calendar; /** * Represents in the year value part constructed out of a {@link jakarta.ejb.ScheduleExpression#getYear()} * <p/> * <p> * A {@link Year} can hold only {@link Integer} as its value. The only exception to this being the wildcard (*) * value. The various ways in which a * {@link Year} value can be represented are: * <ul> * <li>Wildcard. For example, year = "*"</li> * <li>Range. For example, year = "2009-2011"</li> * <li>List. For example, year = "2008, 2010, 2011"</li> * <li>Single value. For example, year = "2009"</li> * </ul> * </p> * * @author Jaikiran Pai * @version $Revision: $ */ public class Year extends IntegerBasedExpression { // The Enterprise Beans 3. timer service spec says that the year // value can be any 4 digit value. // Hence the max value 9999 public static final Integer MAX_YEAR = 9999; // TODO: think about this min value. The Enterprise Beans 3.1 timerservice spec // says, that the year value can be any 4 digit value. // That's the reason we have set it to 1000 here. public static final Integer MIN_YEAR = 1000; /** * Creates a {@link Year} by parsing the passed {@link String} <code>value</code> * <p> * Valid values are of type {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#WILDCARD}, {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#RANGE}, * {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#LIST} or {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#SINGLE_VALUE} * </p> * * @param value The value to be parsed * @throws IllegalArgumentException If the passed <code>value</code> is neither a {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#WILDCARD}, * {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#RANGE}, {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#LIST} * nor {@link org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType#SINGLE_VALUE} */ public Year(String value) { super(value); } /** * Returns the maximum possible value for a {@link Year} * * @see Year#MAX_YEAR */ @Override protected Integer getMaxValue() { return MAX_YEAR; } /** * Returns the minimum possible value for a {@link Year} * * @see Year#MIN_YEAR */ @Override protected Integer getMinValue() { return MIN_YEAR; } @Override public boolean isRelativeValue(String value) { // year doesn't support relative values, so always return false return false; } @Override protected boolean accepts(ScheduleExpressionType scheduleExprType) { switch (scheduleExprType) { case RANGE: case LIST: case SINGLE_VALUE: case WILDCARD: return true; // year doesn't support increment case INCREMENT: default: return false; } } public Integer getNextMatch(Calendar currentCal) { if (this.scheduleExpressionType == ScheduleExpressionType.WILDCARD) { return currentCal.get(Calendar.YEAR); } if (this.absoluteValues.isEmpty()) { return null; } int currentYear = currentCal.get(Calendar.YEAR); for (Integer year : this.absoluteValues) { if (currentYear == year) { return currentYear; } if (year > currentYear) { return year; } } return this.absoluteValues.first(); } }
4,998
36.02963
205
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/schedule/attribute/Hour.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.schedule.attribute; import org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType; /** * Represents the value of a hour constructed out of a {@link jakarta.ejb.ScheduleExpression#getHour()} * <p/> * <p> * A {@link Hour} can hold only {@link Integer} as its value. The only exception to this being the wildcard (*) * value. The various ways in which a * {@link Hour} value can be represented are: * <ul> * <li>Wildcard. For example, hour = "*"</li> * <li>Range. For example, hour = "0-23"</li> * <li>List. For example, hour = "1, 12, 20"</li> * <li>Single value. For example, hour = "5"</li> * <li>Increment. For example, hour = "0 &#47; 3"</li> * </ul> * </p> * * @author Jaikiran Pai * @version $Revision: $ */ public class Hour extends IntegerBasedExpression { /** * Maximum allowed value for a {@link Hour} */ public static final Integer MAX_HOUR = 23; /** * Minimum allowed value for a {@link Hour} */ public static final Integer MIN_HOUR = 0; /** * Creates a {@link Hour} by parsing the passed {@link String} <code>value</code> * <p> * Valid values are of type {@link ScheduleExpressionType#WILDCARD}, {@link ScheduleExpressionType#RANGE}, * {@link ScheduleExpressionType#LIST} {@link ScheduleExpressionType#INCREMENT} or * {@link ScheduleExpressionType#SINGLE_VALUE} * </p> * * @param value The value to be parsed * @throws IllegalArgumentException If the passed <code>value</code> is neither a {@link ScheduleExpressionType#WILDCARD}, * {@link ScheduleExpressionType#RANGE}, {@link ScheduleExpressionType#LIST}, * {@link ScheduleExpressionType#INCREMENT} nor {@link ScheduleExpressionType#SINGLE_VALUE}. */ public Hour(String value) { super(value); } public int getFirst() { if (this.scheduleExpressionType == ScheduleExpressionType.WILDCARD) { return 0; } return this.absoluteValues.first(); } /** * Returns the maximum allowed value for a {@link Hour} * * @see Hour#MAX_HOUR */ @Override protected Integer getMaxValue() { return MAX_HOUR; } /** * Returns the minimum allowed value for a {@link Hour} * * @see Hour#MIN_HOUR */ @Override protected Integer getMinValue() { return MIN_HOUR; } @Override public boolean isRelativeValue(String value) { // hour doesn't support relative values return false; } @Override protected boolean accepts(ScheduleExpressionType scheduleExprType) { switch (scheduleExprType) { case RANGE: case LIST: case SINGLE_VALUE: case WILDCARD: case INCREMENT: return true; default: return false; } } public Integer getNextMatch(int currentHour) { if (this.scheduleExpressionType == ScheduleExpressionType.WILDCARD) { return currentHour; } if (this.absoluteValues.isEmpty()) { return null; } for (Integer hour : this.absoluteValues) { if (currentHour == hour) { return currentHour; } if (hour > currentHour) { return hour; } } return this.absoluteValues.first(); } }
4,553
31.76259
129
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/schedule/attribute/DayOfMonth.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.schedule.attribute; import java.util.Calendar; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import java.util.regex.Pattern; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.timerservice.schedule.util.CalendarUtil; import org.jboss.as.ejb3.timerservice.schedule.value.RangeValue; import org.jboss.as.ejb3.timerservice.schedule.value.ScheduleExpressionType; import org.jboss.as.ejb3.timerservice.schedule.value.ScheduleValue; import org.jboss.as.ejb3.timerservice.schedule.value.SingleValue; /** * Represents the value of a day in a month, constructed out of a {@link jakarta.ejb.ScheduleExpression#getDayOfMonth()} * <p/> * <p> * A {@link DayOfMonth} can hold an {@link Integer} or a {@link String} as its value. * value. The various ways in which a * {@link DayOfMonth} value can be represented are: * <ul> * <li>Wildcard. For example, dayOfMonth = "*"</li> * <li>Range. Examples: * <ul> * <li>dayOfMonth = "1-10"</li> * <li>dayOfMonth = "Sun-Tue"</li> * <li>dayOfMonth = "1st-5th"</li> * </ul> * </li> * <li>List. Examples: * <ul> * <li>dayOfMonth = "1, 12, 20"</li> * <li>dayOfMonth = "Mon, Fri, Sun"</li> * <li>dayOfMonth = "3rd, 1st, Last"</li> * </ul> * </li> * <li>Single value. Examples: * <ul> * <li>dayOfMonth = "Fri"</li> * <li>dayOfMonth = "Last"</li> * <li>dayOfMonth = "10"</li> * </ul> * </li> * </ul> * </p> * * @author Jaikiran Pai * @version $Revision: $ */ public class DayOfMonth extends IntegerBasedExpression { /** * Regex pattern for multiple space characters */ public static final Pattern REGEX_SPACES = Pattern.compile("\\s+"); /** * The maximum allowed value for the {@link DayOfMonth} */ public static final Integer MAX_DAY_OF_MONTH = 31; /** * The minimum allowed value for the {@link DayOfMonth} */ public static final Integer MIN_DAY_OF_MONTH = -7; /** * A {@link DayOfMonth} can be represented as a {@link String} too (for example "1st", "Sun" etc...). * Internally, we map all allowed {@link String} values to their {@link Integer} equivalents. * This map holds the {@link String} name to {@link Integer} value mapping. */ private static final Map<String, Integer> ORDINAL_TO_WEEK_NUMBER_MAPPING = new HashMap<>(8); static { ORDINAL_TO_WEEK_NUMBER_MAPPING.put("1st", 1); ORDINAL_TO_WEEK_NUMBER_MAPPING.put("2nd", 2); ORDINAL_TO_WEEK_NUMBER_MAPPING.put("3rd", 3); ORDINAL_TO_WEEK_NUMBER_MAPPING.put("4th", 4); ORDINAL_TO_WEEK_NUMBER_MAPPING.put("5th", 5); } /** * Creates a {@link DayOfMonth} by parsing the passed {@link String} <code>value</code> * <p> * Valid values are of type {@link ScheduleExpressionType#WILDCARD}, {@link ScheduleExpressionType#RANGE}, * {@link ScheduleExpressionType#LIST} or {@link ScheduleExpressionType#SINGLE_VALUE} * </p> * * @param value The value to be parsed * @throws IllegalArgumentException If the passed <code>value</code> is neither a {@link ScheduleExpressionType#WILDCARD}, * {@link ScheduleExpressionType#RANGE}, {@link ScheduleExpressionType#LIST}, * nor {@link ScheduleExpressionType#SINGLE_VALUE}. */ public DayOfMonth(String value) { super(value); } /** * Returns the maximum allowed value for a {@link DayOfMonth} * * @see DayOfMonth#MAX_DAY_OF_MONTH */ @Override protected Integer getMaxValue() { return MAX_DAY_OF_MONTH; } /** * Returns the minimum allowed value for a {@link DayOfMonth} * * @see DayOfMonth#MIN_DAY_OF_MONTH */ @Override protected Integer getMinValue() { return MIN_DAY_OF_MONTH; } public Integer getNextMatch(Calendar currentCal) { if (this.scheduleExpressionType == ScheduleExpressionType.WILDCARD) { return currentCal.get(Calendar.DAY_OF_MONTH); } int currentDayOfMonth = currentCal.get(Calendar.DAY_OF_MONTH); SortedSet<Integer> eligibleDaysOfMonth = this.getEligibleDaysOfMonth(currentCal); if (eligibleDaysOfMonth.isEmpty()) { return null; } for (Integer hour : eligibleDaysOfMonth) { if (currentDayOfMonth == hour) { return currentDayOfMonth; } if (hour > currentDayOfMonth) { return hour; } } return eligibleDaysOfMonth.first(); } @Override protected void assertValid(Integer value) throws IllegalArgumentException { if (value != null && value == 0) { throw EjbLogger.EJB3_TIMER_LOGGER.invalidScheduleValue(DayOfMonth.class.getSimpleName(), String.valueOf(value)); } super.assertValid(value); } private boolean hasRelativeDayOfMonth() { return !this.relativeValues.isEmpty(); } private SortedSet<Integer> getEligibleDaysOfMonth(Calendar cal) { if (!this.hasRelativeDayOfMonth()) { return this.absoluteValues; } SortedSet<Integer> eligibleDaysOfMonth = new TreeSet<>(this.absoluteValues); for (ScheduleValue relativeValue : this.relativeValues) { if (relativeValue instanceof SingleValue) { SingleValue singleValue = (SingleValue) relativeValue; String value = singleValue.getValue(); Integer absoluteDayOfMonth = this.getAbsoluteDayOfMonth(cal, value); eligibleDaysOfMonth.add(absoluteDayOfMonth); } else if (relativeValue instanceof RangeValue) { RangeValue range = (RangeValue) relativeValue; String start = range.getStart(); String end = range.getEnd(); Integer dayOfMonthStart; // either start will be relative or end will be relative or both are relative if (this.isRelativeValue(start)) { dayOfMonthStart = this.getAbsoluteDayOfMonth(cal, start); } else { dayOfMonthStart = this.parseInt(start); } Integer dayOfMonthEnd; if (this.isRelativeValue(end)) { dayOfMonthEnd = this.getAbsoluteDayOfMonth(cal, end); } else { dayOfMonthEnd = this.parseInt(end); } // validations this.assertValid(dayOfMonthStart); this.assertValid(dayOfMonthEnd); // start and end are both the same. So it's just a single value if (dayOfMonthStart.equals(dayOfMonthEnd)) { eligibleDaysOfMonth.add(dayOfMonthEnd); continue; } if (dayOfMonthStart > dayOfMonthEnd) { // In range "x-y", if x is larger than y, the range is equivalent to // "x-max, min-y", where max is the largest value of the corresponding attribute // and min is the smallest. for (int i = dayOfMonthStart; i <= this.getMaxValue(); i++) { eligibleDaysOfMonth.add(i); } for (int i = this.getMinValue(); i <= dayOfMonthEnd; i++) { eligibleDaysOfMonth.add(i); } } else { // just keep adding from range start to range end (both inclusive). for (int i = dayOfMonthStart; i <= dayOfMonthEnd; i++) { eligibleDaysOfMonth.add(i); } } } } return eligibleDaysOfMonth; } /** * Gets the absolute day of month. * @param cal the calendar * @param trimmedRelativeDayOfMonth a non-null, trimmed, relative day of month * @return the absolute day of month */ private int getAbsoluteDayOfMonth(Calendar cal, String trimmedRelativeDayOfMonth) { if (trimmedRelativeDayOfMonth.isEmpty()) { throw EjbLogger.EJB3_TIMER_LOGGER.invalidScheduleValue(DayOfMonth.class.getSimpleName(), trimmedRelativeDayOfMonth); } trimmedRelativeDayOfMonth = trimmedRelativeDayOfMonth.toLowerCase(Locale.ROOT); if (trimmedRelativeDayOfMonth.equals("last")) { return CalendarUtil.getLastDateOfMonth(cal); } if (this.isValidNegativeDayOfMonth(trimmedRelativeDayOfMonth)) { int negativeRelativeDayOfMonth = Integer.parseInt(trimmedRelativeDayOfMonth); int lastDayOfCurrentMonth = CalendarUtil.getLastDateOfMonth(cal); return lastDayOfCurrentMonth + negativeRelativeDayOfMonth; } String[] parts = splitDayOfWeekBased(trimmedRelativeDayOfMonth); if (parts != null) { String ordinal = parts[0]; String day = parts[1]; // DAY_OF_WEEK_ALIAS value is 0-based, while Calendar.SUNDAY is 1, // MONDAY is 2, so need to add 1 match Calendar's value. int dayOfWeek = DayOfWeek.DAY_OF_WEEK_ALIAS.get(day) + 1; Integer date; if (ordinal.equals("last")) { date = CalendarUtil.getDateOfLastDayOfWeekInMonth(cal, dayOfWeek); } else { int weekNumber = ORDINAL_TO_WEEK_NUMBER_MAPPING.get(ordinal); date = CalendarUtil.getNthDayOfMonth(cal, weekNumber, dayOfWeek); } // TODO: Rethink about this. The reason why we have this currently is to handle cases like: // 5th Wed which may not be valid for all months (i.e. all months do not have 5 weeks). In such // cases we set the date to last date of the month. // This needs to be thought about a bit more in detail, to understand it's impact on other scenarios. if (date == null) { date = CalendarUtil.getLastDateOfMonth(cal); } return date; } throw EjbLogger.EJB3_TIMER_LOGGER.invalidScheduleValue(DayOfMonth.class.getSimpleName(), trimmedRelativeDayOfMonth); } private boolean isValidNegativeDayOfMonth(String dayOfMonth) { try { int val = Integer.parseInt(dayOfMonth.trim()); if (val <= -1 && val >= -7) { return true; } return false; } catch (NumberFormatException nfe) { return false; } } /** * Checks if a relative value is weekOfDay-based, and splits the passed * {@code trimmedLowerCaseRelativeVal} to 2 parts. * @param trimmedLowerCaseRelativeVal must be non-null, trimmed and lower case value * @return 2 parts, or null if {@code trimmedLowerCaseRelativeVal} is not dayOfWeek-based */ private String[] splitDayOfWeekBased(String trimmedLowerCaseRelativeVal) { String[] relativeParts = REGEX_SPACES.split(trimmedLowerCaseRelativeVal); if (relativeParts == null) { return null; } if (relativeParts.length != 2) { return null; } String lowerCaseOrdinal = relativeParts[0]; String lowerCaseDayOfWeek = relativeParts[1]; if (lowerCaseOrdinal == null || lowerCaseDayOfWeek == null) { return null; } if (!ORDINAL_TO_WEEK_NUMBER_MAPPING.containsKey(lowerCaseOrdinal) && !lowerCaseOrdinal.equals("last")) { return null; } if (!DayOfWeek.DAY_OF_WEEK_ALIAS.containsKey(lowerCaseDayOfWeek)) { return null; } return relativeParts; } @Override public boolean isRelativeValue(String value) { String lowerCaseValue = value.toLowerCase(Locale.ROOT); if (lowerCaseValue.equals("last")) { return true; } if (this.isValidNegativeDayOfMonth(lowerCaseValue)) { return true; } if (this.splitDayOfWeekBased(lowerCaseValue) != null) { return true; } return false; } @Override protected boolean accepts(ScheduleExpressionType scheduleExprType) { switch (scheduleExprType) { case RANGE: case LIST: case SINGLE_VALUE: case WILDCARD: return true; // day-of-month doesn't support increment case INCREMENT: default: return false; } } public Integer getFirstMatch(Calendar cal) { if (this.scheduleExpressionType == ScheduleExpressionType.WILDCARD) { return Calendar.SUNDAY; } SortedSet<Integer> eligibleDaysOfMonth = this.getEligibleDaysOfMonth(cal); if (eligibleDaysOfMonth.isEmpty()) { return null; } return eligibleDaysOfMonth.first(); } @Override protected Integer parseInt(String alias) { try { return super.parseInt(alias); } catch (NumberFormatException nfe) { String lowerCaseAlias = alias.toLowerCase(Locale.ENGLISH); final Integer dayOfWeekInteger = DayOfWeek.DAY_OF_WEEK_ALIAS.get(lowerCaseAlias); // DAY_OF_WEEK_ALIAS value is 0-based, while Calendar.SUNDAY is 1, // MONDAY is 2, so need to add 1 match Calendar's value. return dayOfWeekInteger == null ? null : dayOfWeekInteger + 1; } } }
14,653
37.563158
128
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/schedule/util/CalendarUtil.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.schedule.util; import java.util.Calendar; import java.util.GregorianCalendar; /** * CalendarUtil * * @author Jaikiran Pai * @version $Revision: $ */ public class CalendarUtil { /** * Returns the last date of the month represented by the passed <code>cal</code> * * @param calendar The {@link java.util.Calendar} whose {@link java.util.Calendar#MONTH} field will be used * as the current month * @return */ public static int getLastDateOfMonth(Calendar calendar) { Calendar tmpCal = new GregorianCalendar(calendar.getTimeZone()); tmpCal.set(Calendar.YEAR, calendar.get(Calendar.YEAR)); tmpCal.set(Calendar.MONTH, calendar.get(Calendar.MONTH)); tmpCal.set(Calendar.DAY_OF_MONTH, 1); return tmpCal.getActualMaximum(Calendar.DAY_OF_MONTH); } public static Integer getNthDayOfMonth(Calendar cal, int n, int dayOfWeek) { int dateOfFirstXXXDay = getFirstDateInMonthForDayOfWeek(cal, dayOfWeek); final int FIRST_WEEK = 1; final int NUM_DAYS_IN_WEEK = 7; int weekDiff = n - FIRST_WEEK; int dateOfNthXXXDayInMonth = dateOfFirstXXXDay + (weekDiff * NUM_DAYS_IN_WEEK); int maxDateInCurrentMonth = CalendarUtil.getLastDateOfMonth(cal); if (dateOfNthXXXDayInMonth > maxDateInCurrentMonth) { return null; } return dateOfNthXXXDayInMonth; } public static int getDateOfLastDayOfWeekInMonth(Calendar calendar, int dayOfWeek) { int lastDateOfMonth = getLastDateOfMonth(calendar); Calendar tmpCal = new GregorianCalendar(calendar.getTimeZone()); tmpCal.set(Calendar.YEAR, calendar.get(Calendar.YEAR)); tmpCal.set(Calendar.MONTH, calendar.get(Calendar.MONTH)); tmpCal.set(Calendar.DATE, lastDateOfMonth); int day = tmpCal.get(Calendar.DAY_OF_WEEK); if (day == dayOfWeek) { return tmpCal.get(Calendar.DATE); } while (day != dayOfWeek) { tmpCal.add(Calendar.DATE, -1); day = tmpCal.get(Calendar.DAY_OF_WEEK); } return tmpCal.get(Calendar.DATE); } private static int getFirstDateInMonthForDayOfWeek(Calendar cal, final int dayOfWeek) { Calendar tmpCal = new GregorianCalendar(cal.getTimeZone()); tmpCal.set(Calendar.YEAR, cal.get(Calendar.YEAR)); tmpCal.set(Calendar.MONTH, cal.get(Calendar.MONTH)); tmpCal.set(Calendar.DATE, 1); int day = tmpCal.get(Calendar.DAY_OF_WEEK); if (day == dayOfWeek) { return tmpCal.get(Calendar.DATE); } while (day != dayOfWeek) { tmpCal.add(Calendar.DATE, 1); day = tmpCal.get(Calendar.DAY_OF_WEEK); } return tmpCal.get(Calendar.DATE); } }
3,883
36.346154
111
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/schedule/value/ScheduleValue.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.schedule.value; /** * ScheduleValue * * @author Jaikiran Pai * @version $Revision: $ */ public interface ScheduleValue { }
1,202
34.382353
70
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/schedule/value/IncrementValue.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.schedule.value; import java.util.StringTokenizer; import org.jboss.as.ejb3.logging.EjbLogger; /** * Represents a value for a {@code ScheduleExpression} which is expressed as an increment type. An * {@link IncrementValue} comprises of a start value and an interval, separated by a "/" * <p/> * <p> * An {@link IncrementValue} is specified in the form of x&#47;y to mean "Every N { seconds | minutes | hours } * within the { minute | hour | day }" (respectively). For expression x/y, the attribute is constrained to * every yth value within the set of allowable values beginning at time x. The x value is inclusive. * The wildcard character (*) can be used in the x position, and is equivalent to 0. * </p> * * @author Jaikiran Pai * @version $Revision: $ * @see ScheduleExpressionType#INCREMENT */ public class IncrementValue implements ScheduleValue { /** * The separator which is used for parsing a {@link String} which * represents a {@link IncrementValue} */ public static final String INCREMENT_SEPARATOR = "/"; /** * The "x" value as {@code int} in the x&#47;y expression */ private final int start; /** * The "y" value as {@code int} in the x&#47;y expression */ private final int interval; /** * Creates a {@link IncrementValue} by parsing the passed <code>value</code>. * <p> * Upon successfully parsing the passed <code>value</code>, this constructor * sets the start value and the interval value of this {@link IncrementValue} * </p> * * @param value The value to be parsed * @throws IllegalArgumentException If the passed <code>value</code> cannot be * represented as an {@link IncrementValue} */ public IncrementValue(String value) { StringTokenizer tokenizer = new StringTokenizer(value, INCREMENT_SEPARATOR); int numberOfTokens = tokenizer.countTokens(); if (numberOfTokens != 2) { throw EjbLogger.EJB3_TIMER_LOGGER.invalidScheduleValue(ScheduleExpressionType.INCREMENT.name(), value); } String startVal = tokenizer.nextToken().trim(); String intervalVal = tokenizer.nextToken().trim(); try { this.start = "*".equals(startVal) ? 0 : Integer.parseInt(startVal); this.interval = Integer.parseInt(intervalVal); } catch (NumberFormatException e) { throw EjbLogger.EJB3_TIMER_LOGGER.invalidScheduleValue(ScheduleExpressionType.INCREMENT.name(), value); } // start will be validated by the target timer attribute classes // (Hour, Minute, and Second) accordingly. // check for invalid interval values here. // Note that 0 interval is valid, making this increment value behave as if it's a single value. if (this.interval < 0) { throw EjbLogger.EJB3_TIMER_LOGGER.invalidScheduleValue(ScheduleExpressionType.INCREMENT.name(), value); } } /** * Returns the start of this {@link IncrementValue} * * @return int start value */ public int getStart() { return this.start; } /** * Returns the interval of this {@link IncrementValue} * * @return int interval value */ public int getInterval() { return this.interval; } }
4,432
37.215517
115
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/schedule/value/ScheduleExpressionType.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.schedule.value; import org.jboss.as.ejb3.logging.EjbLogger; /** * Represents the type of expression used in the values of a {@link jakarta.ejb.ScheduleExpression} * * @author Jaikiran Pai * @version $Revision: $ */ public enum ScheduleExpressionType { /** * Represents a single value type. * <p> * For example: * <ul> * <li>second = "10"</li> * <li>month = "Jun"</li> * </ul> * <p/> * <p/> * </p> */ SINGLE_VALUE, /** * Represents a wildcard "*" value. * <p/> * <p> * For example: * <ul> * <li>second = "*"</li> * </ul> * </p> */ WILDCARD, /** * Represents a value represented as a list. * <p/> * <p> * For example: * <ul> * <li>second = "1, 10"</li> * <li>dayOfMonth = "Sun, Fri, Mon"</li> * <ul> * </p> */ LIST, /** * Represents a value represented as a range. * <p> * For example: * <ul> * <li>minute = "0-15"</li> * <li>year = "2009-2012</li> * </ul> * </p> */ RANGE, /** * Represents a value represented as an increment. * <p> * For example: * <ul> * <li>hour = "* &#47; 3"</li> * <li>minute = "20 &#47; 10</li> * </ul> * </p> */ INCREMENT; public static ScheduleExpressionType getType(String value) { if (value == null) { throw EjbLogger.EJB3_TIMER_LOGGER.invalidScheduleValue("", value); } // Order of check is important. // TODO: Explain why this order is important if (value.trim().equals("*")) { return ScheduleExpressionType.WILDCARD; } if (value.contains(",")) { return ScheduleExpressionType.LIST; } if (value.contains("-") && RangeValue.accepts(value)) { return ScheduleExpressionType.RANGE; } if (value.contains("/")) { return ScheduleExpressionType.INCREMENT; } return ScheduleExpressionType.SINGLE_VALUE; } }
3,163
25.588235
99
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/schedule/value/ListValue.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.schedule.value; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import org.jboss.as.ejb3.logging.EjbLogger; /** * Represents a value for a {@link jakarta.ejb.ScheduleExpression} which is expressed as a list type. A * {@link ListValue} comprises of values separated by a ",". * <p/> * <p> * Each value in the {@link ListValue} must be an individual attribute value or a range. * List items <b>cannot</b> themselves be lists, wild-cards, or increments. * Duplicate values are allowed, but are ignored. * </p> * * @author Jaikiran Pai * @version $Revision: $ * @see ScheduleExpressionType#LIST */ public class ListValue implements ScheduleValue { /** * Separator used for parsing a {@link String} which represents * a {@link ListValue} */ public static final String LIST_SEPARATOR = ","; /** * The individual values in a {@link ListValue} * <p> * Each value in this set may be a {@link String} representing a {@link SingleValue} * or a {@link RangeValue} * </p> */ private final List<String> values = new ArrayList<String>(); /** * Creates a {@link ListValue} by parsing the passed <code>value</code>. * * @param list The value to be parsed * @throws IllegalArgumentException If the passed <code>value</code> cannot be * represented as an {@link ListValue} */ public ListValue(String list) { if (list == null || list.isEmpty()) { throw EjbLogger.EJB3_TIMER_LOGGER.invalidScheduleValue(ScheduleExpressionType.LIST.name(), list); } StringTokenizer tokenizer = new StringTokenizer(list, LIST_SEPARATOR); while (tokenizer.hasMoreTokens()) { String value = tokenizer.nextToken().trim(); this.values.add(value); } // a list MUST minimally contain 2 elements // Ex: "," "1," ", 2" are all invalid if (this.values.size() < 2) { throw EjbLogger.EJB3_TIMER_LOGGER.invalidScheduleValue(ScheduleExpressionType.LIST.name(), list); } } /** * Returns the values that make up the {@link ListValue}. * <p> * Each value in this set may be a {@link String} representing a {@link SingleValue} * or a {@link RangeValue} * </p> * * @return */ public List<String> getValues() { return this.values; } }
3,521
34.938776
109
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/schedule/value/RangeValue.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.schedule.value; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jboss.as.ejb3.logging.EjbLogger; /** * Represents a value for a {@link jakarta.ejb.ScheduleExpression} which is expressed as a range type. An * {@link RangeValue} comprises of a start and an end value for the range, separated by a "-" * <p/> * <p> * Each side of the range must be an individual attribute value. Members of a range <b>cannot</b> themselves * be lists, wild-cards, ranges, or increments. In range ”x-y”, if x is larger than y, the range is equivalent * to “x-max, min-y”, where max is the largest value of the corresponding attribute and min is the * smallest. The range “x-x”, where both range values are the same, evaluates to the single value x. * </p> * * @author Jaikiran Pai * @version $Revision: $ * @see ScheduleExpressionType#RANGE */ public class RangeValue implements ScheduleValue { /** * The separator which is used for parsing a {@link String} which * represents a {@link RangeValue} */ public static final String RANGE_SEPARATOR = "-"; private static final Pattern RANGE_PATTERN; static { final String POSITIVE_OR_NEGATIVE_INTEGER = "\\s*-?\\s*\\d+\\s*"; final String WORD = "\\s*([1-5][a-zA-Z]{2})?\\s*[a-zA-Z]+\\s*[a-zA-Z]*\\s*"; final String OR = "|"; final String OPEN_GROUP = "("; final String CLOSE_GROUP = ")"; String rangeRegex = OPEN_GROUP + POSITIVE_OR_NEGATIVE_INTEGER + OR + WORD + CLOSE_GROUP + RANGE_SEPARATOR + OPEN_GROUP + POSITIVE_OR_NEGATIVE_INTEGER + OR + WORD + CLOSE_GROUP; RANGE_PATTERN = Pattern.compile(rangeRegex); } /** * The start value of the range */ private String rangeStart; /** * The end value of the range */ private String rangeEnd; /** * Creates a {@link RangeValue} by parsing the passed <code>value</code>. * <p> * Upon successfully parsing the passed <code>value</code>, this constructor * sets the start and the end value of this {@link RangeValue} * </p> * * @param range The value to be parsed * @throws IllegalArgumentException If the passed <code>value</code> cannot be * represented as an {@link RangeValue} */ public RangeValue(String range) { String[] values = getRangeValues(range); if (values == null || values.length != 2) { throw EjbLogger.EJB3_TIMER_LOGGER.invalidScheduleValue(ScheduleExpressionType.RANGE.name(), range); } this.rangeStart = values[0].trim(); this.rangeEnd = values[1].trim(); } /** * Returns the start value of this {@link RangeValue} * * @return */ public String getStart() { return this.rangeStart; } /** * Returns the end value of this {@link RangeValue} * * @return */ public String getEnd() { return this.rangeEnd; } public static boolean accepts(String value) { if (value == null) { return false; } Matcher matcher = RANGE_PATTERN.matcher(value); return matcher.matches(); } private String[] getRangeValues(String val) { if (val == null) { return null; } Matcher matcher = RANGE_PATTERN.matcher(val); if (!matcher.matches()) { return null; } String[] rangeVals = new String[2]; rangeVals[0] = matcher.group(1); rangeVals[1] = matcher.group(3); return rangeVals; } public String asString() { return this.rangeStart + RANGE_SEPARATOR + this.rangeStart; } }
4,798
32.559441
113
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/schedule/value/SingleValue.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.schedule.value; /** * Represents a value for a {@link jakarta.ejb.ScheduleExpression} which is expressed as a single value * * @author Jaikiran Pai * @version $Revision: $ */ public class SingleValue implements ScheduleValue { /** * The value */ private final String value; /** * @param val */ public SingleValue(String val) { this.value = val.trim(); } public String getValue() { return this.value; } }
1,548
31.270833
103
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/persistence/TimeoutMethod.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.persistence; import java.io.Serializable; import java.util.Collections; import java.util.List; /** * TimeoutMethod * * @author Jaikiran Pai * @author Stuart Douglas */ public class TimeoutMethod implements Serializable { private static final long serialVersionUID = 3306711742026221772L; /** * Constant string value to indicate that the timeout method has 1 parameter, which must be jakarta.ejb.Timer */ public static final String TIMER_PARAM_1 = "1"; /** * Constant string array value to indicate that the timeout method has 1 * parameter, which must be jakarta.ejb.Timer */ public static final String[] TIMER_PARAM_1_ARRAY = new String[]{TIMER_PARAM_1}; /** * Internal immutable string list to indicate that the timeout method has 1 * parameter, which must be jakarta.ejb.Timer */ private static final List<String> TIMER_PARAM_1_LIST = Collections.singletonList("jakarta.ejb.Timer"); private String declaringClass; private String methodName; private List<String> methodParams; public TimeoutMethod(String declaringClass, String methodName, String[] methodParams) { this.declaringClass = declaringClass; this.methodName = methodName; if (methodParams == null || methodParams.length == 0) { this.methodParams = Collections.emptyList(); } else { this.methodParams = TIMER_PARAM_1_LIST; } } public String getMethodName() { return methodName; } public boolean hasTimerParameter() { return methodParams == TIMER_PARAM_1_LIST; } public String getDeclaringClass() { return declaringClass; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.declaringClass); sb.append("."); sb.append(this.methodName); sb.append("("); if (!this.methodParams.isEmpty()) { sb.append(this.methodParams.get(0)); } sb.append(")"); return sb.toString(); } }
3,156
31.885417
113
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/persistence/TimerPersistence.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.persistence; import java.io.Closeable; import java.util.List; import org.jboss.as.ejb3.timerservice.TimerImpl; import org.jboss.as.ejb3.timerservice.TimerServiceImpl; import org.jboss.msc.service.ServiceName; /** * @author Stuart Douglas */ public interface TimerPersistence { ServiceName SERVICE_NAME = ServiceName.JBOSS.append("ejb3", "timerService", "timerPersistence"); /** * Called when a timer is being persisted. * In a clustered environment, if an auto timer has already been persisted * by another concurrent node, it should not be persisted again, and its * state should be set to {@code CANCELED}. * * @param timer The timer */ void addTimer(TimerImpl timer); /** * Called when a timer is being persisted * * @param timer The timer */ void persistTimer(TimerImpl timer); /** * Invoked before running a timer in order to determine if this node should run the timer. * @param timer The timer * @return true if the timer should be run */ boolean shouldRun(TimerImpl timer); /** * Signals that the timer is being deployed and any internal structured required should be added. * @param timedObjectId */ default void timerDeployed(String timedObjectId) {} /** * Signals that a timer is being undeployed, and all cached data relating to this object should * be dropped to prevent a class loader leak * * @param timedObjectId */ void timerUndeployed(String timedObjectId); /** * Load all active timers for the given object. If the object is an entity bean timers for all beans will be returned. * * @param timedObjectId The timed object id to load timers for * @return A list of all active timers */ List<TimerImpl> loadActiveTimers(String timedObjectId, final TimerServiceImpl timerService); /** * * Registers a listener to listed for new timers that are added to the database. * * @param timedObjectId The timed object * @param listener The listener * @return A Closable that can be used to unregister the listener */ Closeable registerChangeListener(String timedObjectId, final TimerChangeListener listener); /** * Listener that gets invoked when a new timer is added to the underlying store. */ interface TimerChangeListener { /** * Invoked when a timer is added to the underlying store. * @param timer The timer */ void timerAdded(TimerImpl timer); /** * Invoked when a timer needs to be sync with the underlying store * @param oldTimer The timer in Server memory * @param newtimer The timer coming from the store */ void timerSync(TimerImpl oldTimer, TimerImpl newTimer); /** * Invoked when a timer is removed from the underlying store * @param timerId The timer */ void timerRemoved(String timerId); /** * Gets the timer service associated with this listener * * @return The timer service */ TimerServiceImpl getTimerService(); } }
4,264
32.320313
122
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/persistence/TimerEntity.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.persistence; import java.io.Serializable; import java.util.Date; import org.jboss.as.ejb3.timerservice.TimerImpl; import org.jboss.as.ejb3.timerservice.TimerState; /** * * DO NOT MODIFY THIS CLASS * * Due to a temporary implementation that became permanent, the {@link org.jboss.as.ejb3.timerservice.persistence.filestore.FileTimerPersistence} * writes these out directly, modifying this class will break compatibility * * @author <a href="mailto:[email protected]">Carlo de Wolf</a> * @author Stuart Douglas */ public class TimerEntity implements Serializable { private static final long serialVersionUID = 8229332510659372218L; protected final String id; protected final String timedObjectId; protected final Date initialDate; protected final long repeatInterval; protected final Date nextDate; protected final Date previousRun; protected final Serializable info; protected final TimerState timerState; public TimerEntity(TimerImpl timer) { this.id = timer.getId(); this.initialDate = timer.getInitialExpiration(); this.repeatInterval = timer.getInterval(); this.nextDate = timer.getNextExpiration(); this.previousRun = timer.getPreviousRun(); this.timedObjectId = timer.getTimedObjectId(); this.info = timer.getTimerInfo(); if (timer.getState() == TimerState.CREATED) { //a timer that has been persisted cannot be in the created state this.timerState = TimerState.ACTIVE; } else { this.timerState = timer.getState(); } } public String getId() { return id; } public String getTimedObjectId() { return timedObjectId; } public Date getInitialDate() { return initialDate; } public long getInterval() { return repeatInterval; } public Serializable getInfo() { return this.info; } public Date getNextDate() { return nextDate; } public Date getPreviousRun() { return previousRun; } public TimerState getTimerState() { return timerState; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof TimerEntity)) { return false; } TimerEntity other = (TimerEntity) obj; if (this.id == null) { return false; } return this.id.equals(other.id); } @Override public int hashCode() { if (this.id == null) { return super.hashCode(); } return this.id.hashCode(); } }
3,750
27.416667
145
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/persistence/CalendarTimerEntity.java
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.persistence; import java.lang.reflect.Method; import java.util.Date; import jakarta.ejb.ScheduleExpression; import org.jboss.as.ejb3.timerservice.CalendarTimer; /** * DO NOT MODIFY THIS CLASS * * Due to a temporary implementation that became permanent, the {@link org.jboss.as.ejb3.timerservice.persistence.filestore.FileTimerPersistence} * writes these out directly, modifying this class will break compatibility * * @author Jaikiran Pai * @author Stuart Douglas */ public class CalendarTimerEntity extends TimerEntity { private static final long serialVersionUID = -8641876649577480976L; private final String scheduleExprSecond; private final String scheduleExprMinute; private final String scheduleExprHour; private final String scheduleExprDayOfWeek; private final String scheduleExprDayOfMonth; private final String scheduleExprMonth; private final String scheduleExprYear; private final Date scheduleExprStartDate; private final Date scheduleExprEndDate; private final String scheduleExprTimezone; private final boolean autoTimer; private final TimeoutMethod timeoutMethod; public CalendarTimerEntity(CalendarTimer calendarTimer) { super(calendarTimer); this.autoTimer = calendarTimer.isAutoTimer(); if (calendarTimer.isAutoTimer()) { Method method = calendarTimer.getTimeoutMethod(); Class<?>[] methodParams = method.getParameterTypes(); String[] params = new String[methodParams.length]; for (int i = 0; i < methodParams.length; i++) { params[i] = methodParams[i].getName(); } this.timeoutMethod = new TimeoutMethod(method.getDeclaringClass().getName(), method.getName(), params); } else { this.timeoutMethod = null; } ScheduleExpression scheduleExpression = calendarTimer.getScheduleExpression(); this.scheduleExprSecond = scheduleExpression.getSecond(); this.scheduleExprMinute = scheduleExpression.getMinute(); this.scheduleExprHour = scheduleExpression.getHour(); this.scheduleExprDayOfMonth = scheduleExpression.getDayOfMonth(); this.scheduleExprMonth = scheduleExpression.getMonth(); this.scheduleExprDayOfWeek = scheduleExpression.getDayOfWeek(); this.scheduleExprYear = scheduleExpression.getYear(); this.scheduleExprStartDate = scheduleExpression.getStart(); this.scheduleExprEndDate = scheduleExpression.getEnd(); this.scheduleExprTimezone = scheduleExpression.getTimezone(); } public String getSecond() { return scheduleExprSecond; } public String getMinute() { return scheduleExprMinute; } public String getHour() { return scheduleExprHour; } public String getDayOfWeek() { return scheduleExprDayOfWeek; } public String getDayOfMonth() { return scheduleExprDayOfMonth; } public String getMonth() { return scheduleExprMonth; } public String getYear() { return scheduleExprYear; } public Date getStartDate() { return scheduleExprStartDate; } public Date getEndDate() { return scheduleExprEndDate; } public TimeoutMethod getTimeoutMethod() { return timeoutMethod; } public boolean isAutoTimer() { return autoTimer; } public String getTimezone() { return scheduleExprTimezone; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj instanceof CalendarTimerEntity == false) { return false; } CalendarTimerEntity other = (CalendarTimerEntity) obj; if (this.id == null) { return false; } return this.id.equals(other.id); } @Override public int hashCode() { if (this.id == null) { return super.hashCode(); } return this.id.hashCode(); } }
5,139
29.778443
145
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/persistence/database/DatabaseTimerPersistence.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.persistence.database; import static org.jboss.as.ejb3.timerservice.TimerServiceImpl.safeClose; import static org.jboss.as.ejb3.util.MethodInfoHelper.EMPTY_STRING_ARRAY; import static org.jboss.as.ejb3.timerservice.persistence.TimeoutMethod.TIMER_PARAM_1; import static org.jboss.as.ejb3.timerservice.persistence.TimeoutMethod.TIMER_PARAM_1_ARRAY; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.sql.Types; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Base64; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.regex.Pattern; import jakarta.ejb.ScheduleExpression; import javax.sql.DataSource; import jakarta.transaction.HeuristicMixedException; import jakarta.transaction.HeuristicRollbackException; import jakarta.transaction.NotSupportedException; import jakarta.transaction.RollbackException; import jakarta.transaction.SystemException; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.timerservice.CalendarTimer; import org.jboss.as.ejb3.timerservice.TimerImpl; import org.jboss.as.ejb3.timerservice.TimerServiceImpl; import org.jboss.as.ejb3.timerservice.TimerState; import org.jboss.as.ejb3.timerservice.persistence.TimeoutMethod; import org.jboss.as.ejb3.timerservice.persistence.TimerPersistence; import org.jboss.as.naming.ManagedReference; import org.jboss.as.naming.ManagedReferenceFactory; import org.jboss.marshalling.InputStreamByteInput; import org.jboss.marshalling.Marshaller; import org.jboss.marshalling.MarshallerFactory; import org.jboss.marshalling.MarshallingConfiguration; import org.jboss.marshalling.ModularClassResolver; import org.jboss.marshalling.OutputStreamByteOutput; import org.jboss.marshalling.Unmarshaller; import org.jboss.marshalling.river.RiverMarshallerFactory; import org.jboss.modules.ModuleLoader; import org.jboss.msc.Service; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.wildfly.security.manager.WildFlySecurityManager; import org.wildfly.transaction.client.ContextTransactionManager; /** * <p> * Database timer persistence store. * </p> * * @author Stuart Douglas * @author Wolf-Dieter Fink * @author Joerg Baesner */ public class DatabaseTimerPersistence implements TimerPersistence, Service { private final Consumer<DatabaseTimerPersistence> dbConsumer; private final Supplier<ManagedReferenceFactory> dataSourceSupplier; private final Supplier<ModuleLoader> moduleLoaderSupplier; private final Supplier<Timer> timerSupplier; private final Map<String, TimerChangeListener> changeListeners = Collections.synchronizedMap(new HashMap<String, TimerChangeListener>()); private final Map<String, Set<String>> knownTimerIds = new HashMap<>(); /** Identifier for the database dialect to be used for the timer-sql.properties */ private String database; /** Name of the configured partition name*/ private final String partition; /** Current node name*/ private final String nodeName; /** Interval in millis to refresh the timers from the persistence store*/ private final int refreshInterval; /** Flag whether this instance should execute persistent timers*/ private final boolean allowExecution; private volatile ManagedReference managedReference; private volatile DataSource dataSource; private volatile Properties sql; private MarshallerFactory factory; private MarshallingConfiguration configuration; private RefreshTask refreshTask; /** database values */ private static final String POSTGRES = "postgres"; private static final String POSTGRESQL = "postgresql"; private static final String MYSQL = "mysql"; private static final String MARIADB = "mariadb"; private static final String DB2 = "db2"; private static final String HSQL = "hsql"; private static final String HYPERSONIC = "hypersonic"; private static final String H2 = "h2"; private static final String ORACLE = "oracle"; private static final String MSSQL = "mssql"; private static final String SYBASE = "sybase"; private static final String JCONNECT = "jconnect"; private static final String ENTERPRISEDB = "enterprisedb"; /** Names for the different SQL commands stored in the properties*/ private static final String CREATE_TABLE = "create-table"; private static final String CREATE_TIMER = "create-timer"; private static final String CREATE_AUTO_TIMER = "create-auto-timer"; private static final String UPDATE_TIMER = "update-timer"; private static final String LOAD_ALL_TIMERS = "load-all-timers"; private static final String LOAD_TIMER = "load-timer"; private static final String DELETE_TIMER = "delete-timer"; private static final String UPDATE_RUNNING = "update-running"; private static final String GET_TIMER_INFO = "get-timer-info"; /** The format for scheduler start and end date*/ private static final String SCHEDULER_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; /** Pattern to pickout MSSQL */ private static final Pattern MSSQL_PATTERN = Pattern.compile("(sqlserver|microsoft|mssql)"); /** * System property {@code jboss.ejb.timer.database.clearTimerInfoCacheBeyond} * to configure the threshold (in minutes) to clear timer info cache * when database is used as the data store for the ejb timer service. * The default value is 15 minutes. * <p> * For example, if it is set to 10, and a timer is about to expire in * more than 10 minutes from now, its in-memory timer info is cleared; * if the timer is to expire within 10 minutes, its info is retained. * <p> * Timer info of the following types are always retained, regardless of the value of this property: * <ul> * <li>java.lang.String * <li>java.lang.Number * <li>java.util.Date * <li>java.lang.Character * <li>enum * </ul> */ private final long clearTimerInfoCacheBeyond = TimeUnit.MINUTES.toMillis(Long.parseLong( WildFlySecurityManager.getPropertyPrivileged("jboss.ejb.timer.database.clearTimerInfoCacheBeyond", "15"))); public DatabaseTimerPersistence(final Consumer<DatabaseTimerPersistence> dbConsumer, final Supplier<ManagedReferenceFactory> dataSourceSupplier, final Supplier<ModuleLoader> moduleLoaderSupplier, final Supplier<Timer> timerSupplier, final String database, String partition, String nodeName, int refreshInterval, boolean allowExecution) { this.dbConsumer = dbConsumer; this.dataSourceSupplier = dataSourceSupplier; this.moduleLoaderSupplier = moduleLoaderSupplier; this.timerSupplier = timerSupplier; this.database = database; this.partition = partition; this.nodeName = nodeName; this.refreshInterval = refreshInterval; this.allowExecution = allowExecution; } @Override public void start(final StartContext context) throws StartException { dbConsumer.accept(this); factory = new RiverMarshallerFactory(); configuration = new MarshallingConfiguration(); configuration.setClassResolver(ModularClassResolver.getInstance(moduleLoaderSupplier.get())); managedReference = dataSourceSupplier.get().getReference(); dataSource = (DataSource) managedReference.getInstance(); investigateDialect(); loadSqlProperties(); checkDatabase(); refreshTask = new RefreshTask(); if (refreshInterval > 0) { timerSupplier.get().schedule(refreshTask, refreshInterval, refreshInterval); } } @Override public synchronized void stop(final StopContext context) { dbConsumer.accept(null); refreshTask.cancel(); knownTimerIds.clear(); managedReference.release(); managedReference = null; dataSource = null; } /** * Loads timer-sql.properties into a {@code Properties}, and adjusts these * property entries based on the current database dialect. * <p> * If an entry key ends with a database dialect suffix for the current database dialect, * its value is copied to the entry with the corresponding generic key, and * this entry is removed. * <p> * If an entry key ends with a database dialect suffix different than the current one, * it is removed. * * @throws StartException if IOException when loading timer-sql.properties */ private void loadSqlProperties() throws StartException { final InputStream stream = DatabaseTimerPersistence.class.getClassLoader().getResourceAsStream("timer-sql.properties"); sql = new Properties(); try { sql.load(stream); } catch (IOException e) { throw new StartException(e); } finally { safeClose(stream); } // Update the create-auto-timer statements for DB specifics if (database != null) { switch (database) { case DB2: adjustCreateAutoTimerStatement("FROM SYSIBM.SysDummy1 "); break; case ORACLE: adjustCreateAutoTimerStatement("FROM DUAL "); break; } } final Iterator<Map.Entry<Object, Object>> iterator = sql.entrySet().iterator(); while (iterator.hasNext()) { final Map.Entry<Object, Object> next = iterator.next(); final String key = (String) next.getKey(); final int dot = key.lastIndexOf('.'); // this may be an entry for current database, or other database dialect if (dot > 0) { final String keySuffix = key.substring(dot + 1); // this is an entry for the current database dialect, // copy its value to the corresponding generic entry if (keySuffix.equals(database)) { final String keyWithoutSuffix = key.substring(0, dot); sql.setProperty(keyWithoutSuffix, (String) next.getValue()); } iterator.remove(); } } } /** * Check the connection MetaData and driver name to guess which database dialect * to use. */ private void investigateDialect() { Connection connection = null; if (database == null) { // no database dialect from configuration guessing from MetaData try { connection = dataSource.getConnection(); DatabaseMetaData metaData = connection.getMetaData(); String dbProduct = metaData.getDatabaseProductName(); database = identifyDialect(dbProduct); if (database == null) { EjbLogger.EJB3_TIMER_LOGGER.debug("Attempting to guess on driver name."); database = identifyDialect(metaData.getDriverName()); } } catch (Exception e) { EjbLogger.EJB3_TIMER_LOGGER.debug("Unable to read JDBC metadata.", e); } finally { safeClose(connection); } if (database != null) { EjbLogger.EJB3_TIMER_LOGGER.debugf("Detect database dialect as '%s'. If this is incorrect, please specify the correct dialect using the 'database' attribute in your configuration.", database); } } else { EjbLogger.EJB3_TIMER_LOGGER.debugf("Database dialect '%s' read from configuration, adjusting it to match the final database valid value.", database); database = identifyDialect(database); EjbLogger.EJB3_TIMER_LOGGER.debugf("New Database dialect is '%s'.", database); } if (database == null) { EjbLogger.EJB3_TIMER_LOGGER.databaseDialectNotConfiguredOrDetected(); } } /** * Use the given name and check for different database types to have a unified identifier for the dialect * * @param name A database name or even a driver name which should include the database name * @return A unified dialect identifier */ private String identifyDialect(String name) { String unified = null; if (name != null) { name = name.toLowerCase(Locale.ROOT); if (name.contains(POSTGRES) || name.contains(ENTERPRISEDB)) { unified = POSTGRESQL; } else if (name.contains(MYSQL)) { unified = MYSQL; } else if (name.contains(MARIADB)) { unified = MARIADB; } else if (name.contains(DB2)) { unified = DB2; } else if (name.contains(HSQL) || name.contains(HYPERSONIC)) { unified = HSQL; } else if (name.contains(H2)) { unified = H2; } else if (name.contains(ORACLE)) { unified = ORACLE; } else if (MSSQL_PATTERN.matcher(name).find()) { unified = MSSQL; } else if (name.contains(SYBASE) || name.contains(JCONNECT)) { unified = SYBASE; } else { EjbLogger.EJB3_TIMER_LOGGER.unknownDatabaseName(name); } } EjbLogger.EJB3_TIMER_LOGGER.debugf("Check dialect for '%s', result is '%s'", name, unified); return unified; } private void adjustCreateAutoTimerStatement(final String fromDummyTable) { final String insertQuery = sql.getProperty(CREATE_AUTO_TIMER); final int whereNotExists = insertQuery.indexOf("WHERE NOT EXISTS"); if (whereNotExists > 0) { StringBuilder sb = new StringBuilder(insertQuery.substring(0, whereNotExists)); sb.append(fromDummyTable).append("WHERE NOT EXISTS").append(insertQuery.substring(whereNotExists + 16)); sql.setProperty(CREATE_AUTO_TIMER, sb.toString()); } } /** * Checks whether the database transaction configuration is appropriate * and create the timer table if necessary. */ private void checkDatabase() { String loadTimer = sql.getProperty(LOAD_TIMER); Connection connection = null; Statement statement = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { //test for the existence of the table by running the load timer query connection = dataSource.getConnection(); if (connection.getTransactionIsolation() < Connection.TRANSACTION_READ_COMMITTED) { EjbLogger.EJB3_TIMER_LOGGER.wrongTransactionIsolationConfiguredForTimer(); } preparedStatement = connection.prepareStatement(loadTimer); preparedStatement.setString(1, "NON-EXISTENT"); preparedStatement.setString(2, "NON-EXISTENT"); preparedStatement.setString(3, "NON-EXISTENT"); resultSet = preparedStatement.executeQuery(); } catch (SQLException e) { //the query failed, assume it is because the table does not exist if (connection != null) { try { String createTable = sql.getProperty(CREATE_TABLE); String[] statements = createTable.split(";"); statement = connection.createStatement(); for (final String sql : statements) { statement.addBatch(sql); } statement.executeBatch(); } catch (SQLException e1) { EjbLogger.EJB3_TIMER_LOGGER.couldNotCreateTable(e1); } } else { EjbLogger.EJB3_TIMER_LOGGER.couldNotCreateTable(e); } } finally { safeClose(resultSet); safeClose(preparedStatement); safeClose(statement); safeClose(connection); } } /** * Loads a timer from database by its id and timed object id. * * @param timedObjectId the timed object id for the timer * @param timerId the timer id * @param timerService the active timer service * @return the timer loaded from database; null if nothing can be loaded */ public TimerImpl loadTimer(final String timedObjectId, final String timerId, final TimerServiceImpl timerService) { String loadTimer = sql.getProperty(LOAD_TIMER); Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; TimerImpl timer = null; try { connection = dataSource.getConnection(); preparedStatement = connection.prepareStatement(loadTimer); preparedStatement.setString(1, timedObjectId); preparedStatement.setString(2, timerId); preparedStatement.setString(3, partition); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { Holder holder = timerFromResult(resultSet, timerService, timerId, null); if (holder != null) { timer = holder.timer; } } } catch (SQLException e) { EjbLogger.EJB3_TIMER_LOGGER.failToRestoreTimersForObjectId(timerId, e); } finally { safeClose(resultSet); safeClose(preparedStatement); safeClose(connection); } return timer; } @Override public void addTimer(final TimerImpl timerEntity) { String timedObjectId = timerEntity.getTimedObjectId(); synchronized (this) { if(!knownTimerIds.containsKey(timedObjectId)) { throw EjbLogger.EJB3_TIMER_LOGGER.timerCannotBeAdded(timerEntity); } } if (timerEntity.isAutoTimer()) { addAutoTimer((CalendarTimer) timerEntity); return; } String createTimer = sql.getProperty(CREATE_TIMER); Connection connection = null; PreparedStatement statement = null; try { synchronized (this) { knownTimerIds.get(timerEntity.getTimedObjectId()).add(timerEntity.getId()); } connection = dataSource.getConnection(); statement = connection.prepareStatement(createTimer); statementParameters(timerEntity, statement); statement.execute(); if (isClearTimerInfoCache(timerEntity)) { timerEntity.setCachedTimerInfo(Object.class); EjbLogger.EJB3_TIMER_LOGGER.debugf("Cleared timer info for timer: %s", timerEntity.getId()); } } catch (SQLException e) { timerEntity.setCachedTimerInfo(null); throw new RuntimeException(e); } finally { safeClose(statement); safeClose(connection); } } @Override public void persistTimer(final TimerImpl timerEntity) { Connection connection = null; PreparedStatement statement = null; try { connection = dataSource.getConnection(); if (timerEntity.getState() == TimerState.CANCELED || timerEntity.getState() == TimerState.EXPIRED) { String deleteTimer = sql.getProperty(DELETE_TIMER); statement = connection.prepareStatement(deleteTimer); statement.setString(1, timerEntity.getTimedObjectId()); statement.setString(2, timerEntity.getId()); statement.setString(3, partition); statement.execute(); synchronized (this) { knownTimerIds.get(timerEntity.getTimedObjectId()).remove(timerEntity.getId()); } } else { synchronized (this) { knownTimerIds.get(timerEntity.getTimedObjectId()).add(timerEntity.getId()); } String updateTimer = sql.getProperty(UPDATE_TIMER); statement = connection.prepareStatement(updateTimer); statement.setTimestamp(1, timestamp(timerEntity.getNextExpiration())); statement.setTimestamp(2, timestamp(timerEntity.getPreviousRun())); statement.setString(3, timerEntity.getState().name()); setNodeName(timerEntity.getState(), statement, 4); // WHERE CLAUSE statement.setString(5, timerEntity.getTimedObjectId()); statement.setString(6, timerEntity.getId()); statement.setString(7, partition); statement.setString(8, nodeName); // only persist if this node or empty statement.execute(); } } catch (SQLException e) { throw new RuntimeException(e); } finally { safeClose(statement); safeClose(connection); } } @Override public boolean shouldRun(TimerImpl timer) { final ContextTransactionManager tm = ContextTransactionManager.getInstance(); if (!allowExecution) { //timers never execute on this node return false; } String loadTimer = sql.getProperty(UPDATE_RUNNING); Connection connection = null; PreparedStatement statement = null; try { tm.begin(); try { connection = dataSource.getConnection(); statement = connection.prepareStatement(loadTimer); statement.setString(1, TimerState.IN_TIMEOUT.name()); setNodeName(TimerState.IN_TIMEOUT, statement, 2); statement.setString(3, timer.getId()); statement.setString(4, TimerState.IN_TIMEOUT.name()); statement.setString(5, TimerState.RETRY_TIMEOUT.name()); if (timer.getNextExpiration() == null) { statement.setTimestamp(6, null); } else { statement.setTimestamp(6, timestamp(timer.getNextExpiration())); } } catch (SQLException e) { try { tm.rollback(); } catch (Exception ee){ EjbLogger.EJB3_TIMER_LOGGER.timerUpdateFailedAndRollbackNotPossible(ee); } // fix for WFLY-10130 EjbLogger.EJB3_TIMER_LOGGER.exceptionCheckingIfTimerShouldRun(timer, e); return false; } int affected = statement.executeUpdate(); tm.commit(); return affected == 1; } catch (SQLException | SystemException | SecurityException | IllegalStateException | RollbackException | HeuristicMixedException | HeuristicRollbackException e) { // failed to update the DB try { tm.rollback(); } catch (IllegalStateException | SecurityException | SystemException rbe) { EjbLogger.EJB3_TIMER_LOGGER.timerUpdateFailedAndRollbackNotPossible(rbe); } EjbLogger.EJB3_TIMER_LOGGER.debugf(e, "Timer %s not running due to exception ", timer); return false; } catch (NotSupportedException e) { // happen from tm.begin, no rollback necessary EjbLogger.EJB3_TIMER_LOGGER.timerNotRunning(e, timer); return false; } finally { safeClose(statement); safeClose(connection); } } @Override public synchronized void timerUndeployed(final String timedObjectId) { knownTimerIds.remove(timedObjectId); } @Override public synchronized void timerDeployed(String timedObjectId) { knownTimerIds.put(timedObjectId, new HashSet<>()); } @Override public List<TimerImpl> loadActiveTimers(final String timedObjectId, final TimerServiceImpl timerService) { if(!knownTimerIds.containsKey(timedObjectId)) { // if the timedObjectId has not being deployed EjbLogger.EJB3_TIMER_LOGGER.timerNotDeployed(timedObjectId); return Collections.emptyList(); } String loadTimer = sql.getProperty(LOAD_ALL_TIMERS); Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; try { connection = dataSource.getConnection(); statement = connection.prepareStatement(loadTimer); statement.setString(1, timedObjectId); statement.setString(2, partition); resultSet = statement.executeQuery(); final List<Holder> timers = new ArrayList<>(); while (resultSet.next()) { String timerId = null; try { timerId = resultSet.getString(1); final Holder timerImpl = timerFromResult(resultSet, timerService, timerId, null); if (timerImpl != null) { timers.add(timerImpl); } else { final String deleteTimer = sql.getProperty(DELETE_TIMER); try (PreparedStatement deleteStatement = connection.prepareStatement(deleteTimer)) { deleteStatement.setString(1, resultSet.getString(2)); deleteStatement.setString(2, timerId); deleteStatement.setString(3, partition); deleteStatement.execute(); } } } catch (Exception e) { EjbLogger.EJB3_TIMER_LOGGER.timerReinstatementFailed(resultSet.getString(2), timerId, e); } } synchronized (this) { // ids should be always be not null Set<String> ids = knownTimerIds.get(timedObjectId); for (Holder timer : timers) { ids.add(timer.timer.getId()); } for(Holder timer : timers) { if(timer.requiresReset) { TimerImpl ret = timer.timer; EjbLogger.DEPLOYMENT_LOGGER.loadedPersistentTimerInTimeout(ret.getId(), ret.getTimedObjectId()); if(ret.getNextExpiration() == null) { ret.setTimerState(TimerState.CANCELED, null); persistTimer(ret); } else { ret.setTimerState(TimerState.ACTIVE, null); persistTimer(ret); } } } } List<TimerImpl> ret = new ArrayList<>(); for(Holder timer : timers) { ret.add(timer.timer); } return ret; } catch (SQLException e) { throw new RuntimeException(e); } finally { safeClose(resultSet); safeClose(statement); safeClose(connection); } } @Override public Closeable registerChangeListener(final String timedObjectId, TimerChangeListener listener) { changeListeners.put(timedObjectId, listener); return new Closeable() { @Override public void close() throws IOException { changeListeners.remove(timedObjectId); } }; } public void refreshTimers() { refreshTask.run(); } /** * Obtains a {@link Holder} from a row in {@code ResultSet}. * Caller of this method must get the timer id from the {@code ResultSet} * in advance and pass in as param {@code timerId}. * Caller of this method may get the timer state from the {@code ResultSet} * in advance and pass in as param {@code timerState}. * * @param resultSet the {@code ResultSet} from database query * @param timerService the associated {@code TimerServiceImpl} * @param timerId the timer id, not null * @param timerState the timer state from current row in the {@code ResultSet}, may be null * @return the {@code Holder} instance containing the timer from current {@code ResultSet} row * @throws SQLException on errors reading from {@code ResultSet} */ private Holder timerFromResult(final ResultSet resultSet, final TimerServiceImpl timerService, final String timerId, final TimerState timerState) throws SQLException { boolean calendarTimer = resultSet.getBoolean(24); final String nodeName = resultSet.getString(25); boolean requiresReset = false; TimerImpl.Builder builder; if (calendarTimer) { CalendarTimer.Builder cb = CalendarTimer.builder(); builder = cb; //set calendar timer specifics first final ScheduleExpression scheduleExpression = new ScheduleExpression(); scheduleExpression.second(resultSet.getString(10)); scheduleExpression.minute(resultSet.getString(11)); scheduleExpression.hour(resultSet.getString(12)); scheduleExpression.dayOfWeek(resultSet.getString(13)); scheduleExpression.dayOfMonth(resultSet.getString(14)); scheduleExpression.month(resultSet.getString(15)); scheduleExpression.year(resultSet.getString(16)); scheduleExpression.start(stringAsSchedulerDate(resultSet.getString(17), timerId)); scheduleExpression.end(stringAsSchedulerDate(resultSet.getString(18), timerId)); scheduleExpression.timezone(resultSet.getString(19)); cb.setScheduleExpression(scheduleExpression); cb.setAutoTimer(resultSet.getBoolean(20)); final String clazz = resultSet.getString(21); final String methodName = resultSet.getString(22); if (methodName != null) { final String paramString = resultSet.getString(23); final String[] params = paramString == null || paramString.isEmpty() ? EMPTY_STRING_ARRAY : TIMER_PARAM_1_ARRAY; final Method timeoutMethod = CalendarTimer.getTimeoutMethod(new TimeoutMethod(clazz, methodName, params), timerService.getInvoker().getClassLoader()); if (timeoutMethod == null) { EjbLogger.EJB3_TIMER_LOGGER.timerReinstatementFailed(resultSet.getString(2), timerId, new NoSuchMethodException()); return null; } cb.setTimeoutMethod(timeoutMethod); } } else { builder = TimerImpl.builder(); } builder.setId(timerId); builder.setTimedObjectId(resultSet.getString(2)); builder.setInitialDate(resultSet.getTimestamp(3)); builder.setRepeatInterval(resultSet.getLong(4)); builder.setNextDate(resultSet.getTimestamp(5)); builder.setPreviousRun(resultSet.getTimestamp(6)); // builder.setPrimaryKey(deSerialize(resultSet.getString(7))); builder.setInfo((Serializable) deSerialize(resultSet.getString(8))); builder.setTimerState(timerState != null ? timerState : TimerState.valueOf(resultSet.getString(9))); builder.setPersistent(true); TimerImpl ret = builder.build(timerService); if (isClearTimerInfoCache(ret)) { ret.setCachedTimerInfo(Object.class); EjbLogger.EJB3_TIMER_LOGGER.debugf("Cleared timer info for timer: %s", timerId); } if (nodeName != null && nodeName.equals(this.nodeName) && (ret.getState() == TimerState.IN_TIMEOUT || ret.getState() == TimerState.RETRY_TIMEOUT)) { requiresReset = true; } return new Holder(ret, requiresReset); } private void statementParameters(final TimerImpl timerEntity, final PreparedStatement statement) throws SQLException { statement.setString(1, timerEntity.getId()); statement.setString(2, timerEntity.getTimedObjectId()); statement.setTimestamp(3, timestamp(timerEntity.getInitialExpiration())); statement.setLong(4, timerEntity.getInterval()); statement.setTimestamp(5, timestamp(timerEntity.getNextExpiration())); statement.setTimestamp(6, timestamp(timerEntity.getPreviousRun())); statement.setString(7, null); statement.setString(8, serialize(timerEntity.getTimerInfo())); statement.setString(9, timerEntity.getState().name()); if (timerEntity instanceof CalendarTimer) { final CalendarTimer c = (CalendarTimer) timerEntity; statement.setString(10, c.getScheduleExpression().getSecond()); statement.setString(11, c.getScheduleExpression().getMinute()); statement.setString(12, c.getScheduleExpression().getHour()); statement.setString(13, c.getScheduleExpression().getDayOfWeek()); statement.setString(14, c.getScheduleExpression().getDayOfMonth()); statement.setString(15, c.getScheduleExpression().getMonth()); statement.setString(16, c.getScheduleExpression().getYear()); // WFLY-9054: Oracle ojdbc6/7 store a timestamp as '06-JUL-17 01.54.00.269000000 PM' // but expect 'YYYY-MM-DD hh:mm:ss.fffffffff' as all other DB statement.setString(17, schedulerDateAsString(c.getScheduleExpression().getStart())); statement.setString(18, schedulerDateAsString(c.getScheduleExpression().getEnd())); statement.setString(19, c.getScheduleExpression().getTimezone()); statement.setBoolean(20, false); statement.setString(21, null); statement.setString(22, null); statement.setString(23, null); statement.setBoolean(24, true); } else { statement.setString(10, null); statement.setString(11, null); statement.setString(12, null); statement.setString(13, null); statement.setString(14, null); statement.setString(15, null); statement.setString(16, null); statement.setTimestamp(17, null); statement.setTimestamp(18, null); statement.setString(19, null); statement.setBoolean(20, false); statement.setString(21, null); statement.setString(22, null); statement.setString(23, null); statement.setBoolean(24, false); } statement.setString(25, partition); setNodeName(timerEntity.getState(), statement, 26); } private void addAutoTimer(final CalendarTimer timer) { String createTimer = sql.getProperty(CREATE_AUTO_TIMER); Connection connection = null; PreparedStatement statement = null; final String timerInfoString = serialize(timer.getTimerInfo()); final Method timeoutMethod = timer.getTimeoutMethod(); final String timeoutMethodClassName = timeoutMethod.getDeclaringClass().getName(); final String timeoutMethodParam = timeoutMethod.getParameterCount() == 0 ? null : TIMER_PARAM_1; final ScheduleExpression exp = timer.getScheduleExpression(); final String startDateString = schedulerDateAsString(exp.getStart()); final String endDateString = schedulerDateAsString(exp.getEnd()); try { connection = dataSource.getConnection(); statement = connection.prepareStatement(createTimer); // insert values statement.setString(1, timer.getId()); statement.setString(2, timer.getTimedObjectId()); statement.setTimestamp(3, timestamp(timer.getNextExpiration())); statement.setString(4, timerInfoString); statement.setString(5, exp.getSecond()); statement.setString(6, exp.getMinute()); statement.setString(7, exp.getHour()); statement.setString(8, exp.getDayOfWeek()); statement.setString(9, exp.getDayOfMonth()); statement.setString(10, exp.getMonth()); statement.setString(11, exp.getYear()); statement.setString(12, startDateString); statement.setString(13, endDateString); statement.setString(14, exp.getTimezone()); statement.setBoolean(15, true); statement.setString(16, timeoutMethodClassName); statement.setString(17, timeoutMethod.getName()); statement.setString(18, timeoutMethodParam); statement.setBoolean(19, true); statement.setString(20, partition); // where clause statement.setString(21, timer.getTimedObjectId()); statement.setString(22, exp.getSecond()); statement.setString(23, exp.getMinute()); statement.setString(24, exp.getHour()); statement.setString(25, exp.getDayOfWeek()); statement.setString(26, exp.getDayOfMonth()); statement.setString(27, exp.getMonth()); statement.setString(28, exp.getYear()); statement.setString(29, startDateString); statement.setString(30, startDateString); statement.setString(31, endDateString); statement.setString(32, endDateString); statement.setString(33, exp.getTimezone()); statement.setString(34, exp.getTimezone()); statement.setString(35, timeoutMethodClassName); statement.setString(36, timeoutMethod.getName()); statement.setString(37, timeoutMethodParam); statement.setString(38, timeoutMethodParam); statement.setString(39, partition); int affectedRows = statement.executeUpdate(); if (affectedRows < 1) { timer.setTimerState(TimerState.CANCELED, null); } else { synchronized (this) { knownTimerIds.get(timer.getTimedObjectId()).add(timer.getId()); } } } catch (SQLException e) { throw new RuntimeException(e); } finally { safeClose(statement); safeClose(connection); } } /** * Retrieves the timer info from the timer database. * * @param timer the timer whose info to be retrieved * @return the timer info from database; null if {@code SQLException} */ public Serializable getPersistedTimerInfo(final TimerImpl timer) { String getTimerInfo = sql.getProperty(GET_TIMER_INFO); Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; Serializable result = null; try { connection = dataSource.getConnection(); statement = connection.prepareStatement(getTimerInfo); statement.setString(1, timer.getTimedObjectId()); statement.setString(2, timer.getId()); resultSet = statement.executeQuery(); if (resultSet.next()) { result = (Serializable) deSerialize(resultSet.getString(1)); } } catch (SQLException e) { EjbLogger.EJB3_TIMER_LOGGER.failedToRetrieveTimerInfo(timer, e); } finally { safeClose(resultSet); safeClose(statement); safeClose(connection); } return result; } /** * Determines if the cached info in the timer should be cleared. * @param timer the timer to check * @return true if the cached info in the timer should be cleared; otherwise false */ private boolean isClearTimerInfoCache(final TimerImpl timer) { if (timer.isAutoTimer()) { return false; } final Serializable info = timer.getCachedTimerInfo(); if (info == null || info instanceof String || info instanceof Number || info instanceof Enum || info instanceof java.util.Date || info instanceof Character) { return false; } final Date nextExpiration = timer.getNextExpiration(); if (nextExpiration == null) { return true; } final long howLongTillExpiry = nextExpiration.getTime() - System.currentTimeMillis(); if (howLongTillExpiry <= clearTimerInfoCacheBeyond) { return false; } return true; } private String serialize(final Serializable serializable) { if (serializable == null) { return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); try { final Marshaller marshaller = factory.createMarshaller(configuration); marshaller.start(new OutputStreamByteOutput(out)); marshaller.writeObject(serializable); marshaller.finish(); out.flush(); } catch (IOException e) { throw new RuntimeException(e); } return Base64.getEncoder().encodeToString(out.toByteArray()); } public Object deSerialize(final String data) throws SQLException { if (data == null) { return null; } InputStream in = new ByteArrayInputStream(Base64.getDecoder().decode(data)); try { final Unmarshaller unmarshaller = factory.createUnmarshaller(configuration); unmarshaller.start(new InputStreamByteInput(in)); Object ret = unmarshaller.readObject(); unmarshaller.finish(); return ret; } catch (IOException | ClassNotFoundException e) { throw new RuntimeException(e); } finally { safeClose(in); } } private String schedulerDateAsString(final Date date) { if (date == null) { return null; } return new SimpleDateFormat(SCHEDULER_DATE_FORMAT).format(date); } /** Convert the stored date-string from database back to Date */ private Date stringAsSchedulerDate(final String date, final String timerId) { if (date == null) { return null; } try { return new SimpleDateFormat(SCHEDULER_DATE_FORMAT).parse(date); } catch (ParseException e) { EjbLogger.EJB3_TIMER_LOGGER.scheduleExpressionDateFromTimerPersistenceInvalid(timerId, e.getMessage()); return null; } } private Timestamp timestamp(final Date date) { if (date == null) { return null; } long time = date.getTime(); if(database != null && (database.equals("mysql") || database.equals("postgresql"))) { // truncate the milliseconds because MySQL 5.6.4+ and MariaDB 5.3+ do the same // and querying with a Timestamp containing milliseconds doesn't match the rows // with such truncated DATETIMEs // truncate the milliseconds because postgres timestamp does not reliably support milliseconds time -= time % 1000; } return new Timestamp(time); } /** * Set the node name for persistence if the state is IN_TIMEOUT or RETRY_TIMEOUT to show which node is current active for the timer. */ private void setNodeName(final TimerState timerState, PreparedStatement statement, int paramIndex) throws SQLException { if(timerState == TimerState.IN_TIMEOUT || timerState == TimerState.RETRY_TIMEOUT) { statement.setString(paramIndex, nodeName); } else { statement.setNull(paramIndex, Types.VARCHAR); } } private class RefreshTask extends TimerTask { private volatile AtomicBoolean running = new AtomicBoolean(); @Override public void run() { if (running.compareAndSet(false, true)) { try { Set<String> timedObjects; synchronized (DatabaseTimerPersistence.this) { timedObjects = new HashSet<>(knownTimerIds.keySet()); } for (String timedObjectId : timedObjects) { TimerChangeListener listener = changeListeners.get(timedObjectId); if (listener == null) { continue; } final Set<String> existing; synchronized (DatabaseTimerPersistence.this) { existing = new HashSet<>(knownTimerIds.get(timedObjectId)); } String loadTimer = sql.getProperty(LOAD_ALL_TIMERS); Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; try { connection = dataSource.getConnection(); statement = connection.prepareStatement(loadTimer); statement.setString(1, timedObjectId); statement.setString(2, partition); resultSet = statement.executeQuery(); final TimerServiceImpl timerService = listener.getTimerService(); while (resultSet.next()) { String id = null; try { id = resultSet.getString(1); if (!existing.remove(id)) { final Holder holder = timerFromResult(resultSet, timerService, id, null); if(holder != null) { synchronized (DatabaseTimerPersistence.this) { knownTimerIds.get(timedObjectId).add(id); listener.timerAdded(holder.timer); } } } else { TimerImpl oldTimer = timerService.getTimer(id); // if it is already in memory but it is not in sync we have a problem // remove and add -> the probable cause is db glitch boolean invalidMemoryTimer = oldTimer != null && !TimerState.CREATED_ACTIVE_IN_TIMEOUT_RETRY_TIMEOUT.contains(oldTimer.getState()); // if timers memory - db are in non intersect subsets of valid/invalid states. we put them in sync if (invalidMemoryTimer) { TimerState dbTimerState = TimerState.valueOf(resultSet.getString(9)); boolean validDBTimer = TimerState.CREATED_ACTIVE_IN_TIMEOUT_RETRY_TIMEOUT.contains(dbTimerState); if (validDBTimer) { final Holder holder = timerFromResult(resultSet, timerService, id, dbTimerState); if (holder != null) { synchronized (DatabaseTimerPersistence.this) { knownTimerIds.get(timedObjectId).add(id); listener.timerSync(oldTimer, holder.timer); } } } } } } catch (Exception e) { EjbLogger.EJB3_TIMER_LOGGER.timerReinstatementFailed(resultSet.getString(2), id, e); } } synchronized (DatabaseTimerPersistence.this) { Set<String> timers = knownTimerIds.get(timedObjectId); for (String timer : existing) { TimerImpl timer1 = timerService.getTimer(timer); if (timer1 != null && timer1.getState() != TimerState.CREATED) { timers.remove(timer); listener.timerRemoved(timer); } } } } catch (SQLException e) { EjbLogger.EJB3_TIMER_LOGGER.failedToRefreshTimers(timedObjectId); } finally { safeClose(resultSet); safeClose(statement); safeClose(connection); } } } finally { running.set(false); } } } } static final class Holder { final TimerImpl timer; final boolean requiresReset; Holder(TimerImpl timer, boolean requiresReset) { this.timer = timer; this.requiresReset = requiresReset; } } }
51,719
43.740484
209
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/persistence/filestore/EjbTimerXmlParser_1_0.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.persistence.filestore; import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.CALENDAR_TIMER; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.DECLARING_CLASS; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.INFO; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.INITIAL_DATE; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.NAME; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.NEXT_DATE; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.PARAMETER; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.PREVIOUS_RUN; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.REPEAT_INTERVAL; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.SCHEDULE_EXPR_DAY_OF_MONTH; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.SCHEDULE_EXPR_DAY_OF_WEEK; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.SCHEDULE_EXPR_END_DATE; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.SCHEDULE_EXPR_HOUR; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.SCHEDULE_EXPR_MINUTE; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.SCHEDULE_EXPR_MONTH; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.SCHEDULE_EXPR_SECOND; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.SCHEDULE_EXPR_START_DATE; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.SCHEDULE_EXPR_TIMEZONE; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.SCHEDULE_EXPR_YEAR; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.TIMED_OBJECT_ID; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.TIMEOUT_METHOD; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.TIMER; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.TIMER_ID; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.TIMER_STATE; import static org.jboss.as.ejb3.timerservice.persistence.filestore.EjbTimerXmlPersister.TYPE; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import jakarta.ejb.ScheduleExpression; import javax.xml.stream.XMLStreamException; import org.jboss.as.controller.parsing.ParseUtils; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.timerservice.CalendarTimer; import org.jboss.as.ejb3.timerservice.TimerImpl; import org.jboss.as.ejb3.timerservice.TimerServiceImpl; import org.jboss.as.ejb3.timerservice.TimerState; import org.jboss.as.ejb3.timerservice.persistence.TimeoutMethod; import org.jboss.marshalling.ByteBufferInput; import org.jboss.marshalling.MarshallerFactory; import org.jboss.marshalling.MarshallingConfiguration; import org.jboss.marshalling.Unmarshaller; import org.jboss.staxmapper.XMLElementReader; import org.jboss.staxmapper.XMLExtendedStreamReader; /** * Parser for persistent Jakarta Enterprise Beans timers that are stored in XML. * * @author Stuart Douglas */ public class EjbTimerXmlParser_1_0 implements XMLElementReader<List<TimerImpl>> { public static final String NAMESPACE = "urn:jboss:wildfly:ejb-timers:1.0"; private final TimerServiceImpl timerService; private final MarshallerFactory factory; private final MarshallingConfiguration configuration; private final ClassLoader classLoader; public EjbTimerXmlParser_1_0(TimerServiceImpl timerService, MarshallerFactory factory, MarshallingConfiguration configuration, ClassLoader classLoader) { this.timerService = timerService; this.factory = factory; this.configuration = configuration; this.classLoader = classLoader; } @Override public void readElement(XMLExtendedStreamReader reader, List<TimerImpl> timers) throws XMLStreamException { while (reader.hasNext()) { switch (reader.nextTag()) { case END_ELEMENT: { return; } case START_ELEMENT: { switch (reader.getName().getLocalPart()) { case TIMER: this.parseTimer(reader, timers); break; case CALENDAR_TIMER: this.parseCalendarTimer(reader, timers); break; default: throw ParseUtils.unexpectedElement(reader); } break; } } } } private void parseTimer(XMLExtendedStreamReader reader, List<TimerImpl> timers) throws XMLStreamException { LoadableElements loadableElements = new LoadableElements(); TimerImpl.Builder builder = TimerImpl.builder(); builder.setPersistent(true); final Set<String> required = new HashSet<>(Arrays.asList(new String[]{TIMED_OBJECT_ID, TIMER_ID, INITIAL_DATE, REPEAT_INTERVAL, TIMER_STATE})); for (int i = 0; i < reader.getAttributeCount(); ++i) { String attr = reader.getAttributeValue(i); String attrName = reader.getAttributeLocalName(i); required.remove(attrName); boolean handled = handleCommonAttributes(builder, reader, i); if (!handled) { switch (attrName) { case REPEAT_INTERVAL: builder.setRepeatInterval(Long.parseLong(attr)); break; default: throw ParseUtils.unexpectedAttribute(reader, i); } } } if (!required.isEmpty()) { throw ParseUtils.missingRequired(reader, required); } while (reader.hasNext()) { switch (reader.nextTag()) { case END_ELEMENT: { try { if (loadableElements.info != null) { builder.setInfo((Serializable) deserialize(loadableElements.info)); } timers.add(builder.build(timerService)); } catch (Exception e) { EjbLogger.EJB3_TIMER_LOGGER.timerReinstatementFailed(builder.getTimedObjectId(), builder.getId(), e); } return; } case START_ELEMENT: { boolean handled = handleCommonElements(reader, loadableElements); if (!handled) { throw ParseUtils.unexpectedElement(reader); } break; } } } } private Object deserialize(final String info) throws IOException, ClassNotFoundException { byte[] data = Base64.getDecoder().decode(info.trim()); try (final Unmarshaller unmarshaller = factory.createUnmarshaller(configuration)) { unmarshaller.start(new ByteBufferInput(ByteBuffer.wrap(data))); return unmarshaller.readObject(); } } private boolean handleCommonElements(XMLExtendedStreamReader reader, LoadableElements builder) throws XMLStreamException { boolean handled = false; switch (reader.getName().getLocalPart()) { case INFO: { builder.info = reader.getElementText(); handled = true; break; } } return handled; } private void parseCalendarTimer(XMLExtendedStreamReader reader, List<TimerImpl> timers) throws XMLStreamException { LoadableElements loadableElements = new LoadableElements(); CalendarTimer.Builder builder = CalendarTimer.builder(); builder.setAutoTimer(false).setPersistent(true); final Set<String> required = new HashSet<>(Arrays.asList(new String[]{ TIMED_OBJECT_ID, TIMER_ID, TIMER_STATE, SCHEDULE_EXPR_SECOND, SCHEDULE_EXPR_MINUTE, SCHEDULE_EXPR_HOUR, SCHEDULE_EXPR_DAY_OF_WEEK, SCHEDULE_EXPR_DAY_OF_MONTH, SCHEDULE_EXPR_MONTH, SCHEDULE_EXPR_YEAR})); final ScheduleExpression scheduleExpression = new ScheduleExpression(); for (int i = 0; i < reader.getAttributeCount(); ++i) { String attr = reader.getAttributeValue(i); String attrName = reader.getAttributeLocalName(i); required.remove(attrName); boolean handled = handleCommonAttributes(builder, reader, i); if (!handled) { switch (attrName) { case SCHEDULE_EXPR_SECOND: scheduleExpression.second(attr); break; case SCHEDULE_EXPR_MINUTE: scheduleExpression.minute(attr); break; case SCHEDULE_EXPR_HOUR: scheduleExpression.hour(attr); break; case SCHEDULE_EXPR_DAY_OF_WEEK: scheduleExpression.dayOfWeek(attr); break; case SCHEDULE_EXPR_DAY_OF_MONTH: scheduleExpression.dayOfMonth(attr); break; case SCHEDULE_EXPR_MONTH: scheduleExpression.month(attr); break; case SCHEDULE_EXPR_YEAR: scheduleExpression.year(attr); break; case SCHEDULE_EXPR_START_DATE: scheduleExpression.start(new Date(Long.parseLong(attr))); break; case SCHEDULE_EXPR_END_DATE: scheduleExpression.end(new Date(Long.parseLong(attr))); break; case SCHEDULE_EXPR_TIMEZONE: scheduleExpression.timezone(attr); break; default: throw ParseUtils.unexpectedAttribute(reader, i); } } } if (!required.isEmpty()) { throw ParseUtils.missingRequired(reader, required); } builder.setScheduleExpression(scheduleExpression); while (reader.hasNext()) { switch (reader.nextTag()) { case END_ELEMENT: { try { if (loadableElements.info != null) { builder.setInfo((Serializable) deserialize(loadableElements.info)); } if (loadableElements.methodName != null) { Method timeoutMethod = CalendarTimer.getTimeoutMethod(new TimeoutMethod(loadableElements.className, loadableElements.methodName, loadableElements.params.toArray(new String[loadableElements.params.size()])), classLoader); if(timeoutMethod != null) { builder.setTimeoutMethod(timeoutMethod); timers.add(builder.build(timerService)); } else { builder.setId("deleted-timer"); timers.add(builder.build(timerService)); EjbLogger.EJB3_TIMER_LOGGER.timerReinstatementFailed(builder.getTimedObjectId(), builder.getId(), null); } } else { timers.add(builder.build(timerService)); } } catch (Exception e) { EjbLogger.EJB3_TIMER_LOGGER.timerReinstatementFailed(builder.getTimedObjectId(), builder.getId(), e); } return; } case START_ELEMENT: { boolean handled = handleCommonElements(reader, loadableElements); if (!handled) { switch (reader.getName().getLocalPart()) { case TIMEOUT_METHOD: { builder.setAutoTimer(true); parseTimeoutMethod(reader, loadableElements); break; } default: throw ParseUtils.unexpectedElement(reader); } } } } } } private void parseTimeoutMethod(XMLExtendedStreamReader reader, LoadableElements loadableElements) throws XMLStreamException { final Set<String> required = new HashSet<>(Arrays.asList(new String[]{DECLARING_CLASS, NAME})); for (int i = 0; i < reader.getAttributeCount(); ++i) { String attr = reader.getAttributeValue(i); String attrName = reader.getAttributeLocalName(i); required.remove(attrName); switch (attrName) { case DECLARING_CLASS: loadableElements.className = attr; break; case NAME: loadableElements.methodName = attr; break; default: throw ParseUtils.unexpectedAttribute(reader, i); } } if (!required.isEmpty()) { throw ParseUtils.missingRequired(reader, required); } while (reader.hasNext()) { switch (reader.nextTag()) { case END_ELEMENT: { return; } case START_ELEMENT: { switch (reader.getName().getLocalPart()) { case PARAMETER: { handleParam(reader, loadableElements); break; } default: throw ParseUtils.unexpectedElement(reader); } } } } } private void handleParam(XMLExtendedStreamReader reader, LoadableElements loadableElements) throws XMLStreamException { final Set<String> required = new HashSet<>(Arrays.asList(new String[]{TYPE})); for (int i = 0; i < reader.getAttributeCount(); ++i) { String attr = reader.getAttributeValue(i); String attrName = reader.getAttributeLocalName(i); required.remove(attrName); switch (attrName) { case TYPE: loadableElements.params.add(attr); break; default: throw ParseUtils.unexpectedAttribute(reader, i); } } if (!required.isEmpty()) { throw ParseUtils.missingRequired(reader, required); } while (reader.hasNext()) { switch (reader.nextTag()) { case END_ELEMENT: { return; } case START_ELEMENT: { throw ParseUtils.unexpectedElement(reader); } } } } private boolean handleCommonAttributes(TimerImpl.Builder builder, XMLExtendedStreamReader reader, int i) { boolean handled = true; String attr = reader.getAttributeValue(i); switch (reader.getAttributeLocalName(i)) { case TIMED_OBJECT_ID: builder.setTimedObjectId(attr); break; case TIMER_ID: builder.setId(attr); break; case INITIAL_DATE: builder.setInitialDate(new Date(Long.parseLong(attr))); break; case NEXT_DATE: builder.setNextDate(new Date(Long.parseLong(attr))); break; case TIMER_STATE: builder.setTimerState(TimerState.valueOf(attr)); break; case PREVIOUS_RUN: builder.setPreviousRun(new Date(Long.parseLong(attr))); break; default: handled = false; } return handled; } private static class LoadableElements { String info; String className; String methodName; final List<String> params = new ArrayList<>(); } }
18,499
43.258373
248
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/persistence/filestore/FileTimerPersistence.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.persistence.filestore; import static java.security.AccessController.doPrivileged; import static org.jboss.as.ejb3.logging.EjbLogger.EJB3_TIMER_LOGGER; import static org.jboss.as.ejb3.timerservice.TimerServiceImpl.safeClose; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilePermission; import java.io.IOException; import java.lang.reflect.Constructor; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Consumer; import java.util.function.Supplier; import jakarta.transaction.Status; import jakarta.transaction.Synchronization; import jakarta.transaction.SystemException; import jakarta.transaction.TransactionSynchronizationRegistry; import javax.xml.namespace.QName; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import org.jboss.as.controller.services.path.PathManager; import org.jboss.as.ejb3.component.stateful.CurrentSynchronizationCallback; import org.jboss.as.ejb3.timerservice.TimerImpl; import org.jboss.as.ejb3.timerservice.TimerServiceImpl; import org.jboss.as.ejb3.timerservice.TimerState; import org.jboss.as.ejb3.timerservice.persistence.TimerPersistence; import org.jboss.marshalling.MarshallerFactory; import org.jboss.marshalling.MarshallingConfiguration; import org.jboss.marshalling.ModularClassResolver; import org.jboss.marshalling.river.RiverMarshallerFactory; import org.jboss.modules.ModuleLoader; import org.jboss.msc.Service; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StopContext; import org.jboss.staxmapper.XMLExtendedStreamWriter; import org.jboss.staxmapper.XMLMapper; import org.wildfly.security.manager.WildFlySecurityManager; import org.wildfly.transaction.client.ContextTransactionManager; /** * File based persistent timer store. * <p/> * TODO: this is fairly hackey at the moment, it should be registered as an XA resource to support proper XA semantics * * @author Stuart Douglas */ public class FileTimerPersistence implements TimerPersistence, Service { private static final FilePermission FILE_PERMISSION = new FilePermission("<<ALL FILES>>", "read,write,delete"); private static final XMLInputFactory INPUT_FACTORY = XMLInputFactory.newInstance(); private final boolean createIfNotExists; private MarshallerFactory factory; private MarshallingConfiguration configuration; private final Consumer<FileTimerPersistence> consumer; private final Supplier<TransactionSynchronizationRegistry> txnRegistrySupplier; private final Supplier<ModuleLoader> moduleLoaderSupplier; private final Supplier<PathManager> pathManagerSupplier; private final String path; private final String pathRelativeTo; private File baseDir; private PathManager.Callback.Handle callbackHandle; private final ConcurrentMap<String, Lock> locks = new ConcurrentHashMap<String, Lock>(); private final ConcurrentMap<String, String> directories = new ConcurrentHashMap<String, String>(); public FileTimerPersistence(final Consumer<FileTimerPersistence> consumer, final Supplier<TransactionSynchronizationRegistry> txnRegistrySupplier, final Supplier<ModuleLoader> moduleLoaderSupplier, final Supplier<PathManager> pathManagerSupplier, final boolean createIfNotExists, final String path, final String pathRelativeTo) { this.consumer = consumer; this.txnRegistrySupplier = txnRegistrySupplier; this.moduleLoaderSupplier = moduleLoaderSupplier; this.pathManagerSupplier = pathManagerSupplier; final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(FILE_PERMISSION); } this.createIfNotExists = createIfNotExists; this.path = path; this.pathRelativeTo = pathRelativeTo; } @Override public void start(final StartContext context) { consumer.accept(this); if (WildFlySecurityManager.isChecking()) { WildFlySecurityManager.doUnchecked(new PrivilegedAction<Void>() { public Void run() { doStart(); return null; } }); } else { doStart(); } } private void doStart() { final RiverMarshallerFactory factory = new RiverMarshallerFactory(); final MarshallingConfiguration configuration = new MarshallingConfiguration(); configuration.setClassResolver(ModularClassResolver.getInstance(moduleLoaderSupplier.get())); configuration.setVersion(3); this.configuration = configuration; this.factory = factory; if (pathRelativeTo != null) { callbackHandle = pathManagerSupplier.get().registerCallback(pathRelativeTo, PathManager.ReloadServerCallback.create(), PathManager.Event.UPDATED, PathManager.Event.REMOVED); } baseDir = new File(pathManagerSupplier.get().resolveRelativePathEntry(path, pathRelativeTo)); if (!baseDir.exists()) { if (createIfNotExists) { if (!baseDir.mkdirs()) { throw EJB3_TIMER_LOGGER.failToCreateTimerFileStoreDir(baseDir); } } else { throw EJB3_TIMER_LOGGER.timerFileStoreDirNotExist(baseDir); } } if (!baseDir.isDirectory()) { throw EJB3_TIMER_LOGGER.invalidTimerFileStoreDir(baseDir); } } @Override public void stop(final StopContext context) { consumer.accept(null); locks.clear(); directories.clear(); if (callbackHandle != null) { callbackHandle.remove(); } factory = null; configuration = null; } @Override public void addTimer(final TimerImpl TimerImpl) { if(WildFlySecurityManager.isChecking()) { WildFlySecurityManager.doUnchecked(new PrivilegedAction<Object>() { @Override public Object run() { persistTimer(TimerImpl, true); return null; } }); } else { persistTimer(TimerImpl, true); } } @Override public void persistTimer(final TimerImpl TimerImpl) { if(WildFlySecurityManager.isChecking()) { WildFlySecurityManager.doUnchecked(new PrivilegedAction<Object>() { @Override public Object run() { persistTimer(TimerImpl, false); return null; } }); } else { persistTimer(TimerImpl, false); } } @Override public boolean shouldRun(TimerImpl timer) { return true; } private void persistTimer(final TimerImpl timer, boolean newTimer) { final Lock lock = getLock(timer.getTimedObjectId()); try { final int status = ContextTransactionManager.getInstance().getStatus(); if (status == Status.STATUS_MARKED_ROLLBACK || status == Status.STATUS_ROLLEDBACK || status == Status.STATUS_ROLLING_BACK) { //no need to persist anyway return; } lock.lock(); if (status == Status.STATUS_NO_TRANSACTION || status == Status.STATUS_UNKNOWN || isBeforeCompletion() || status == Status.STATUS_COMMITTED) { Map<String, TimerImpl> map = getTimers(timer.getTimedObjectId(), timer.getTimerService()); if (timer.getState() == TimerState.CANCELED || timer.getState() == TimerState.EXPIRED) { map.remove(timer.getId()); writeFile(timer); } else if (newTimer || map.containsKey(timer.getId())) { //if it is not a new timer and is not in the map then it has //been removed by another thread. map.put(timer.getId(), timer); writeFile(timer); } } else { final String key = timerTransactionKey(timer); Object existing = txnRegistrySupplier.get().getResource(key); //check is there is already a persist sync for this timer if (existing == null) { txnRegistrySupplier.get().registerInterposedSynchronization(new PersistTransactionSynchronization(lock, key, newTimer)); } //update the most recent version of the timer to be persisted txnRegistrySupplier.get().putResource(key, timer); } } catch (SystemException e) { throw new RuntimeException(e); } finally { lock.unlock(); } } private String timerTransactionKey(final TimerImpl TimerImpl) { return "org.jboss.as.ejb3.timerTransactionKey." + TimerImpl.getId(); } @Override public void timerUndeployed(final String timedObjectId) { final Lock lock = getLock(timedObjectId); try { lock.lock(); locks.remove(timedObjectId); directories.remove(timedObjectId); } finally { lock.unlock(); } } private boolean isBeforeCompletion() { final CurrentSynchronizationCallback.CallbackType type = CurrentSynchronizationCallback.get(); if (type != null) { return type == CurrentSynchronizationCallback.CallbackType.BEFORE_COMPLETION; } return false; } @Override public List<TimerImpl> loadActiveTimers(final String timedObjectId, final TimerServiceImpl timerService) { final Lock lock = getLock(timedObjectId); try { lock.lock(); final Map<String, TimerImpl> timers = getTimers(timedObjectId, timerService); final List<TimerImpl> entities = new ArrayList<TimerImpl>(); for (Map.Entry<String, TimerImpl> entry : timers.entrySet()) { entities.add(mostRecentEntityVersion(entry.getValue())); } return entities; } finally { lock.unlock(); } } @Override public Closeable registerChangeListener(String timedObjectId, TimerChangeListener listener) { return new Closeable() { @Override public void close() throws IOException { } }; } /** * Returns either the loaded entity or the most recent version of the entity that has * been persisted in this transaction. */ private TimerImpl mostRecentEntityVersion(final TimerImpl timerImpl) { try { final int status = ContextTransactionManager.getInstance().getStatus(); if (status == Status.STATUS_UNKNOWN || status == Status.STATUS_NO_TRANSACTION) { return timerImpl; } final String key = timerTransactionKey(timerImpl); TimerImpl existing = (TimerImpl) txnRegistrySupplier.get().getResource(key); return existing != null ? existing : timerImpl; } catch (SystemException e) { throw new RuntimeException(e); } } private Lock getLock(final String timedObjectId) { Lock lock = locks.get(timedObjectId); if (lock == null) { final Lock addedLock = new ReentrantLock(); lock = locks.putIfAbsent(timedObjectId, addedLock); if (lock == null) { lock = addedLock; } } return lock; } /** * Gets the timer map, loading from the persistent store if necessary. Should be called under lock * * @param timedObjectId The timed object id * @return The timers for the object */ private Map<String, TimerImpl> getTimers(final String timedObjectId, final TimerServiceImpl timerService) { return loadTimersFromFile(timedObjectId, timerService); } private Map<String, TimerImpl> loadTimersFromFile(String timedObjectId, TimerServiceImpl timerService) { Map<String, TimerImpl> timers = new HashMap<>(); String directory = getDirectory(timedObjectId); timers.putAll(LegacyFileStore.loadTimersFromFile(timedObjectId, timerService, directory, factory, configuration)); for(Map.Entry<String, TimerImpl> entry : timers.entrySet()) { writeFile(entry.getValue()); //write legacy timers into the new format //the legacy code handling code will write a marker file, to make sure that the old timers will not be loaded on next restart. } final File file = new File(directory); if (!file.exists()) { //no timers exist yet return timers; } else if (!file.isDirectory()) { EJB3_TIMER_LOGGER.failToRestoreTimers(file); return timers; } final XMLMapper mapper = createMapper(timerService); for (File timerFile : file.listFiles()) { if (!timerFile.getName().endsWith(".xml")) { continue; } FileInputStream in = null; try { in = new FileInputStream(timerFile); final XMLInputFactory inputFactory = INPUT_FACTORY; setIfSupported(inputFactory, XMLInputFactory.IS_VALIDATING, Boolean.FALSE); setIfSupported(inputFactory, XMLInputFactory.SUPPORT_DTD, Boolean.FALSE); final XMLStreamReader streamReader = inputFactory.createXMLStreamReader(in); try { List<TimerImpl> timerList = new ArrayList<>(); mapper.parseDocument(timerList, streamReader); for (TimerImpl timer : timerList) { if (timer.getId().equals("deleted-timer")) { timerFile.delete(); break; } timers.put(timer.getId(), timer); } } finally { safeClose(in); } } catch (Exception e) { EJB3_TIMER_LOGGER.failToRestoreTimersFromFile(timerFile, e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { EJB3_TIMER_LOGGER.failToCloseFile(e); } } } } return timers; } private XMLMapper createMapper(TimerServiceImpl timerService) { final XMLMapper mapper = XMLMapper.Factory.create(); mapper.registerRootElement(new QName(EjbTimerXmlParser_1_0.NAMESPACE, EjbTimerXmlPersister.TIMERS), new EjbTimerXmlParser_1_0(timerService, factory, configuration, timerService.getInvoker().getClassLoader())); return mapper; } private File fileName(String timedObjectId, String timerId) { return new File(getDirectory(timedObjectId) + File.separator + timerId.replace(File.separator, "-") + ".xml"); } /** * Gets the directory for a given timed object, making sure it exists. * * @param timedObjectId The timed object * @return The directory */ private String getDirectory(String timedObjectId) { String dirName = directories.get(timedObjectId); if (dirName == null) { dirName = baseDir.getAbsolutePath() + File.separator + timedObjectId.replace(File.separator, "-"); File file = new File(dirName); if (!file.exists() && !file.mkdirs()) { EJB3_TIMER_LOGGER.failToCreateDirectoryForPersistTimers(file); } directories.put(timedObjectId, dirName); } return dirName; } private final class PersistTransactionSynchronization implements Synchronization { private final String transactionKey; private final Lock lock; private final boolean newTimer; private volatile TimerImpl timer; public PersistTransactionSynchronization(final Lock lock, final String transactionKey, final boolean newTimer) { this.lock = lock; this.transactionKey = transactionKey; this.newTimer = newTimer; } @Override public void beforeCompletion() { //get the latest version of the entity timer = (TimerImpl) txnRegistrySupplier.get().getResource(transactionKey); if (timer == null) { return; } } @Override public void afterCompletion(final int status) { doPrivileged(new PrivilegedAction<Void>() { public Void run() { if (timer == null) { return null; } try { lock.lock(); if (status == Status.STATUS_COMMITTED) { final Map<String, TimerImpl> map = getTimers(timer.getTimedObjectId(), timer.getTimerService()); if (timer.getState() == TimerState.CANCELED || timer.getState() == TimerState.EXPIRED) { map.remove(timer.getId()); } else { if (newTimer || map.containsKey(timer.getId())) { //if an existing timer is not in the map it has been cancelled by another thread map.put(timer.getId(), timer); } } writeFile(timer); } } finally { lock.unlock(); } return null; } }); } } private void writeFile(TimerImpl timer) { final File file = fileName(timer.getTimedObjectId(), timer.getId()); //if the timer is expired or cancelled delete the file if (timer.getState() == TimerState.CANCELED || timer.getState() == TimerState.EXPIRED) { if (file.exists()) { file.delete(); } return; } try { FileOutputStream out = new FileOutputStream(file); try { XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out); XMLMapper mapper = createMapper(timer.getTimerService()); mapper.deparseDocument(new EjbTimerXmlPersister(factory, configuration), Collections.singletonList(timer), writer); writer.flush(); writer.close(); } finally { safeClose(out); } } catch (Exception e) { throw new RuntimeException(e); } } private void setIfSupported(final XMLInputFactory inputFactory, final String property, final Object value) { if (inputFactory.isPropertySupported(property)) { inputFactory.setProperty(property, value); } } public static XMLExtendedStreamWriter create(XMLStreamWriter writer) throws Exception { // Use reflection to access package protected class FormattingXMLStreamWriter // TODO: at some point the staxmapper API could be enhanced to make this unnecessary Class<?> clazz = Class.forName("org.jboss.staxmapper.FormattingXMLStreamWriter"); Constructor<?> ctr = clazz.getConstructor(XMLStreamWriter.class); ctr.setAccessible(true); return (XMLExtendedStreamWriter) ctr.newInstance(new Object[]{writer}); } }
21,442
39.155431
217
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/persistence/filestore/LegacyFileStore.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.persistence.filestore; import static org.jboss.as.ejb3.logging.EjbLogger.EJB3_TIMER_LOGGER; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Date; import java.util.HashMap; import java.util.Map; import jakarta.ejb.ScheduleExpression; import org.jboss.as.ejb3.timerservice.CalendarTimer; import org.jboss.as.ejb3.timerservice.TimerImpl; import org.jboss.as.ejb3.timerservice.TimerServiceImpl; import org.jboss.as.ejb3.timerservice.persistence.CalendarTimerEntity; import org.jboss.as.ejb3.timerservice.persistence.TimerEntity; import org.jboss.marshalling.InputStreamByteInput; import org.jboss.marshalling.MarshallerFactory; import org.jboss.marshalling.MarshallingConfiguration; import org.jboss.marshalling.Unmarshaller; import org.jboss.vfs.VFSUtils; /** * Contains the code needed to load timers from the legacy persistent format. * * The old format was based on jboss marshalling, and as such it was almost impossible to maintain * compatibility, as class changes to the serialized classes would result in old persistent timers * being unreadable. * * This class will load old style timers, and then create a marker file to indicate to the system * that these timers have already been read. * * @author Stuart Douglas */ public class LegacyFileStore { public static final String MIGRATION_MARKER = "migrated-to-xml.marker"; static Map<String, TimerImpl> loadTimersFromFile(final String timedObjectId, final TimerServiceImpl timerService, String directory, MarshallerFactory factory, MarshallingConfiguration configuration) { final Map<String, TimerImpl> timers = new HashMap<String, TimerImpl>(); Unmarshaller unmarshaller = null; try { final File file = new File(directory); if (!file.exists()) { //no timers exist yet return timers; } else if (!file.isDirectory()) { EJB3_TIMER_LOGGER.failToRestoreTimers(file); return timers; } File marker = new File(file, MIGRATION_MARKER); if (marker.exists()) { return timers; } unmarshaller = factory.createUnmarshaller(configuration); for (File timerFile : file.listFiles()) { if(timerFile.getName().endsWith(".xml")) { continue; } FileInputStream in = null; try { in = new FileInputStream(timerFile); unmarshaller.start(new InputStreamByteInput(in)); final TimerEntity entity = unmarshaller.readObject(TimerEntity.class); //we load the legacy timer entity class, and turn it into a timer state TimerImpl.Builder builder; if (entity instanceof CalendarTimerEntity) { CalendarTimerEntity c = (CalendarTimerEntity) entity; final ScheduleExpression scheduleExpression = new ScheduleExpression(); scheduleExpression.second(c.getSecond()) .minute(c.getMinute()) .hour(c.getHour()) .dayOfWeek(c.getDayOfWeek()) .dayOfMonth(c.getDayOfMonth()) .month(c.getMonth()) .year(c.getYear()) .start(c.getStartDate()) .end(c.getEndDate()) .timezone(c.getTimezone()); builder = CalendarTimer.builder() .setScheduleExpression(scheduleExpression) .setAutoTimer(c.isAutoTimer()) .setTimeoutMethod(CalendarTimer.getTimeoutMethod(c.getTimeoutMethod(), timerService.getInvoker().getClassLoader())); } else { builder = TimerImpl.builder(); } builder.setId(entity.getId()) .setTimedObjectId(entity.getTimedObjectId()) .setInitialDate(entity.getInitialDate()) .setRepeatInterval(entity.getInterval()) .setNextDate(entity.getNextDate()) .setPreviousRun(entity.getPreviousRun()) .setInfo(entity.getInfo()) .setTimerState(entity.getTimerState()) .setPersistent(true); timers.put(entity.getId(), builder.build(timerService)); unmarshaller.finish(); } catch (Exception e) { EJB3_TIMER_LOGGER.failToRestoreTimersFromFile(timerFile, e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { EJB3_TIMER_LOGGER.failToCloseFile(e); } } } } if (!timers.isEmpty()) { Files.write(marker.toPath(), new Date().toString().getBytes(StandardCharsets.UTF_8)); } } catch (Exception e) { EJB3_TIMER_LOGGER.failToRestoreTimersForObjectId(timedObjectId, e); } finally { VFSUtils.safeClose(unmarshaller); } return timers; } }
6,748
43.111111
204
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/persistence/filestore/EjbTimerXmlPersister.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.persistence.filestore; import java.io.ByteArrayOutputStream; import java.util.Base64; import java.util.List; import javax.xml.stream.XMLStreamException; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.timerservice.CalendarTimer; import org.jboss.as.ejb3.timerservice.TimerImpl; import org.jboss.marshalling.Marshaller; import org.jboss.marshalling.MarshallerFactory; import org.jboss.marshalling.MarshallingConfiguration; import org.jboss.marshalling.OutputStreamByteOutput; import org.jboss.staxmapper.XMLElementWriter; import org.jboss.staxmapper.XMLExtendedStreamWriter; /** * @author Stuart Douglas */ public class EjbTimerXmlPersister implements XMLElementWriter<List<TimerImpl>> { static final String TIMERS = "timers"; static final String TIMER = "timer"; static final String CALENDAR_TIMER = "calendar-timer"; static final String INFO = "info"; static final String TIMED_OBJECT_ID = "timed-object-id"; static final String TIMER_ID = "timer-id"; static final String INITIAL_DATE = "initial-date"; static final String REPEAT_INTERVAL = "repeat-interval"; static final String NEXT_DATE = "next-date"; static final String PREVIOUS_RUN = "previous-run"; static final String TIMER_STATE = "timer-state"; static final String TIMEOUT_METHOD = "timeout-method"; static final String SCHEDULE_EXPR_SECOND = "schedule-expr-second"; static final String SCHEDULE_EXPR_MINUTE = "schedule-expr-minute"; static final String SCHEDULE_EXPR_HOUR = "schedule-expr-hour"; static final String SCHEDULE_EXPR_DAY_OF_WEEK = "schedule-expr-day-of-week"; static final String SCHEDULE_EXPR_DAY_OF_MONTH = "schedule-expr-day-of-month"; static final String SCHEDULE_EXPR_MONTH = "schedule-expr-month"; static final String SCHEDULE_EXPR_YEAR = "schedule-expr-year"; static final String SCHEDULE_EXPR_START_DATE = "schedule-expr-start-date"; static final String SCHEDULE_EXPR_END_DATE = "schedule-expr-end-date"; static final String SCHEDULE_EXPR_TIMEZONE = "schedule-expr-timezone"; static final String PARAMETER = "parameter"; static final String DECLARING_CLASS = "declaring-class"; static final String NAME = "name"; static final String TYPE = "type"; private final MarshallerFactory factory; private final MarshallingConfiguration configuration; public EjbTimerXmlPersister(MarshallerFactory factory, MarshallingConfiguration configuration) { this.factory = factory; this.configuration = configuration; } @Override public void writeContent(XMLExtendedStreamWriter writer, List<TimerImpl> timers) throws XMLStreamException { writer.writeStartDocument(); writer.writeStartElement(TIMERS); writer.writeDefaultNamespace(EjbTimerXmlParser_1_0.NAMESPACE); for (TimerImpl timer : timers) { if (timer instanceof CalendarTimer) { writeCalendarTimer(writer, (CalendarTimer) timer); } else { writeTimer(writer, timer); } } writer.writeEndElement(); writer.writeEndDocument(); } private void writeCalendarTimer(XMLExtendedStreamWriter writer, CalendarTimer timer) throws XMLStreamException { String info = null; if (timer.getInfo() != null) { try (final Marshaller marshaller = factory.createMarshaller(configuration)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); marshaller.start(new OutputStreamByteOutput(out)); marshaller.writeObject(timer.getInfo()); marshaller.flush(); info = Base64.getEncoder().encodeToString(out.toByteArray()); } catch (Exception e) { EjbLogger.EJB3_TIMER_LOGGER.failedToPersistTimer(timer, e); return; } } writer.writeStartElement(CALENDAR_TIMER); writer.writeAttribute(TIMED_OBJECT_ID, timer.getTimedObjectId()); writer.writeAttribute(TIMER_ID, timer.getId()); if (timer.getInitialExpiration() != null) { writer.writeAttribute(INITIAL_DATE, Long.toString(timer.getInitialExpiration().getTime())); } if(timer.getNextExpiration() != null) { writer.writeAttribute(NEXT_DATE, Long.toString(timer.getNextExpiration().getTime())); } writer.writeAttribute(TIMER_STATE, timer.getState().name()); writer.writeAttribute(SCHEDULE_EXPR_SECOND, timer.getScheduleExpression().getSecond()); writer.writeAttribute(SCHEDULE_EXPR_MINUTE, timer.getScheduleExpression().getMinute()); writer.writeAttribute(SCHEDULE_EXPR_HOUR, timer.getScheduleExpression().getHour()); writer.writeAttribute(SCHEDULE_EXPR_DAY_OF_WEEK, timer.getScheduleExpression().getDayOfWeek()); writer.writeAttribute(SCHEDULE_EXPR_DAY_OF_MONTH, timer.getScheduleExpression().getDayOfMonth()); writer.writeAttribute(SCHEDULE_EXPR_MONTH, timer.getScheduleExpression().getMonth()); writer.writeAttribute(SCHEDULE_EXPR_YEAR, timer.getScheduleExpression().getYear()); if (timer.getScheduleExpression().getStart() != null) { writer.writeAttribute(SCHEDULE_EXPR_START_DATE, Long.toString(timer.getScheduleExpression().getStart().getTime())); } if (timer.getScheduleExpression().getEnd() != null) { writer.writeAttribute(SCHEDULE_EXPR_END_DATE, Long.toString(timer.getScheduleExpression().getEnd().getTime())); } if (timer.getScheduleExpression().getTimezone() != null) { writer.writeAttribute(SCHEDULE_EXPR_TIMEZONE, timer.getScheduleExpression().getTimezone()); } if (info != null) { writer.writeStartElement(INFO); writer.writeCharacters(info); writer.writeEndElement(); } if (timer.isAutoTimer()) { writer.writeStartElement(TIMEOUT_METHOD); writer.writeAttribute(DECLARING_CLASS, timer.getTimeoutMethod().getDeclaringClass().getName()); writer.writeAttribute(NAME, timer.getTimeoutMethod().getName()); for (Class<?> param : timer.getTimeoutMethod().getParameterTypes()) { writer.writeStartElement(PARAMETER); writer.writeAttribute(TYPE, param.getName()); writer.writeEndElement(); } writer.writeEndElement(); } writer.writeEndElement(); } private void writeTimer(XMLExtendedStreamWriter writer, TimerImpl timer) throws XMLStreamException { String info = null; if (timer.getInfo() != null) { try (final Marshaller marshaller = factory.createMarshaller(configuration)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); marshaller.start(new OutputStreamByteOutput(out)); marshaller.writeObject(timer.getInfo()); marshaller.flush(); info = Base64.getEncoder().encodeToString(out.toByteArray()); } catch (Exception e) { EjbLogger.EJB3_TIMER_LOGGER.failedToPersistTimer(timer, e); return; } } writer.writeStartElement(TIMER); writer.writeAttribute(TIMED_OBJECT_ID, timer.getTimedObjectId()); writer.writeAttribute(TIMER_ID, timer.getId()); writer.writeAttribute(INITIAL_DATE, Long.toString(timer.getInitialExpiration().getTime())); writer.writeAttribute(REPEAT_INTERVAL, Long.toString(timer.getInterval())); if(timer.getNextExpiration() != null) { writer.writeAttribute(NEXT_DATE, Long.toString(timer.getNextExpiration().getTime())); } writer.writeAttribute(TIMER_STATE, timer.getState().name()); if (info != null) { writer.writeStartElement(INFO); writer.writeCharacters(info); writer.writeEndElement(); } writer.writeEndElement(); } }
9,096
46.878947
127
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/distributable/DistributableTimerServiceFactoryServiceConfigurator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.distributable; import java.util.UUID; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import jakarta.ejb.TimerConfig; import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; import org.jboss.as.controller.capability.CapabilityServiceSupport; import org.jboss.as.ejb3.component.EJBComponent; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerService; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerServiceFactory; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerServiceFactoryConfiguration; import org.jboss.as.ejb3.timerservice.spi.TimedObjectInvoker; import org.jboss.as.ejb3.timerservice.spi.TimedObjectInvokerFactory; import org.jboss.as.ejb3.timerservice.spi.TimerListener; import org.jboss.as.ejb3.timerservice.spi.TimerServiceRegistry; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.ee.UUIDFactory; import org.wildfly.clustering.ejb.timer.TimeoutListener; import org.wildfly.clustering.ejb.timer.TimerManagementProvider; import org.wildfly.clustering.ejb.timer.TimerManager; import org.wildfly.clustering.ejb.timer.TimerManagerConfiguration; import org.wildfly.clustering.ejb.timer.TimerManagerFactory; import org.wildfly.clustering.ejb.timer.TimerManagerFactoryConfiguration; import org.wildfly.clustering.ejb.timer.TimerRegistry; import org.wildfly.clustering.ejb.timer.TimerServiceConfiguration; import org.wildfly.clustering.service.ServiceConfigurator; import org.wildfly.clustering.service.ServiceSupplierDependency; import org.wildfly.clustering.service.SimpleServiceNameProvider; import org.wildfly.clustering.service.SupplierDependency; /** * Configures a service that provides a distributed {@link TimerServiceFactory}. * @author Paul Ferraro */ public class DistributableTimerServiceFactoryServiceConfigurator extends SimpleServiceNameProvider implements CapabilityServiceConfigurator, TimerManagerFactoryConfiguration<UUID>, ManagedTimerServiceFactory, TimerRegistry<UUID> { enum TimerIdentifierFactory implements Supplier<java.util.UUID>, Function<String, UUID> { INSTANCE; @Override public java.util.UUID get() { return UUIDFactory.INSECURE.get(); } @Override public java.util.UUID apply(String id) { return java.util.UUID.fromString(id); } } private volatile SupplierDependency<TimerManagerFactory<UUID, Batch>> factory; private final TimerServiceRegistry registry; private final TimedObjectInvokerFactory invokerFactory; private final TimerServiceConfiguration configuration; private final TimerListener registrar; private final TimerManagementProvider provider; private final Predicate<TimerConfig> filter; private volatile ServiceConfigurator configurator; public DistributableTimerServiceFactoryServiceConfigurator(ServiceName name, ManagedTimerServiceFactoryConfiguration factoryConfiguration, TimerServiceConfiguration configuration, TimerManagementProvider provider, Predicate<TimerConfig> filter) { super(name); this.registry = factoryConfiguration.getTimerServiceRegistry(); this.invokerFactory = factoryConfiguration.getInvokerFactory(); this.configuration = configuration; this.registrar = factoryConfiguration.getTimerListener(); this.provider = provider; this.filter = filter; } @Override public ManagedTimerService createTimerService(EJBComponent component) { TimedObjectInvoker invoker = this.invokerFactory.createInvoker(component); TimerServiceRegistry registry = this.registry; TimerListener timerListener = this.registrar; Predicate<TimerConfig> filter = this.filter; TimerServiceConfiguration configuration = this.configuration; TimerSynchronizationFactory<UUID> synchronizationFactory = new DistributableTimerSynchronizationFactory<>(this.getRegistry()); TimeoutListener<UUID, Batch> timeoutListener = new DistributableTimeoutListener<>(invoker, synchronizationFactory); TimerManager<UUID, Batch> manager = this.factory.get().createTimerManager(new TimerManagerConfiguration<UUID, Batch>() { @Override public TimerServiceConfiguration getTimerServiceConfiguration() { return configuration; } @Override public Supplier<UUID> getIdentifierFactory() { return DistributableTimerServiceFactoryServiceConfigurator.this.getIdentifierFactory(); } @Override public TimerRegistry<UUID> getRegistry() { return DistributableTimerServiceFactoryServiceConfigurator.this.getRegistry(); } @Override public boolean isPersistent() { return DistributableTimerServiceFactoryServiceConfigurator.this.isPersistent(); } @Override public TimeoutListener<UUID, Batch> getListener() { return timeoutListener; } }); DistributableTimerServiceConfiguration<UUID> serviceConfiguration = new DistributableTimerServiceConfiguration<>() { @Override public TimedObjectInvoker getInvoker() { return invoker; } @Override public TimerServiceRegistry getTimerServiceRegistry() { return registry; } @Override public TimerListener getTimerListener() { return timerListener; } @Override public Function<String, UUID> getIdentifierParser() { return TimerIdentifierFactory.INSTANCE; } @Override public Predicate<TimerConfig> getTimerFilter() { return filter; } @Override public TimerSynchronizationFactory<UUID> getTimerSynchronizationFactory() { return synchronizationFactory; } }; return new DistributableTimerService<>(serviceConfiguration, manager); } @Override public ServiceConfigurator configure(CapabilityServiceSupport support) { this.configurator = this.provider.getTimerManagerFactoryServiceConfigurator(this).configure(support); this.factory = new ServiceSupplierDependency<>(this.configurator); return this; } @Override public ServiceBuilder<?> build(ServiceTarget target) { this.configurator.build(target).install(); ServiceName name = this.getServiceName(); ServiceBuilder<?> builder = target.addService(name); Consumer<ManagedTimerServiceFactory> factory = this.factory.register(builder).provides(name); return builder.setInstance(Service.newInstance(factory, this)).setInitialMode(ServiceController.Mode.ON_DEMAND); } @Override public Supplier<UUID> getIdentifierFactory() { return TimerIdentifierFactory.INSTANCE; } @Override public TimerRegistry<UUID> getRegistry() { return this; } @Override public void register(UUID id) { this.registrar.timerAdded(id.toString()); } @Override public void unregister(UUID id) { this.registrar.timerRemoved(id.toString()); } @Override public boolean isPersistent() { return this.filter.test(new TimerConfig(null, true)); } @Override public TimerServiceConfiguration getTimerServiceConfiguration() { return this.configuration; } }
8,915
39.162162
250
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/distributable/TimerSynchronizationFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.distributable; import java.util.function.Consumer; import jakarta.transaction.Synchronization; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.ee.Batcher; import org.wildfly.clustering.ejb.timer.Timer; /** * Factory for creating {@link Synchronization} instances for a distributed timer service. * Used to defer timer activation or cancellation until an active transaction is committed. * @author Paul Ferraro * @param <I> the timer identifier type */ public interface TimerSynchronizationFactory<I> { Synchronization createActivateSynchronization(Timer<I> timer, Batch batch, Batcher<Batch> batcher); Synchronization createCancelSynchronization(Timer<I> timer, Batch batch, Batcher<Batch> batcher); Consumer<Timer<I>> getActivateTask(); Consumer<Timer<I>> getCancelTask(); }
1,888
39.191489
103
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/distributable/DistributableTimerServiceConfiguration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.distributable; import java.util.function.Function; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerServiceConfiguration; /** * Encapsulates the configuration of a {@link DistributedTimerService}. * @author Paul Ferraro * @param <I> the timer identifier type */ public interface DistributableTimerServiceConfiguration<I> extends ManagedTimerServiceConfiguration { Function<String, I> getIdentifierParser(); TimerSynchronizationFactory<I> getTimerSynchronizationFactory(); }
1,558
38.974359
101
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/distributable/OOBTimer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.distributable; import java.io.Serializable; import java.util.Date; import java.util.Map; import java.util.function.Function; import jakarta.ejb.EJBException; import jakarta.ejb.ScheduleExpression; import jakarta.ejb.TimerHandle; import jakarta.transaction.Transaction; import org.jboss.as.ejb3.context.CurrentInvocationContext; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.timerservice.spi.ManagedTimer; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerService; import org.jboss.as.ejb3.timerservice.spi.TimedObjectInvoker; import org.jboss.invocation.InterceptorContext; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.ee.Batcher; import org.wildfly.clustering.ejb.timer.Timer; import org.wildfly.clustering.ejb.timer.TimerManager; import org.wildfly.common.function.ExceptionConsumer; /** * Timer implementation for use outside the context of a timeout event. * Ensures that all timer methods are invoked within the context of a batch. * @author Paul Ferraro * @param <I> the timer identifier type */ public class OOBTimer<I> implements ManagedTimer { private static final Function<ManagedTimer, TimerHandle> GET_HANDLE = ManagedTimer::getHandle; private static final Function<ManagedTimer, Serializable> GET_INFO = ManagedTimer::getInfo; private static final Function<ManagedTimer, Date> GET_NEXT_TIMEOUT = ManagedTimer::getNextTimeout; private static final Function<ManagedTimer, ScheduleExpression> GET_SCHEDULE = ManagedTimer::getSchedule; private static final Function<ManagedTimer, Long> GET_TIME_REMAINING = ManagedTimer::getTimeRemaining; private static final Function<ManagedTimer, Boolean> IS_ACTIVE = ManagedTimer::isActive; private static final Function<ManagedTimer, Boolean> IS_CALENDAR = ManagedTimer::isCalendarTimer; private static final Function<ManagedTimer, Boolean> IS_CANCELED = ManagedTimer::isCanceled; private static final Function<ManagedTimer, Boolean> IS_EXPIRED = ManagedTimer::isExpired; private static final Function<ManagedTimer, Boolean> IS_PERSISTENT = ManagedTimer::isPersistent; private static final ExceptionConsumer<ManagedTimer, EJBException> ACTIVATE = ManagedTimer::activate; private static final ExceptionConsumer<ManagedTimer, EJBException> CANCEL = ManagedTimer::cancel; private static final ExceptionConsumer<ManagedTimer, Exception> INVOKE = ManagedTimer::invoke; private static final ExceptionConsumer<ManagedTimer, EJBException> SUSPEND = ManagedTimer::suspend; private final TimerManager<I, Batch> manager; private final I id; private final TimedObjectInvoker invoker; private final TimerSynchronizationFactory<I> synchronizationFactory; public OOBTimer(TimerManager<I, Batch> manager, I id, TimedObjectInvoker invoker, TimerSynchronizationFactory<I> synchronizationFactory) { this.manager = manager; this.id = id; this.invoker = invoker; this.synchronizationFactory = synchronizationFactory; } @Override public void cancel() { this.invoke(CANCEL); } @Override public long getTimeRemaining() { return this.invoke(GET_TIME_REMAINING); } @Override public Date getNextTimeout() { return this.invoke(GET_NEXT_TIMEOUT); } @Override public ScheduleExpression getSchedule() { return this.invoke(GET_SCHEDULE); } @Override public boolean isPersistent() { return this.invoke(IS_PERSISTENT); } @Override public boolean isCalendarTimer() { return this.invoke(IS_CALENDAR); } @Override public Serializable getInfo() { return this.invoke(GET_INFO); } @Override public TimerHandle getHandle() { return this.invoke(GET_HANDLE); } @Override public String getId() { return this.id.toString(); } @Override public void activate() { this.invoke(ACTIVATE); } @Override public void suspend() { this.invoke(SUSPEND); } @Override public void invoke() throws Exception { this.invoke(INVOKE); } @Override public boolean isActive() { return this.invoke(IS_ACTIVE); } @Override public boolean isCanceled() { return this.invoke(IS_CANCELED); } @Override public boolean isExpired() { return this.invoke(IS_EXPIRED); } private <R> R invoke(Function<ManagedTimer, R> function) { InterceptorContext interceptorContext = CurrentInvocationContext.get(); ManagedTimer currentTimer = (interceptorContext != null) ? (ManagedTimer) interceptorContext.getTimer() : null; if ((currentTimer != null) && currentTimer.getId().equals(this.id.toString())) { return function.apply(currentTimer); } Transaction transaction = ManagedTimerService.getActiveTransaction(); @SuppressWarnings("unchecked") Map.Entry<Timer<I>, Batch> existing = (transaction != null) ? (Map.Entry<Timer<I>, Batch>) this.invoker.getComponent().getTransactionSynchronizationRegistry().getResource(this.id) : null; if (existing != null) { Timer<I> timer = existing.getKey(); Batch suspendedBatch = existing.getValue(); return function.apply(new DistributableTimer<>(this.manager, timer, suspendedBatch, this.invoker, this.synchronizationFactory)); } Batcher<Batch> batcher = this.manager.getBatcher(); try (Batch batch = batcher.createBatch()) { Timer<I> timer = this.manager.getTimer(this.id); if (timer == null) { throw EjbLogger.ROOT_LOGGER.timerWasCanceled(this.id.toString()); } Batch suspendedBatch = batcher.suspendBatch(); try { return function.apply(new DistributableTimer<>(this.manager, timer, suspendedBatch, this.invoker, this.synchronizationFactory)); } finally { batcher.resumeBatch(suspendedBatch); } } } private <E extends Exception> void invoke(ExceptionConsumer<ManagedTimer, E> consumer) throws E { InterceptorContext interceptorContext = CurrentInvocationContext.get(); ManagedTimer currentTimer = (interceptorContext != null) ? (ManagedTimer) interceptorContext.getTimer() : null; if ((currentTimer != null) && currentTimer.getId().equals(this.id.toString())) { consumer.accept(currentTimer); } else { Transaction transaction = ManagedTimerService.getActiveTransaction(); @SuppressWarnings("unchecked") Map.Entry<Timer<I>, Batch> existing = (transaction != null) ? (Map.Entry<Timer<I>, Batch>) this.invoker.getComponent().getTransactionSynchronizationRegistry().getResource(this.id) : null; if (existing != null) { Timer<I> timer = existing.getKey(); Batch suspendedBatch = existing.getValue(); consumer.accept(new DistributableTimer<>(this.manager, timer, suspendedBatch, this.invoker, this.synchronizationFactory)); } else { Batcher<Batch> batcher = this.manager.getBatcher(); try (Batch batch = batcher.createBatch()) { Timer<I> timer = this.manager.getTimer(this.id); if (timer == null) { throw EjbLogger.ROOT_LOGGER.timerWasCanceled(this.id.toString()); } Batch suspendedBatch = batcher.suspendBatch(); try { consumer.accept(new DistributableTimer<>(this.manager, timer, suspendedBatch, this.invoker, this.synchronizationFactory)); } finally { batcher.resumeBatch(suspendedBatch); } } } } } @Override public int hashCode() { return this.id.hashCode(); } @Override public boolean equals(Object object) { if (!(object instanceof ManagedTimer)) return false; return this.getId().equals(((ManagedTimer) object).getId()); } @Override public String toString() { return this.getId(); } }
9,336
38.731915
199
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/distributable/DefaultScheduleTimerOperationProvider.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.distributable; import java.time.Instant; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; import java.util.function.UnaryOperator; import jakarta.ejb.ScheduleExpression; import org.jboss.as.ejb3.timerservice.schedule.CalendarBasedTimeout; import org.jboss.as.ejb3.timerservice.schedule.attribute.DayOfMonth; import org.jboss.as.ejb3.timerservice.schedule.attribute.DayOfWeek; import org.jboss.as.ejb3.timerservice.schedule.attribute.Hour; import org.jboss.as.ejb3.timerservice.schedule.attribute.Minute; import org.jboss.as.ejb3.timerservice.schedule.attribute.Month; import org.jboss.as.ejb3.timerservice.schedule.attribute.Second; import org.jboss.as.ejb3.timerservice.schedule.attribute.Year; import org.kohsuke.MetaInfServices; import org.wildfly.clustering.ejb.timer.ImmutableScheduleExpression; import org.wildfly.clustering.ejb.timer.ScheduleTimerOperationProvider; /** * Provides a mechanism for calculating the next timeout for a given {@link ScheduleExpression}. * @author Paul Ferraro */ @MetaInfServices(ScheduleTimerOperationProvider.class) public class DefaultScheduleTimerOperationProvider implements ScheduleTimerOperationProvider { @Override public UnaryOperator<Instant> createOperator(ImmutableScheduleExpression expression) { return new DefaultScheduleTimerOperator(expression); } private static class DefaultScheduleTimerOperator implements UnaryOperator<Instant> { private final CalendarBasedTimeout timeout; private final Calendar first; DefaultScheduleTimerOperator(ImmutableScheduleExpression expression) { Instant start = expression.getStart(); Instant end = expression.getEnd(); this.timeout = new CalendarBasedTimeout(new Second(expression.getSecond()), new Minute(expression.getMinute()), new Hour(expression.getHour()), new DayOfMonth(expression.getDayOfMonth()), new Month(expression.getMonth()), new DayOfWeek(expression.getDayOfWeek()), new Year(expression.getYear()), TimeZone.getTimeZone(expression.getZone()), (start != null) ? Date.from(start) : null, (end != null) ? Date.from(end) : null); this.first = (start != null) ? this.timeout.getFirstTimeout() : this.timeout.getNextTimeout(); } @Override public Instant apply(Instant lastTimeout) { Calendar next = (lastTimeout != null) ? this.timeout.getNextTimeout(createCalendar(lastTimeout)) : this.first; return (next != null) ? next.toInstant() : null; } private static Calendar createCalendar(Instant instant) { Calendar calendar = new GregorianCalendar(); calendar.setTimeInMillis(instant.toEpochMilli()); return calendar; } } }
4,081
43.857143
122
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/distributable/DistributableTimer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.distributable; import java.io.Serializable; import java.lang.reflect.Method; import java.time.Duration; import java.time.Instant; import java.time.ZoneId; import java.util.Date; import java.util.Set; import java.util.function.Predicate; import jakarta.ejb.EJBException; import jakarta.ejb.NoMoreTimeoutsException; import jakarta.ejb.ScheduleExpression; import jakarta.ejb.TimerHandle; import jakarta.transaction.RollbackException; import jakarta.transaction.SystemException; import jakarta.transaction.Transaction; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.timerservice.TimerHandleImpl; import org.jboss.as.ejb3.timerservice.spi.ManagedTimer; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerService; import org.jboss.as.ejb3.timerservice.spi.TimedObjectInvoker; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.ee.BatchContext; import org.wildfly.clustering.ejb.timer.ImmutableScheduleExpression; import org.wildfly.clustering.ejb.timer.ScheduleTimerConfiguration; import org.wildfly.clustering.ejb.timer.Timer; import org.wildfly.clustering.ejb.timer.TimerManager; /** * Managed timer facade for a distributable EJB timer. * @author Paul Ferraro * @param <I> the timer identifier type */ public class DistributableTimer<I> implements ManagedTimer { private final TimerManager<I, Batch> manager; private final Timer<I> timer; private final Batch suspendedBatch; private final TimedObjectInvoker invoker; private final TimerSynchronizationFactory<I> synchronizationFactory; public DistributableTimer(TimerManager<I, Batch> manager, Timer<I> timer, Batch suspendedBatch, TimedObjectInvoker invoker, TimerSynchronizationFactory<I> synchronizationFactory) { this.manager = manager; this.timer = timer; this.suspendedBatch = suspendedBatch; this.invoker = invoker; this.synchronizationFactory = synchronizationFactory; } @Override public String getId() { return this.timer.getId().toString(); } @Override public boolean isActive() { return this.timer.isActive() && !this.timer.isCanceled(); } @Override public boolean isCanceled() { return this.timer.isCanceled(); } @Override public boolean isExpired() { return false; } @Override public void activate() { this.timer.activate(); } @Override public void suspend() { this.timer.suspend(); } @Override public void invoke() throws Exception { Predicate<Method> matcher = this.timer.getMetaData().getTimeoutMatcher(); if (matcher != null) { this.invoker.callTimeout(this, this.invoker.getComponent().getComponentDescription().getScheduleMethods().keySet().stream().filter(matcher).findFirst().get()); } else { this.invoker.callTimeout(this); } } @Override public void cancel() { this.validateInvocationContext(); Transaction transaction = ManagedTimerService.getActiveTransaction(); try (BatchContext context = this.manager.getBatcher().resumeBatch(this.suspendedBatch)) { if (transaction != null) { // Cancel timer on tx commit // Reactivate timer on tx rollback this.timer.suspend(); transaction.registerSynchronization(this.synchronizationFactory.createCancelSynchronization(this.timer, this.suspendedBatch, this.manager.getBatcher())); @SuppressWarnings("unchecked") Set<I> inactiveTimers = (Set<I>) this.invoker.getComponent().getTransactionSynchronizationRegistry().getResource(this.manager); if (inactiveTimers != null) { inactiveTimers.remove(this.timer.getId()); } } else { this.synchronizationFactory.getCancelTask().accept(this.timer); } } catch (RollbackException e) { // getActiveTransaction() would have returned null throw new IllegalStateException(e); } catch (SystemException e) { this.suspendedBatch.discard(); throw new EJBException(e); } } @Override public long getTimeRemaining() { this.validateInvocationContext(); try (BatchContext context = this.manager.getBatcher().resumeBatch(this.suspendedBatch)) { Instant next = this.timer.getMetaData().getNextTimeout(); if (next == null) { throw new NoMoreTimeoutsException(); } return Duration.between(Instant.now(), next).toMillis(); } } @Override public Date getNextTimeout() { this.validateInvocationContext(); try (BatchContext context = this.manager.getBatcher().resumeBatch(this.suspendedBatch)) { Instant next = this.timer.getMetaData().getNextTimeout(); if (next == null) { throw new NoMoreTimeoutsException(); } return Date.from(next); } } @Override public Serializable getInfo() { this.validateInvocationContext(); try (BatchContext context = this.manager.getBatcher().resumeBatch(this.suspendedBatch)) { return (Serializable) this.timer.getMetaData().getContext(); } } @Override public TimerHandle getHandle() { this.validateInvocationContext(); // for non-persistent timers throws an exception (mandated by EJB3 spec) if (!this.timer.getMetaData().isPersistent()) { throw EjbLogger.EJB3_TIMER_LOGGER.invalidTimerHandlersForPersistentTimers("EJB3.1 Spec 18.2.6"); } try (BatchContext context = this.manager.getBatcher().resumeBatch(this.suspendedBatch)) { // Create handle w/OOB timer return new TimerHandleImpl(new OOBTimer<>(this.manager, this.timer.getId(), this.invoker, this.synchronizationFactory), this.invoker.getComponent()); } } @Override public ScheduleExpression getSchedule() { this.validateInvocationContext(); if (!this.timer.getMetaData().getType().isCalendar()) { throw EjbLogger.EJB3_TIMER_LOGGER.invalidTimerNotCalendarBaseTimer(this); } try (BatchContext context = this.manager.getBatcher().resumeBatch(this.suspendedBatch)) { ImmutableScheduleExpression expression = this.timer.getMetaData().getConfiguration(ScheduleTimerConfiguration.class).getScheduleExpression(); ScheduleExpression result = new ScheduleExpression() .second(expression.getSecond()) .minute(expression.getMinute()) .hour(expression.getHour()) .dayOfMonth(expression.getDayOfMonth()) .month(expression.getMonth()) .dayOfWeek(expression.getDayOfWeek()) .year(expression.getYear()); Instant start = expression.getStart(); if (start != null) { result.start(Date.from(start)); } Instant end = expression.getEnd(); if (end != null) { result.end(Date.from(end)); } ZoneId zone = expression.getZone(); if (zone != SimpleImmutableScheduleExpression.DEFAULT_ZONE_ID) { result.timezone(zone.getId()); } return result; } } @Override public boolean isCalendarTimer() { this.validateInvocationContext(); try (BatchContext context = this.manager.getBatcher().resumeBatch(this.suspendedBatch)) { return this.timer.getMetaData().getType().isCalendar(); } } @Override public boolean isPersistent() { this.validateInvocationContext(); try (BatchContext context = this.manager.getBatcher().resumeBatch(this.suspendedBatch)) { return this.timer.getMetaData().isPersistent(); } } @Override public int hashCode() { return this.timer.hashCode(); } @Override public boolean equals(Object object) { if (!(object instanceof ManagedTimer)) return false; return this.getId().equals(((ManagedTimer) object).getId()); } @Override public String toString() { return this.getId(); } }
9,473
36.74502
184
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/distributable/SimpleImmutableScheduleExpression.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.distributable; import static org.jboss.as.ejb3.logging.EjbLogger.EJB3_TIMER_LOGGER; import java.time.DateTimeException; import java.time.Instant; import java.time.ZoneId; import java.util.Date; import jakarta.ejb.ScheduleExpression; import org.wildfly.clustering.ejb.timer.ImmutableScheduleExpression; /** * An immutable copy of a {@link ScheduleExpression}. * @author Paul Ferraro */ public class SimpleImmutableScheduleExpression implements ImmutableScheduleExpression { static final ZoneId DEFAULT_ZONE_ID = ZoneId.systemDefault(); private final String second; private final String minute; private final String hour; private final String dayOfMonth; private final String month; private final String dayOfWeek; private final String year; private final ZoneId zone; private final Instant start; private final Instant end; public SimpleImmutableScheduleExpression(ScheduleExpression expression) { this.second = expression.getSecond(); this.minute = expression.getMinute(); this.hour = expression.getHour(); this.dayOfMonth = expression.getDayOfMonth(); this.month = expression.getMonth(); this.dayOfWeek = expression.getDayOfWeek(); this.year = expression.getYear(); this.zone = createZoneId(expression.getTimezone()); Date start = expression.getStart(); Date end = expression.getEnd(); this.start = (start != null) ? start.toInstant() : null; this.end = (end != null) ? end.toInstant() : null; } private static ZoneId createZoneId(String id) { if (id == null) return DEFAULT_ZONE_ID; try { return ZoneId.of(id.trim()); } catch (DateTimeException e) { EJB3_TIMER_LOGGER.unknownTimezoneId(id, DEFAULT_ZONE_ID.getId()); return DEFAULT_ZONE_ID; } } @Override public String getSecond() { return this.second; } @Override public String getMinute() { return this.minute; } @Override public String getHour() { return this.hour; } @Override public String getDayOfMonth() { return this.dayOfMonth; } @Override public String getMonth() { return this.month; } @Override public String getDayOfWeek() { return this.dayOfWeek; } @Override public String getYear() { return this.year; } @Override public ZoneId getZone() { return this.zone; } @Override public Instant getStart() { return this.start; } @Override public Instant getEnd() { return this.end; } }
3,751
27.861538
87
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/distributable/DistributableTimerService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.distributable; import java.lang.reflect.Method; import java.time.Duration; import java.time.Instant; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Stream; import jakarta.ejb.EJBException; import jakarta.ejb.ScheduleExpression; import jakarta.ejb.TimerConfig; import jakarta.transaction.RollbackException; import jakarta.transaction.SystemException; import jakarta.transaction.Transaction; import jakarta.transaction.TransactionSynchronizationRegistry; import org.jboss.as.ejb3.component.EJBComponent; import org.jboss.as.ejb3.context.CurrentInvocationContext; import org.jboss.as.ejb3.timerservice.spi.AutoTimer; import org.jboss.as.ejb3.timerservice.spi.ManagedTimer; import org.jboss.as.ejb3.timerservice.spi.ManagedTimerService; import org.jboss.as.ejb3.timerservice.spi.TimedObjectInvoker; import org.jboss.as.ejb3.timerservice.spi.TimerServiceRegistry; import org.jboss.invocation.InterceptorContext; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.ee.Batcher; import org.wildfly.clustering.ejb.timer.ImmutableScheduleExpression; import org.wildfly.clustering.ejb.timer.IntervalTimerConfiguration; import org.wildfly.clustering.ejb.timer.ScheduleTimerConfiguration; import org.wildfly.clustering.ejb.timer.Timer; import org.wildfly.clustering.ejb.timer.TimerManager; /** * EJB specification facade for a distributable EJB timer manager. * @author Paul Ferraro * @param <I> the timer identifier type */ public class DistributableTimerService<I> implements ManagedTimerService { private final TimerServiceRegistry registry; private final TimedObjectInvoker invoker; private final TimerManager<I, Batch> manager; private final TimerSynchronizationFactory<I> synchronizationFactory; private final Function<String, I> identifierParser; private final Predicate<TimerConfig> filter; public DistributableTimerService(DistributableTimerServiceConfiguration<I> configuration, TimerManager<I, Batch> manager) { this.invoker = configuration.getInvoker(); this.identifierParser = configuration.getIdentifierParser(); this.filter = configuration.getTimerFilter(); this.registry = configuration.getTimerServiceRegistry(); this.manager = manager; this.synchronizationFactory = configuration.getTimerSynchronizationFactory(); } @Override public TimedObjectInvoker getInvoker() { return this.invoker; } @Override public void start() { this.manager.start(); // Create and start auto-timers, if they do not already exist Supplier<I> identifierFactory = this.manager.getIdentifierFactory(); EJBComponent component = this.invoker.getComponent(); try (Batch batch = this.manager.getBatcher().createBatch()) { for (Map.Entry<Method, List<AutoTimer>> entry : component.getComponentDescription().getScheduleMethods().entrySet()) { Method method = entry.getKey(); ListIterator<AutoTimer> timers = entry.getValue().listIterator(); while (timers.hasNext()) { AutoTimer autoTimer = timers.next(); if (this.filter.test(autoTimer.getTimerConfig())) { Timer<I> timer = this.manager.createTimer(identifierFactory.get(), new SimpleScheduleTimerConfiguration(autoTimer.getScheduleExpression()), autoTimer.getTimerConfig().getInfo(), method, timers.previousIndex()); if (timer != null) { timer.activate(); } } } } } this.registry.registerTimerService(this); } @Override public void stop() { this.registry.unregisterTimerService(this); this.manager.stop(); } @Override public ManagedTimer findTimer(String timerId) { InterceptorContext interceptorContext = CurrentInvocationContext.get(); ManagedTimer currentTimer = (interceptorContext != null) ? (ManagedTimer) interceptorContext.getTimer() : null; if ((currentTimer != null) && currentTimer.getId().equals(timerId)) { return currentTimer; } try { I id = this.identifierParser.apply(timerId); try (Batch batch = this.manager.getBatcher().createBatch()) { Timer<I> timer = this.manager.getTimer(id); return (timer != null) ? new OOBTimer<>(this.manager, timer.getId(), this.invoker, this.synchronizationFactory) : null; } } catch (IllegalArgumentException e) { // We couldn't parse the timerId return null; } } @Override public jakarta.ejb.Timer createCalendarTimer(ScheduleExpression schedule, TimerConfig config) { return this.createEJBTimer(new ScheduleTimerFactory<>(schedule, config.getInfo())); } @Override public jakarta.ejb.Timer createIntervalTimer(Date initialExpiration, long intervalDuration, TimerConfig config) { return this.createEJBTimer(new IntervalTimerFactory<>(initialExpiration.toInstant(), Duration.ofMillis(intervalDuration), config.getInfo())); } @Override public jakarta.ejb.Timer createSingleActionTimer(Date expiration, TimerConfig config) { return this.createEJBTimer(new IntervalTimerFactory<>(expiration.toInstant(), null, config.getInfo())); } private jakarta.ejb.Timer createEJBTimer(BiFunction<TimerManager<I, Batch>, I, Timer<I>> factory) { Timer<I> timer = this.createTimer(factory); return new OOBTimer<>(this.manager, timer.getId(), this.invoker, this.synchronizationFactory); } private Timer<I> createTimer(BiFunction<TimerManager<I, Batch>, I, Timer<I>> factory) { Transaction transaction = ManagedTimerService.getActiveTransaction(); boolean close = true; Batcher<Batch> batcher = this.manager.getBatcher(); Batch batch = batcher.createBatch(); try { I id = this.manager.getIdentifierFactory().get(); Timer<I> timer = factory.apply(this.manager, id); if (timer.getMetaData().getNextTimeout() != null) { if (transaction != null) { // Transactional case: Activate timer on tx commit // Cancel timer on tx rollback Batch suspendedBatch = batcher.suspendBatch(); transaction.registerSynchronization(this.synchronizationFactory.createActivateSynchronization(timer, suspendedBatch, batcher)); TransactionSynchronizationRegistry tsr = this.invoker.getComponent().getTransactionSynchronizationRegistry(); // Store suspended batch in TSR so we can resume it later, if necessary tsr.putResource(id, new SimpleImmutableEntry<>(timer, suspendedBatch)); @SuppressWarnings("unchecked") Set<I> inactiveTimers = (Set<I>) tsr.getResource(this.manager); if (inactiveTimers == null) { inactiveTimers = new TreeSet<>(); tsr.putResource(this.manager, inactiveTimers); } inactiveTimers.add(id); close = false; } else { // Non-transactional case: activate timer immediately. this.synchronizationFactory.getActivateTask().accept(timer); } } else { // This timer will never expire! timer.cancel(); } return timer; } catch (RollbackException e) { // getActiveTransaction() would have returned null throw new IllegalStateException(e); } catch (SystemException e) { batch.discard(); throw new EJBException(e); } finally { if (close) { batch.close(); } } } @Override public Collection<jakarta.ejb.Timer> getTimers() throws EJBException { this.validateInvocationContext(); Collection<jakarta.ejb.Timer> timers = new LinkedList<>(); @SuppressWarnings("unchecked") Set<I> inactiveTimers = (ManagedTimerService.getActiveTransaction() != null) ? (Set<I>) this.invoker.getComponent().getTransactionSynchronizationRegistry().getResource(this.manager) : null; if (inactiveTimers != null) { this.addTimers(timers, inactiveTimers); } try (Stream<I> activeTimers = this.manager.getActiveTimers()) { this.addTimers(timers, activeTimers::iterator); } return Collections.unmodifiableCollection(timers); } private void addTimers(Collection<jakarta.ejb.Timer> timers, Iterable<I> timerIds) { for (I timerId : timerIds) { timers.add(new OOBTimer<>(this.manager, timerId, this.invoker, this.synchronizationFactory)); } } @Override public Collection<jakarta.ejb.Timer> getAllTimers() throws EJBException { this.validateInvocationContext(); return this.registry.getAllTimers(); } @Override public String toString() { return String.format("%s(%s)", this.getClass().getSimpleName(), this.invoker.getTimedObjectId()); } static class IntervalTimerFactory<I> implements BiFunction<TimerManager<I, Batch>, I, Timer<I>>, IntervalTimerConfiguration { private final Instant start; private final Duration interval; private final Object info; IntervalTimerFactory(Instant start, Duration interval, Object info) { this.start = start; this.interval = interval; this.info = info; } @Override public Instant getStart() { return this.start; } @Override public Duration getInterval() { return this.interval; } @Override public Timer<I> apply(TimerManager<I, Batch> manager, I id) { return manager.createTimer(id, this, this.info); } } static class SimpleScheduleTimerConfiguration implements ScheduleTimerConfiguration { private final ImmutableScheduleExpression expression; SimpleScheduleTimerConfiguration(ScheduleExpression expression) { this.expression = new SimpleImmutableScheduleExpression(expression); } @Override public ImmutableScheduleExpression getScheduleExpression() { return this.expression; } } static class ScheduleTimerFactory<I> implements BiFunction<TimerManager<I, Batch>, I, Timer<I>> { private final ScheduleTimerConfiguration configuration; private final Object info; ScheduleTimerFactory(ScheduleExpression expression, Object info) { this.configuration = new SimpleScheduleTimerConfiguration(expression); this.info = info; } @Override public Timer<I> apply(TimerManager<I, Batch> manager, I id) { return manager.createTimer(id, this.configuration, this.info); } } }
12,648
40.884106
234
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/distributable/DistributableTimeoutListener.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.distributable; import java.util.concurrent.ExecutionException; import java.util.concurrent.RejectedExecutionException; import org.jboss.as.ejb3.component.EJBComponentUnavailableException; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.timerservice.spi.ManagedTimer; import org.jboss.as.ejb3.timerservice.spi.TimedObjectInvoker; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.ee.Batcher; import org.wildfly.clustering.ejb.timer.TimeoutListener; import org.wildfly.clustering.ejb.timer.Timer; import org.wildfly.clustering.ejb.timer.TimerManager; /** * Timeout listener implementation that invokes the relevant timeout callback method of an EJB. * @author Paul Ferraro * @param <I> the timer identifier type */ public class DistributableTimeoutListener<I> implements TimeoutListener<I, Batch> { private final TimedObjectInvoker invoker; private final TimerSynchronizationFactory<I> synchronizationFactory; DistributableTimeoutListener(TimedObjectInvoker invoker, TimerSynchronizationFactory<I> synchronizationFactory) { this.invoker = invoker; this.synchronizationFactory = synchronizationFactory; } @Override public void timeout(TimerManager<I, Batch> manager, Timer<I> timer) throws ExecutionException { Batcher<Batch> batcher = manager.getBatcher(); Batch suspendedBatch = batcher.suspendBatch(); try { ManagedTimer managedTimer = new DistributableTimer<>(manager, timer, suspendedBatch, this.invoker, this.synchronizationFactory); try { invoke(managedTimer); } catch (ExecutionException e) { EjbLogger.EJB3_TIMER_LOGGER.errorInvokeTimeout(managedTimer, e); // Retry once on execution failure EjbLogger.EJB3_TIMER_LOGGER.timerRetried(managedTimer); invoke(managedTimer); } } finally { batcher.resumeBatch(suspendedBatch); } } private static void invoke(ManagedTimer timer) throws ExecutionException { try { timer.invoke(); } catch (EJBComponentUnavailableException e) { throw new RejectedExecutionException(e); } catch (Throwable e) { throw new ExecutionException(e); } } }
3,394
40.402439
140
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/timerservice/distributable/DistributableTimerSynchronizationFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.timerservice.distributable; import java.util.function.Consumer; import jakarta.transaction.Status; import jakarta.transaction.Synchronization; import org.jboss.as.ejb3.context.CurrentInvocationContext; import org.jboss.as.ejb3.timerservice.spi.ManagedTimer; import org.jboss.invocation.InterceptorContext; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.ee.BatchContext; import org.wildfly.clustering.ee.Batcher; import org.wildfly.clustering.ee.Batch.State; import org.wildfly.clustering.ejb.timer.Timer; import org.wildfly.clustering.ejb.timer.TimerRegistry; /** * Factory for creating {@link Synchronization} instances for a distributed timer service. * @author Paul Ferraro * @param <I> the timer identifier type */ public class DistributableTimerSynchronizationFactory<I> implements TimerSynchronizationFactory<I> { private final Consumer<Timer<I>> activateTask; private final Consumer<Timer<I>> cancelTask; public DistributableTimerSynchronizationFactory(TimerRegistry<I> registry) { this.activateTask = new Consumer<>() { @Override public void accept(Timer<I> timer) { timer.activate(); registry.register(timer.getId()); } }; this.cancelTask = new Consumer<>() { @Override public void accept(Timer<I> timer) { registry.unregister(timer.getId()); timer.cancel(); } }; } @Override public Consumer<Timer<I>> getActivateTask() { return this.activateTask; } @Override public Consumer<Timer<I>> getCancelTask() { return this.cancelTask; } @Override public Synchronization createActivateSynchronization(Timer<I> timer, Batch batch, Batcher<Batch> batcher) { return new DistributableTimerSynchronization<>(timer, batch, batcher, this.activateTask, this.cancelTask); } @Override public Synchronization createCancelSynchronization(Timer<I> timer, Batch batch, Batcher<Batch> batcher) { return new DistributableTimerSynchronization<>(timer, batch, batcher, this.cancelTask, this.activateTask); } private static class DistributableTimerSynchronization<I> implements Synchronization { private final Batcher<Batch> batcher; private final Timer<I> timer; private final Batch batch; private final Consumer<Timer<I>> commitTask; private final Consumer<Timer<I>> rollbackTask; DistributableTimerSynchronization(Timer<I> timer, Batch batch, Batcher<Batch> batcher, Consumer<Timer<I>> commitTask, Consumer<Timer<I>> rollbackTask) { this.timer = timer; this.batch = batch; this.batcher = batcher; this.commitTask = commitTask; this.rollbackTask = rollbackTask; } @Override public void beforeCompletion() { // Do nothing } @Override public void afterCompletion(int status) { InterceptorContext interceptorContext = CurrentInvocationContext.get(); ManagedTimer currentTimer = (interceptorContext != null) ? (ManagedTimer) interceptorContext.getTimer() : null; try (BatchContext context = this.batcher.resumeBatch(this.batch)) { try (Batch currentBatch = ((currentTimer != null) && currentTimer.getId().equals(this.timer.getId().toString())) || this.batch.getState() != State.ACTIVE ? this.batcher.createBatch() : this.batch) { if (!this.timer.isCanceled()) { if (status == Status.STATUS_COMMITTED) { this.commitTask.accept(this.timer); } else { this.rollbackTask.accept(this.timer); } } } } } } }
4,969
38.133858
214
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/clustering/SingletonBarrierService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.clustering; import static org.jboss.as.ejb3.subsystem.EJB3SubsystemRootResourceDefinition.CLUSTERED_SINGLETON_CAPABILITY; import java.util.function.Supplier; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StopContext; import org.wildfly.clustering.singleton.service.SingletonPolicy; /** * Service that installs a singleton service on service start using a singleton policy. * * @author Flavia Rainone */ public class SingletonBarrierService implements Service { public static final ServiceName SERVICE_NAME = CLUSTERED_SINGLETON_CAPABILITY.getCapabilityServiceName().append("barrier"); private final Supplier<SingletonPolicy> policy; public SingletonBarrierService(Supplier<SingletonPolicy> policy) { this.policy = policy; } @Override public void start(StartContext context) { this.policy.get().createSingletonServiceConfigurator(CLUSTERED_SINGLETON_CAPABILITY.getCapabilityServiceName()) .build(context.getChildTarget()) .install(); } @Override public void stop(StopContext context) { } }
2,236
36.915254
127
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/clustering/ClusteringSchema.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.clustering; import java.util.List; import org.jboss.as.controller.xml.IntVersionSchema; import org.jboss.as.controller.xml.VersionedNamespace; import org.jboss.staxmapper.IntVersion; /** * @author Paul Ferraro */ public enum ClusteringSchema implements IntVersionSchema<ClusteringSchema> { VERSION_1_0(1, 0), VERSION_1_1(1, 1), ; static final ClusteringSchema CURRENT = VERSION_1_1; private final VersionedNamespace<IntVersion, ClusteringSchema> namespace; ClusteringSchema(int major, int minor) { this.namespace = IntVersionSchema.createURN(List.of(this.getLocalName()), new IntVersion(major, minor)); } @Override public String getLocalName() { return "clustering"; } @Override public VersionedNamespace<IntVersion, ClusteringSchema> getNamespace() { return this.namespace; } }
1,915
32.614035
112
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/clustering/EJBBoundClusteringMetaData.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.clustering; import org.jboss.metadata.ejb.parser.jboss.ejb3.AbstractEJBBoundMetaData; /** * @author Jaikiran Pai * @author Flavia Rainone */ public class EJBBoundClusteringMetaData extends AbstractEJBBoundMetaData { private static final long serialVersionUID = 4149623336107841341L; private boolean singleton; public void setClusteredSingleton(boolean singleton) { this.singleton = singleton; } public boolean isClusteredSingleton() { return singleton; } }
1,555
34.363636
74
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/clustering/EJBBoundClusteringMetaDataParser.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.clustering; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.metadata.ejb.parser.jboss.ejb3.AbstractEJBBoundMetaDataParser; import org.jboss.metadata.property.PropertyReplacer; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; /** * Parses the urn:clustering namespace elements for clustering related metadata on Jakarta Enterprise Beans. * * @author Jaikiran Pai * @author Flavia Rainone */ public class EJBBoundClusteringMetaDataParser extends AbstractEJBBoundMetaDataParser<EJBBoundClusteringMetaData> { private final ClusteringSchema schema; public EJBBoundClusteringMetaDataParser(ClusteringSchema schema) { this.schema = schema; } @Override public EJBBoundClusteringMetaData parse(final XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException { // we only parse <clustering> (root) element if (!reader.getLocalName().equals("clustering")) { throw unexpectedElement(reader); } if (this.schema != ClusteringSchema.CURRENT) { EjbLogger.ROOT_LOGGER.deprecatedNamespace(reader.getNamespaceURI(), reader.getLocalName()); } EJBBoundClusteringMetaData metaData = new EJBBoundClusteringMetaData(); this.processElements(metaData, reader, propertyReplacer); return metaData; } @Override protected void processElement(final EJBBoundClusteringMetaData metaData, final XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException { if (this.schema.getNamespace().getUri().equals(reader.getNamespaceURI())) { switch (reader.getLocalName()) { case "clustered": { if (this.schema.since(ClusteringSchema.VERSION_1_1)) { throw unexpectedElement(reader); } // Swallow ignored content reader.getElementText(); break; } case "clustered-singleton": if (this.schema.since(ClusteringSchema.VERSION_1_1)) { requireNoAttributes(reader); final String text = getElementText(reader, propertyReplacer); if (text != null) { final boolean isClusteredSingleton = Boolean.parseBoolean(text.trim()); metaData.setClusteredSingleton(isClusteredSingleton); } break; } default: { throw unexpectedElement(reader); } } } else { super.processElement(metaData, reader, propertyReplacer); } } }
3,862
41.450549
175
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/logging/EjbLogger.java
/* * * * JBoss, Home of Professional Open Source. * * Copyright 2011, Red Hat, Inc., and individual contributors * * as indicated by the @author tags. See the copyright.txt file in the * * distribution for a full listing of individual contributors. * * * * This is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation; either version 2.1 of * * the License, or (at your option) any later version. * * * * This software is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this software; if not, write to the Free * * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package org.jboss.as.ejb3.logging; import static org.jboss.logging.Logger.Level.DEBUG; import static org.jboss.logging.Logger.Level.ERROR; import static org.jboss.logging.Logger.Level.INFO; import static org.jboss.logging.Logger.Level.WARN; import java.io.File; import java.io.IOException; import java.io.InvalidClassException; import java.lang.reflect.Method; import java.rmi.RemoteException; import java.sql.SQLException; import java.util.Date; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.naming.Context; import javax.xml.stream.Location; import javax.xml.stream.XMLStreamException; import jakarta.ejb.ConcurrentAccessTimeoutException; import jakarta.ejb.EJBAccessException; import jakarta.ejb.EJBException; import jakarta.ejb.EJBTransactionRequiredException; import jakarta.ejb.EJBTransactionRolledbackException; import jakarta.ejb.IllegalLoopbackException; import jakarta.ejb.LockType; import jakarta.ejb.NoMoreTimeoutsException; import jakarta.ejb.NoSuchEJBException; import jakarta.ejb.NoSuchObjectLocalException; import jakarta.ejb.RemoveException; import jakarta.ejb.Timer; import jakarta.ejb.TransactionAttributeType; import jakarta.interceptor.InvocationContext; import jakarta.resource.ResourceException; import jakarta.resource.spi.UnavailableException; import jakarta.resource.spi.endpoint.MessageEndpoint; import jakarta.transaction.NotSupportedException; import jakarta.transaction.RollbackException; import jakarta.transaction.Transaction; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.ee.component.Component; import org.jboss.as.ee.component.ComponentCreateServiceFactory; import org.jboss.as.ee.component.ComponentDescription; import org.jboss.as.ee.component.ComponentInstance; import org.jboss.as.ee.component.ResourceInjectionTarget; import org.jboss.as.ejb3.component.EJBComponentDescription; import org.jboss.as.ejb3.component.EJBComponentUnavailableException; import org.jboss.as.ejb3.component.EJBViewDescription; import org.jboss.as.ejb3.component.singleton.SingletonComponent; import org.jboss.as.ejb3.component.stateful.StatefulSessionComponentInstance; import org.jboss.as.ejb3.subsystem.EJB3SubsystemModel; import org.jboss.as.ejb3.subsystem.deployment.EJBComponentType; import org.jboss.as.ejb3.subsystem.deployment.InstalledComponent; import org.jboss.as.ejb3.timerservice.TimerImpl; import org.jboss.as.ejb3.tx.TimerTransactionRolledBackException; import org.jboss.as.naming.context.NamespaceContextSelector; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.dmr.ModelNode; import org.jboss.ejb.client.EJBLocator; import org.jboss.invocation.InterceptorContext; import org.jboss.invocation.proxy.MethodIdentifier; import org.jboss.jandex.AnnotationTarget; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.MethodInfo; import org.jboss.jca.core.spi.rar.NotFoundException; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.annotations.Param; import org.jboss.logging.annotations.Signature; import org.jboss.metadata.ejb.spec.MethodParametersMetaData; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; /** * @author <a href="mailto:[email protected]">Flemming Harms</a> * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ @MessageLogger(projectCode = "WFLYEJB", length = 4) public interface EjbLogger extends BasicLogger { EjbLogger ROOT_LOGGER = Logger.getMessageLogger(EjbLogger.class, "org.jboss.as.ejb3"); /** * A logger with the category {@code org.jboss.as.ejb3.deployment} used for deployment log messages */ EjbLogger DEPLOYMENT_LOGGER = Logger.getMessageLogger(EjbLogger.class, "org.jboss.as.ejb3.deployment"); /** * A logger with the category {@code org.jboss.as.ejb3.remote} used for remote log messages */ EjbLogger REMOTE_LOGGER = Logger.getMessageLogger(EjbLogger.class, "org.jboss.as.ejb3.remote"); /** * logger use to log Jakarta Enterprise Beans invocation errors */ EjbLogger EJB3_INVOCATION_LOGGER = Logger.getMessageLogger(EjbLogger.class, "org.jboss.as.ejb3.invocation"); /** * logger use to log Jakarta Enterprise Beans timer messages */ EjbLogger EJB3_TIMER_LOGGER = Logger.getMessageLogger(EjbLogger.class, "org.jboss.as.ejb3.timer"); // /** // * Logs an error message indicating an exception occurred while removing an inactive bean. // * // * @param id the session id that could not be removed // */ // @LogMessage(level = ERROR) // @Message(id = 1, value = "Failed to remove %s from cache") // void cacheRemoveFailed(Object id); // /** // * Logs a warning message indicating an Jakarta Enterprise Beans for the specific id could not be found // * // * @param id the session id that could not be released // */ // @LogMessage(level = INFO) // @Message(id = 2, value = "Failed to find SFSB instance with session ID %s in cache") // void cacheEntryNotFound(Object id); // /** // * Logs an error message indicating an exception occurred while executing an invocation // * // * @param cause the cause of the error. // */ // @LogMessage(level = ERROR) // @Message(id = 3, value = "Asynchronous invocation failed") // void asyncInvocationFailed(@Cause Throwable cause); /** * Logs an error message indicating an exception occurred while getting status * * @param cause the cause of the error. */ @LogMessage(level = ERROR) @Message(id = 4, value = "failed to get tx manager status; ignoring") void getTxManagerStatusFailed(@Cause Throwable cause); /** * Logs an error message indicating an exception occurred while calling setRollBackOnly * * @param se the cause of the error. */ @LogMessage(level = ERROR) @Message(id = 5, value = "failed to set rollback only; ignoring") void setRollbackOnlyFailed(@Cause Throwable se); /** * Logs a warning message indicating ActivationConfigProperty will be ignored since it is not allowed by resource adapter */ @LogMessage(level = WARN) @Message(id = 6, value = "ActivationConfigProperty %s will be ignored since it is not allowed by resource adapter: %s") void activationConfigPropertyIgnored(Object propName, String resourceAdapterName); /** * Logs an error message indicating Discarding stateful component instance due to exception * * @param component the discarded instance * @param t the cause of error */ @LogMessage(level = ERROR) @Message(id = 7, value = "Discarding stateful component instance: %s due to exception") void discardingStatefulComponent(StatefulSessionComponentInstance component, @Cause Throwable t); // /** // * Logs an error message indicating it failed to remove bean with the specified session id // * // */ // @LogMessage(level = ERROR) // @Message(id = 8, value = "Failed to remove bean: %s with session id %s") // void failedToRemoveBean(String componentName, SessionID sessionId, @Cause Throwable t); // /** // * Logs an info message indicating it could not find stateful session bean instance with id // * // * @param sessionId the id of the session bean // * @param componentName // */ // @LogMessage(level = INFO) // @Message(id = 9, value = "Could not find stateful session bean instance with id: %s for bean: %s during destruction. Probably already removed") // void failToFindSfsbWithId(SessionID sessionId, String componentName); /** * Logs a warning message indicating Default interceptor class is not listed in the <interceptors> section of ejb-jar.xml and will not be applied" */ @LogMessage(level = WARN) @Message(id = 10, value = "Default interceptor class %s is not listed in the <interceptors> section of ejb-jar.xml and will not be applied") void defaultInterceptorClassNotListed(String clazz); // /** // * Logs a warning message indicating No method found on Jakarta Enterprise Beans while processing exclude-list element in ejb-jar.xml // */ // @LogMessage(level = WARN) // @Message(id = 11, value = "No method named: %s found on Jakarta Enterprise Beans: %s while processing exclude-list element in ejb-jar.xml") // void noMethodFoundOnEjbExcludeList(String methodName, String ejbName); // /** // * Logs a warning message indicating No method with param types found on Jakarta Enterprise Beans while processing exclude-list element in ejb-jar.xml // */ // @LogMessage(level = WARN) // @Message(id = 12, value = "No method named: %s with param types: %s found on Jakarta Enterprise Beans: %s while processing exclude-list element in ejb-jar.xml") // void noMethodFoundOnEjbWithParamExcludeList(String methodName, String s, String ejbName); // /** // * Logs a warning message indicating no method named found on Jakarta Enterprise Beans while processing method-permission element in ejb-jar.xml // */ // @LogMessage(level = WARN) // @Message(id = 13, value = "No method named: %s found on Jakarta Enterprise Beans: %s while processing method-permission element in ejb-jar.xml") // void noMethodFoundOnEjbPermission(String methodName, String ejbName); // /** // * Logs a warning message indicating No method with param type found on Jakarta Enterprise Beans while processing method-permission element in ejb-jar.xml // */ // @LogMessage(level = WARN) // @Message(id = 14, value = "No method named: %s with param types: %s found on Jakarta Enterprise Beans: %s while processing method-permission element in ejb-jar.xml") // void noMethodFoundWithParamOnEjbMethodPermission(String methodName, String s, String ejbName); /** * Logs a warning message indicating Unknown timezone id found in schedule expression. Ignoring it and using server's timezone */ @LogMessage(level = WARN) @Message(id = 15, value = "Unknown timezone id: %s found in schedule expression. Ignoring it and using server's timezone: %s") void unknownTimezoneId(String timezoneId, String id); /** * Logs a warning message indicating the timer persistence is not enabled, persistent timers will not survive JVM restarts */ @LogMessage(level = WARN) @Message(id = 16, value = "Timer persistence is not enabled, persistent timers will not survive JVM restarts") void timerPersistenceNotEnable(); /** * Logs an info message indicating the next expiration is null. No tasks will be scheduled for timer */ @LogMessage(level = INFO) @Message(id = 17, value = "Next expiration is null. No tasks will be scheduled for timer %S") void nextExpirationIsNull(TimerImpl timer); /** * Logs an error message indicating Ignoring exception during setRollbackOnly */ @LogMessage(level = ERROR) @Message(id = 18, value = "Ignoring exception during setRollbackOnly") void ignoringException(@Cause Throwable e); // /** // * Logs a warning message indicating the unregistered an already registered Timerservice with id %s and a new instance will be registered // */ // @LogMessage(level = WARN) // @Message(id = 19, value = "Unregistered an already registered Timerservice with id %s and a new instance will be registered") // void UnregisteredRegisteredTimerService(String timedObjectId); /** * Logs an error message indicating an error invoking timeout for timer */ @LogMessage(level = ERROR) @Message(id = 20, value = "Error invoking timeout for timer: %s") void errorInvokeTimeout(Timer timer, @Cause Throwable e); /** * Logs an info message indicating timer will be retried */ @LogMessage(level = INFO) @Message(id = 21, value = "Timer: %s will be retried") void timerRetried(Timer timer); /** * Logs an error message indicating an error during retyring timeout for timer */ @LogMessage(level = ERROR) @Message(id = 22, value = "Error during retrying timeout for timer: %s") void errorDuringRetryTimeout(Timer timer, @Cause Throwable e); /** * Logs an info message indicating retrying timeout for timer */ @LogMessage(level = INFO) @Message(id = 23, value = "Retrying timeout for timer: %s") void retryingTimeout(Timer timer); /** * Logs an info message indicating timer is not active, skipping retry of timer */ @LogMessage(level = INFO) @Message(id = 24, value = "Timer is not active, skipping retry of timer: %s") void timerNotActive(Timer timer); /** * Logs a warning message indicating could not read timer information for Jakarta Enterprise Beans component */ @LogMessage(level = WARN) @Message(id = 26, value = "Could not read timer information for Jakarta Enterprise Beans component %s") void failToReadTimerInformation(String componentName); // /** // * Logs an error message indicating it could not remove persistent timer // */ // @LogMessage(level = ERROR) // @Message(id = 27, value = "Could not remove persistent timer %s") // void failedToRemovePersistentTimer(File file); /** * Logs an error message indicating it's not a directory, could not restore timers" */ @LogMessage(level = ERROR) @Message(id = 28, value = "%s is not a directory, could not restore timers") void failToRestoreTimers(File file); /** * Logs an error message indicating it could not restore timer from file */ @LogMessage(level = ERROR) @Message(id = 29, value = "Could not restore timer from %s") void failToRestoreTimersFromFile(File timerFile, @Cause Throwable e); /** * Logs an error message indicating error closing file */ @LogMessage(level = ERROR) @Message(id = 30, value = "error closing file ") void failToCloseFile(@Cause Throwable e); /** * Logs an error message indicating Could not restore timers for specified id */ @LogMessage(level = ERROR) @Message(id = 31, value = "Could not restore timers for %s") void failToRestoreTimersForObjectId(String timedObjectId, @Cause Throwable e); /** * Logs an error message indicating Could not restore timers for specified id */ @LogMessage(level = ERROR) @Message(id = 32, value = "Could not create directory %s to persist Jakarta Enterprise Beans timers.") void failToCreateDirectoryForPersistTimers(File file); // /** // * Logs an error message indicating it discarding entity component instance // */ // @LogMessage(level = ERROR) // @Message(id = 33, value = "Discarding entity component instance: %s due to exception") // void discardingEntityComponent(EntityBeanComponentInstance instance, @Cause Throwable t); /** * Logs an error message indicating that an invocation failed */ @LogMessage(level = ERROR) @Message(id = 34, value = "Jakarta Enterprise Beans Invocation failed on component %s for method %s") void invocationFailed(String component, Method method, @Cause Throwable t); /** * Logs an error message indicating that an Jakarta Enterprise Beans client proxy could not be swapped out in a RMI invocation */ @LogMessage(level = WARN) @Message(id = 35, value = "Could not find Jakarta Enterprise Beans for locator %s, Jakarta Enterprise Beans client proxy will not be replaced") void couldNotFindEjbForLocatorIIOP(EJBLocator<?> locator); /** * Logs an error message indicating that an Jakarta Enterprise Beans client proxy could not be swapped out in a RMI invocation */ @LogMessage(level = WARN) @Message(id = 36, value = "Jakarta Enterprise Beans %s is not being replaced with a Stub as it is not exposed over IIOP") void ejbNotExposedOverIIOP(EJBLocator<?> locator); /** * Logs an error message indicating that dynamic stub creation failed */ @LogMessage(level = ERROR) @Message(id = 37, value = "Dynamic stub creation failed for class %s") void dynamicStubCreationFailed(String clazz, @Cause Throwable t); // /** // */ // @LogMessage(level = ERROR) // @Message(id = 38, value = "Exception releasing entity") // void exceptionReleasingEntity(@Cause Throwable t); // // /** // * Log message indicating that an unsupported client marshalling strategy was received from a remote client // * // * @param strategy The client marshalling strategy // * @param channel The channel on which the client marshalling strategy was received // */ // @LogMessage(level = INFO) // @Message(id = 39, value = "Unsupported client marshalling strategy %s received on channel %s ,no further communication will take place") // void unsupportedClientMarshallingStrategy(String strategy, Channel channel); // // // /** // * Log message indicating that some error caused a channel to be closed // * // * @param channel The channel being closed // * @param t The cause // */ // @LogMessage(level = ERROR) // @Message(id = 40, value = "Closing channel %s due to an error") // void closingChannel(Channel channel, @Cause Throwable t); // // /** // * Log message indicating that a {@link Channel.Receiver#handleEnd(org.jboss.remoting3.Channel)} notification // * was received and the channel is being closed // * // * @param channel The channel for which the {@link Channel.Receiver#handleEnd(org.jboss.remoting3.Channel)} notification // * was received // */ // @LogMessage(level = DEBUG) // @Message(id = 41, value = "Channel end notification received, closing channel %s") // void closingChannelOnChannelEnd(Channel channel); /** * Logs a message which includes the resource adapter name and the destination on which a message driven bean * is listening * * @param mdbName The message driven bean name * @param raName The resource adapter name */ @LogMessage(level = INFO) @Message(id = 42, value = "Started message driven bean '%s' with '%s' resource adapter") void logMDBStart(final String mdbName, final String raName); /** * Logs a waring message indicating an overlapped invoking timeout for timer */ @LogMessage(level = WARN) @Message(id = 43, value = "A previous execution of timer %s is still in progress, skipping this overlapping scheduled execution at: %s.") void skipOverlappingInvokeTimeout(Timer timer, Date scheduledTime); /** * Returns a {@link IllegalStateException} indicating that {@link org.jboss.jca.core.spi.rar.ResourceAdapterRepository} * was unavailable * * @return the exception */ @Message(id = 44, value = "Resource adapter repository is not available") IllegalStateException resourceAdapterRepositoryUnAvailable(); /** * Returns a {@link IllegalArgumentException} indicating that no {@link org.jboss.jca.core.spi.rar.Endpoint} * could be found for a resource adapter named <code>resourceAdapterName</code> * * @param resourceAdapterName The name of the resource adapter * @param notFoundException The original exception cause * @return the exception */ @Message(id = 45, value = "Could not find an Endpoint for resource adapter %s") IllegalArgumentException noSuchEndpointException(final String resourceAdapterName, @Cause NotFoundException notFoundException); /** * Returns a {@link IllegalStateException} indicating that the {@link org.jboss.jca.core.spi.rar.Endpoint} * is not available * * @param componentName The MDB component name * @return the exception */ @Message(id = 46, value = "Endpoint is not available for message driven component %s") IllegalStateException endpointUnAvailable(String componentName); /** * Returns a {@link RuntimeException} indicating that the {@link org.jboss.jca.core.spi.rar.Endpoint} * for the message driven component, could not be deactivated * * @param componentName The message driven component name * @param cause Original cause * @return the exception */ @Message(id = 47, value = "Could not deactivate endpoint for message driven component %s") RuntimeException failureDuringEndpointDeactivation(final String componentName, @Cause ResourceException cause); // @Message(id = 48, value = "") // UnsupportedCallbackException unsupportedCallback(@Param Callback current); @Message(id = 49, value = "Could not create an instance of cluster node selector %s for cluster %s") RuntimeException failureDuringLoadOfClusterNodeSelector(final String clusterNodeSelectorName, final String clusterName, @Cause Exception e); @LogMessage(level = WARN) @Message(id = 50, value = "Failed to parse property %s due to %s") void failedToCreateOptionForProperty(String propertyName, String reason); @Message(id = 51, value = "Could not find view %s for Jakarta Enterprise Beans %s") IllegalStateException viewNotFound(String viewClass, String ejbName); @Message(id = 52, value = "Cannot perform asynchronous local invocation for component that is not a session bean") RuntimeException asyncInvocationOnlyApplicableForSessionBeans(); @Message(id = 53, value = "%s is not a Stateful Session bean in app: %s module: %s distinct-name: %s") IllegalArgumentException notStatefulSessionBean(String ejbName, String appName, String moduleName, String distinctName); @Message(id = 54, value = "Failed to marshal Jakarta Enterprise Beans parameters") RuntimeException failedToMarshalEjbParameters(@Cause Exception e); @Message(id = 55, value = "No matching deployment for Jakarta Enterprise Beans: %s") NoSuchEJBException unknownDeployment(EJBLocator<?> locator); @Message(id = 56, value = "Could not find Jakarta Enterprise Beans in matching deployment: %s") NoSuchEJBException ejbNotFoundInDeployment(EJBLocator<?> locator); @Message(id = 57, value = "%s annotation is only valid on method targets") IllegalArgumentException annotationApplicableOnlyForMethods(String annotationName); @Message(id = 58, value = "Method %s, on class %s, annotated with @jakarta.interceptor.AroundTimeout is expected to accept a single param of type jakarta.interceptor.InvocationContext") IllegalArgumentException aroundTimeoutMethodExpectedWithInvocationContextParam(String methodName, String className); @Message(id = 59, value = "Method %s, on class %s, annotated with @jakarta.interceptor.AroundTimeout must return Object type") IllegalArgumentException aroundTimeoutMethodMustReturnObjectType(String methodName, String className); @Message(id = 60, value = "Wrong tx on thread: expected %s, actual %s") IllegalStateException wrongTxOnThread(Transaction expected, Transaction actual); @Message(id = 61, value = "Unknown transaction attribute %s on invocation %s") IllegalStateException unknownTxAttributeOnInvocation(TransactionAttributeType txAttr, InterceptorContext invocation); @Message(id = 62, value = "Transaction is required for invocation %s") EJBTransactionRequiredException txRequiredForInvocation(InterceptorContext invocation); @Message(id = 63, value = "Transaction present on server in Never call (Enterprise Beans 3 13.6.2.6)") EJBException txPresentForNeverTxAttribute(); @LogMessage(level = ERROR) @Message(id = 64, value = "Failed to set transaction for rollback only") void failedToSetRollbackOnly(@Cause Throwable e); @Message(id = 65, value = "View interface cannot be null") IllegalArgumentException viewInterfaceCannotBeNull(); // @Message(id = 66, value = "Cannot call getEjbObject before the object is associated with a primary key") // IllegalStateException cannotCallGetEjbObjectBeforePrimaryKeyAssociation(); // // @Message(id = 67, value = "Cannot call getEjbLocalObject before the object is associated with a primary key") // IllegalStateException cannotCallGetEjbLocalObjectBeforePrimaryKeyAssociation(); @Message(id = 68, value = "Could not load view class for component %s") RuntimeException failedToLoadViewClassForComponent(@Cause Exception e, String componentName); // @Message(id = 69, value = "Entities can not be created for %s bean since no create method is available.") // IllegalStateException entityCannotBeCreatedDueToMissingCreateMethod(String beanName); // // @Message(id = 70, value = "%s is not an entity bean component") // IllegalArgumentException notAnEntityBean(Component component); // // @Message(id = 71, value = "Instance for PK [%s] already registered") // IllegalStateException instanceAlreadyRegisteredForPK(Object primaryKey); // // @Message(id = 72, value = "Instance [%s] not found in cache") // IllegalStateException entityBeanInstanceNotFoundInCache(EntityBeanComponentInstance instance); @Message(id = 73, value = "Illegal call to EJBHome.remove(Object) on a session bean") RemoveException illegalCallToEjbHomeRemove(); @Message(id = 74, value = "Enterprise Beans 3.1 FR 13.6.2.8 setRollbackOnly is not allowed with SUPPORTS transaction attribute") IllegalStateException setRollbackOnlyNotAllowedForSupportsTxAttr(); @Message(id = 75, value = "Cannot call getPrimaryKey on a session bean") EJBException cannotCallGetPKOnSessionBean(); @Message(id = 76, value = "Singleton beans cannot have Enterprise Beans 2.x views") RuntimeException ejb2xViewNotApplicableForSingletonBeans(); // @Message(id = 77, value = "ClassTable %s cannot find a class for class index %d") // ClassNotFoundException classNotFoundInClassTable(String classTableName, int index); @Message(id = 78, value = "Bean %s does not have an EJBLocalObject") IllegalStateException ejbLocalObjectUnavailable(String beanName); @Message(id = 79, value = "[Enterprise Beans 3.1 spec, section 14.1.1] Class: %s cannot be marked as an application exception because it is not of type java.lang.Exception") IllegalArgumentException cannotBeApplicationExceptionBecauseNotAnExceptionType(Class<?> klass); @Message(id = 80, value = "[Enterprise Beans 3.1 spec, section 14.1.1] Exception class: %s cannot be marked as an application exception because it is of type java.rmi.RemoteException") IllegalArgumentException rmiRemoteExceptionCannotBeApplicationException(Class<?> klass); @Message(id = 81, value = "%s annotation is allowed only on classes. %s is not a class") RuntimeException annotationOnlyAllowedOnClass(String annotationName, AnnotationTarget incorrectTarget); @Message(id = 82, value = "Bean %s specifies @Remote annotation, but does not implement 1 interface") DeploymentUnitProcessingException beanWithRemoteAnnotationImplementsMoreThanOneInterface(Class<?> beanClass); @Message(id = 83, value = "Bean %s specifies @Local annotation, but does not implement 1 interface") DeploymentUnitProcessingException beanWithLocalAnnotationImplementsMoreThanOneInterface(Class<?> beanClass); @Message(id = 84, value = "Could not analyze remote interface for %s") RuntimeException failedToAnalyzeRemoteInterface(@Cause Exception e, String beanName); @Message(id = 85, value = "Exception while parsing %s") DeploymentUnitProcessingException failedToParse(@Cause Exception e, String filePath); @Message(id = 86, value = "Failed to install management resources for %s") DeploymentUnitProcessingException failedToInstallManagementResource(@Cause Exception e, String componentName); @Message(id = 87, value = "Could not load view %s") RuntimeException failedToLoadViewClass(@Cause Exception e, String viewClassName); @Message(id = 88, value = "Could not determine type of ejb-ref %s for injection target %s") DeploymentUnitProcessingException couldNotDetermineEjbRefForInjectionTarget(String ejbRefName, ResourceInjectionTarget injectionTarget); @Message(id = 89, value = "Could not determine type of ejb-local-ref %s for injection target %s") DeploymentUnitProcessingException couldNotDetermineEjbLocalRefForInjectionTarget(String ejbLocalRefName, ResourceInjectionTarget injectionTarget); @Message(id = 90, value = "@EJB injection target %s is invalid. Only setter methods are allowed") IllegalArgumentException onlySetterMethodsAllowedToHaveEJBAnnotation(MethodInfo methodInfo); @Message(id = 91, value = "@EJB attribute 'name' is required for class level annotations. Class: %s") DeploymentUnitProcessingException nameAttributeRequiredForEJBAnnotationOnClass(String className); @Message(id = 92, value = "@EJB attribute 'beanInterface' is required for class level annotations. Class: %s") DeploymentUnitProcessingException beanInterfaceAttributeRequiredForEJBAnnotationOnClass(String className); @Message(id = 93, value = "Module hasn't been attached to deployment unit %s") IllegalStateException moduleNotAttachedToDeploymentUnit(DeploymentUnit deploymentUnit); @Message(id = 94, value = "Enterprise Beans 3.1 FR 5.4.2 MessageDrivenBean %s does not implement 1 interface nor specifies message listener interface") DeploymentUnitProcessingException mdbDoesNotImplementNorSpecifyMessageListener(ClassInfo beanClass); @Message(id = 95, value = "Unknown session bean type %s") IllegalArgumentException unknownSessionBeanType(String sessionType); @Message(id = 96, value = "More than one method found with name %s on %s") DeploymentUnitProcessingException moreThanOneMethodWithSameNameOnComponent(String methodName, Class<?> componentClass); @Message(id = 97, value = "Unknown Jakarta Enterprise Beans locator type %s") RuntimeException unknownEJBLocatorType(EJBLocator<?> locator); @Message(id = 98, value = "Could not create CORBA object for %s") RuntimeException couldNotCreateCorbaObject(@Cause Exception cause, EJBLocator<?> locator); @Message(id = 99, value = "Provided locator %s was not for Jakarta Enterprise Beans %s") IllegalArgumentException incorrectEJBLocatorForBean(EJBLocator<?> locator, String beanName); @Message(id = 100, value = "Failed to lookup java:comp/ORB") IOException failedToLookupORB(); @Message(id = 101, value = "%s is not an ObjectImpl") IOException notAnObjectImpl(Class<?> type); @Message(id = 102, value = "Message endpoint %s has already been released") UnavailableException messageEndpointAlreadyReleased(MessageEndpoint messageEndpoint); // @Message(id = 103, value = "Cannot handle client version %s") // RuntimeException ejbRemoteServiceCannotHandleClientVersion(byte version); // // @Message(id = 104, value = "Could not find marshaller factory for marshaller strategy %s") // RuntimeException failedToFindMarshallerFactoryForStrategy(String marshallerStrategy); // @Message(id = 105, value = "%s is not an Jakarta Enterprise Beans component") // IllegalArgumentException notAnEJBComponent(Component component); // @Message(id = 106, value = "Could not load method param class %s of timeout method") // RuntimeException failedToLoadTimeoutMethodParamClass(@Cause Exception cause, String className); @Message(id = 107, value = "Timer invocation failed, invoker is not started") IllegalStateException timerInvocationFailedDueToInvokerNotBeingStarted(); // @Message(id = 108, value = "Could not load timer with id %s") // NoSuchObjectLocalException timerNotFound(String timerId); @Message(id = 109, value = "Invalid value for second: %s") IllegalArgumentException invalidValueForSecondInScheduleExpression(String value); @Message(id = 110, value = "Timer invocation failed, transaction rolled back") TimerTransactionRolledBackException timerInvocationRolledBack(); @LogMessage(level = INFO) @Message(id = 111, value = "No jndi bindings will be created for Jakarta Enterprise Beans %s since no views are exposed") void noJNDIBindingsForSessionBean(String beanName); // @LogMessage(level = WARN) // @Message(id = 112, value = "Could not send cluster formation message to the client on channel %s") // void failedToSendClusterFormationMessageToClient(@Cause Exception e, Channel channel); // // @LogMessage(level = WARN) // @Message(id = 113, value = "Could not send module availability notification of module %s on channel %s") // void failedToSendModuleAvailabilityMessageToClient(@Cause Exception e, DeploymentModuleIdentifier deploymentId, Channel channel); // // @LogMessage(level = WARN) // @Message(id = Message.INHERIT, value = "Could not send initial module availability report to channel %s") // void failedToSendModuleAvailabilityMessageToClient(@Cause Exception e, Channel channel); // // @LogMessage(level = WARN) // @Message(id = 114, value = "Could not send module un-availability notification of module %s on channel %s") // void failedToSendModuleUnavailabilityMessageToClient(@Cause Exception e, DeploymentModuleIdentifier deploymentId, Channel channel); // // @LogMessage(level = WARN) // @Message(id = 115, value = "Could not send a cluster formation message for cluster: %s to the client on channel %s") // void failedToSendClusterFormationMessageToClient(@Cause Exception e, String clusterName, Channel channel); // // @LogMessage(level = WARN) // @Message(id = 116, value = "Could not write a new cluster node addition message to channel %s") // void failedToSendClusterNodeAdditionMessageToClient(@Cause Exception e, Channel channel); // // @LogMessage(level = WARN) // @Message(id = 117, value = "Could not write a cluster node removal message to channel %s") // void failedToSendClusterNodeRemovalMessageToClient(@Cause Exception e, Channel channel); @LogMessage(level = WARN) @Message(id = 118, value = "[Enterprise Beans 3.1 spec, section 4.9.2] Session bean implementation class MUST NOT be a interface - %s is an interface, hence won't be considered as a session bean") void sessionBeanClassCannotBeAnInterface(String className); @LogMessage(level = WARN) @Message(id = 119, value = "[Enterprise Beans 3.1 spec, section 4.9.2] Session bean implementation class MUST be public, not abstract and not final - %s won't be considered as a session bean, since it doesn't meet that requirement") void sessionBeanClassMustBePublicNonAbstractNonFinal(String className); @LogMessage(level = WARN) @Message(id = 120, value = "[Enterprise Beans 3.1 spec, section 5.6.2] Message driven bean implementation class MUST NOT be a interface - %s is an interface, hence won't be considered as a message driven bean") void mdbClassCannotBeAnInterface(String className); @LogMessage(level = WARN) @Message(id = 121, value = "[Enterprise Beans 3.1 spec, section 5.6.2] Message driven bean implementation class MUST be public, not abstract and not final - %s won't be considered as a message driven bean, since it doesn't meet that requirement") void mdbClassMustBePublicNonAbstractNonFinal(String className); // @LogMessage(level = WARN) // @Message(id = 122, value = "Method %s was a async method but the client could not be informed about the same. This will mean that the client might block till the method completes") // void failedToSendAsyncMethodIndicatorToClient(@Cause Throwable t, Method invokedMethod); // // @LogMessage(level = WARN) // @Message(id = 123, value = "Asynchronous invocations are only supported on session beans. Bean class %s is not a session bean, invocation on method %s will have no asynchronous semantics") // void asyncMethodSupportedOnlyForSessionBeans(Class<?> beanClass, Method invokedMethod); // // @LogMessage(level = INFO) // @Message(id = 124, value = "Cannot add cluster node %s to cluster %s since none of the client mappings matched for addresses %s") // void cannotAddClusterNodeDueToUnresolvableClientMapping(final String nodeName, final String clusterName, final Object bindings); @Message(id = 125, value = "Could not create an instance of deployment node selector %s") DeploymentUnitProcessingException failedToCreateDeploymentNodeSelector(@Cause Exception e, String deploymentNodeSelectorClassName); // @Message(id = 126, value = "Could not lookup service %s") // IllegalStateException serviceNotFound(ServiceName serviceName); @Message(id = 127, value = "Jakarta Enterprise Beans %s of type %s must have public default constructor") DeploymentUnitProcessingException ejbMustHavePublicDefaultConstructor(String componentName, String componentClassName); @Message(id = 128, value = "Jakarta Enterprise Beans %s of type %s must not be inner class") DeploymentUnitProcessingException ejbMustNotBeInnerClass(String componentName, String componentClassName); @Message(id = 129, value = "Jakarta Enterprise Beans %s of type %s must be declared public") DeploymentUnitProcessingException ejbMustBePublicClass(String componentName, String componentClassName); @Message(id = 130, value = "Jakarta Enterprise Beans %s of type %s must not be declared final") DeploymentUnitProcessingException ejbMustNotBeFinalClass(String componentName, String componentClassName); @LogMessage(level = WARN) @Message(id = 131, value = "Jakarta Enterprise Beans %s should not have a final or static method (%s)") void ejbMethodMustNotBeFinalNorStatic(String ejbName, String methodName); // @Message(id = 131, value = "Jakarta Enterprise Beans client context selector failed due to unavailability of %s service") // IllegalStateException ejbClientContextSelectorUnableToFunctionDueToMissingService(ServiceName serviceName); @Message(id = 132, value = "@PostConstruct method of Jakarta Enterprise Beans singleton %s of type %s has been recursively invoked") IllegalStateException reentrantSingletonCreation(String componentName, String componentClassName); // @Message(id = 133, value = "Failed to read Jakarta Enterprise Beans info") // IOException failedToReadEjbInfo(@Cause Throwable e); // // @Message(id = 134, value = "Failed to read Jakarta Enterprise Beans Locator") // IOException failedToReadEJBLocator(@Cause Throwable e); // // @Message(id = 135, value = "default-security-domain was defined") // String rejectTransformationDefinedDefaultSecurityDomain(); // // @Message(id = 136, value = "default-missing-method-permissions-deny-access was set to true") // String rejectTransformationDefinedDefaultMissingMethodPermissionsDenyAccess(); @Message(id = 137, value = "Only session and message-driven beans with bean-managed transaction demarcation are allowed to access UserTransaction") IllegalStateException unauthorizedAccessToUserTransaction(); // @Message(id = 138, value = "More than one timer found in database with id %s") // RuntimeException moreThanOneTimerFoundWithId(String id); @Message(id = 139, value = "The timer service has been disabled. Please add a <timer-service> entry into the Jakarta Enterprise Beans section of the server configuration to enable it.") String timerServiceIsNotActive(); @Message(id = 140, value = "This Jakarta Enterprise Beans does not have any timeout methods") String ejbHasNoTimerMethods(); @LogMessage(level = ERROR) @Message(id = 141, value = "Exception calling deployment added listener") void deploymentAddListenerException(@Cause Throwable cause); @LogMessage(level = ERROR) @Message(id = 142, value = "Exception calling deployment removal listener") void deploymentRemoveListenerException(@Cause Throwable cause); @LogMessage(level = ERROR) @Message(id = 143, value = "Failed to remove management resources for %s -- %s") void failedToRemoveManagementResources(InstalledComponent component, String cause); @LogMessage(level = INFO) @Message(id = 144, value = "CORBA interface repository for %s: %s") void cobraInterfaceRepository(String repo, String object); @LogMessage(level = ERROR) @Message(id = 145, value = "Cannot unregister EJBHome from CORBA naming service") void cannotUnregisterEJBHomeFromCobra(@Cause Throwable cause); @LogMessage(level = ERROR) @Message(id = 146, value = "Cannot deactivate home servant") void cannotDeactivateHomeServant(@Cause Throwable cause); @LogMessage(level = ERROR) @Message(id = 147, value = "Cannot deactivate bean servant") void cannotDeactivateBeanServant(@Cause Throwable cause); // @LogMessage(level = ERROR) // @Message(id = 148, value = "Exception on channel %s from message %s") // void exceptionOnChannel(@Cause Throwable cause, Channel channel, MessageInputStream inputStream); // // @LogMessage(level = ERROR) // @Message(id = 149, value = "Error invoking method %s on bean named %s for appname %s modulename %s distinctname %s") // void errorInvokingMethod(@Cause Throwable cause, Method invokedMethod, String beanName, String appName, String moduleName, String distinctName); @LogMessage(level = ERROR) @Message(id = 150, value = "Could not write method invocation failure for method %s on bean named %s for appname %s modulename %s distinctname %s due to") void couldNotWriteMethodInvocation(@Cause Throwable cause, Method invokedMethod, String beanName, String appName, String moduleName, String distinctName); @LogMessage(level = ERROR) @Message(id = 151, value = "Exception while generating session id for component %s with invocation %s") void exceptionGeneratingSessionId(@Cause Throwable cause, String componentName, Object invocationInformation); // @LogMessage(level = ERROR) // @Message(id = 152, value = "Could not write out message to channel due to") // void couldNotWriteOutToChannel(@Cause Throwable cause); // // @LogMessage(level = ERROR) // @Message(id = 153, value = "Could not write out invocation success message to channel due to") // void couldNotWriteInvocationSuccessMessage(@Cause Throwable cause); // // @LogMessage(level = WARN) // @Message(id = 154, value = "Received unsupported message header 0x%x on channel %s") // void unsupportedMessageHeader(int header, Channel channel); // // @LogMessage(level = ERROR) // @Message(id = 155, value = "Error during transaction management of transaction id %s") // void errorDuringTransactionManagement(@Cause Throwable cause, XidTransactionID id); // // @LogMessage(level = WARN) // @Message(id = 156, value = "%s retrying %d") // void retrying(String message, int count); @LogMessage(level = ERROR) @Message(id = 157, value = "Failed to get status") void failedToGetStatus(@Cause Throwable cause); @LogMessage(level = ERROR) @Message(id = 158, value = "Failed to rollback") void failedToRollback(@Cause Throwable cause); @LogMessage(level = ERROR) @Message(id = 159, value = "BMT stateful bean '%s' did not complete user transaction properly status=%s") void transactionNotComplete(String componentName, String status); // @LogMessage(level = ERROR) // @Message(id = 160, value = "Cannot delete cache %s %s, will be deleted on exit") // void cannotDeleteCacheFile(String fileType, String fileName); @LogMessage(level = WARN) @Message(id = 161, value = "Failed to reinstate timer '%s' (id=%s) from its persistent state") void timerReinstatementFailed(String timedObjectId, String timerId, @Cause Throwable cause); /** * Logs a waring message indicating an overlapped invoking timeout for timer */ @LogMessage(level = WARN) @Message(id = 162, value = "A previous execution of timer %s is being retried, skipping this scheduled execution at: %s") void skipInvokeTimeoutDuringRetry(Timer timer, Date scheduledTime); @LogMessage(level = ERROR) @Message(id = 163, value = "Cannot create table for timer persistence") void couldNotCreateTable(@Cause SQLException e); @LogMessage(level = ERROR) @Message(id = 164, value = "Exception running timer task for timer %s on Jakarta Enterprise Beans %s") void exceptionRunningTimerTask(Timer timer, String timedObjectId, @Cause Exception e); // @LogMessage(level = ERROR) // @Message(id = 165, value = "Error during transaction recovery") // void errorDuringTransactionRecovery(@Cause Throwable cause); @LogMessage(level = WARN) @Message(id = 166, value = "The @%s annotation is deprecated and will be ignored.") void deprecatedAnnotation(String annotation); @LogMessage(level = WARN) @Message(id = 167, value = "The <%2$s xmlns=\"%1$s\"/> element will be ignored.") void deprecatedNamespace(String namespace, String element); /** * Creates an exception indicating it could not find the Jakarta Enterprise Beans with specific id * * @param sessionId Session id * @return a {@link NoSuchEJBException} for the error. */ @Message(id = 168, value = "Could not find Jakarta Enterprise Beans with id %s") NoSuchEJBException couldNotFindEjb(String sessionId); /** * Creates an exception indicating it a component was not set on the InterceptorContext * * @param context the context. * @return a {@link IllegalStateException} for the error. */ @Message(id = 169, value = "Component not set in InterceptorContext: %s") IllegalStateException componentNotSetInInterceptor(InterceptorContext context); /** * Creates an exception indicating the method was called with null in the name * * @return a {@link IllegalArgumentException} for the error. */ @Message(id = 170, value = "Method name cannot be null") IllegalArgumentException methodNameIsNull(); /** * Creates an exception indicating the bean home interface was not set * * @return a {@link IllegalStateException} for the error. */ @Message(id = 171, value = "Bean %s does not have a Home interface") IllegalStateException beanHomeInterfaceIsNull(String componentName); /** * Creates an exception indicating the bean local home interface was not set * * @return a {@link IllegalStateException} for the error. */ @Message(id = 172, value = "Bean %s does not have a Local Home interface") IllegalStateException beanLocalHomeInterfaceIsNull(String componentName); /** * Creates an exception indicating the getRollBackOnly was called on none container-managed transaction * * @return a {@link IllegalStateException} for the error. */ @Message(id = 173, value = "Enterprise Beans 3.1 FR 13.6.1 Only beans with container-managed transaction demarcation " + "can use getRollbackOnly.") IllegalStateException failToCallgetRollbackOnly(); /** * Creates an exception indicating the getRollBackOnly not allowed without a transaction * * @return a {@link IllegalStateException} for the error. */ @Message(id = 174, value = "getRollbackOnly() not allowed without a transaction.") IllegalStateException failToCallgetRollbackOnlyOnNoneTransaction(); /** * Creates an exception indicating the call getRollBackOnly not allowed after transaction is completed * * @return a {@link IllegalStateException} for the error. */ @Message(id = 175, value = "getRollbackOnly() not allowed after transaction is completed (EJBTHREE-1445)") IllegalStateException failToCallgetRollbackOnlyAfterTxcompleted(); // /** // * Creates an exception indicating the call isBeanManagedTransaction is not allowed without bean-managed transaction // * // * @return a {@link IllegalStateException} for the error. // */ // @Message(id = 176, value = "Enterprise Beans 3.1 FR 4.3.3 & 5.4.5 Only beans with bean-managed transaction demarcation can use this method.") // IllegalStateException failToCallIsBeanManagedTransaction(); /** * Creates an exception indicating the call lookup was call with an empty jndi name * * @return a {@link IllegalStateException} for the error. */ @Message(id = 177, value = "jndi name cannot be null during lookup") IllegalArgumentException jndiNameCannotBeNull(); /** * Creates an exception indicating the NamespaceContextSelector was not set * * @param name the jndi name * @return a {@link IllegalStateException} for the error. */ @Message(id = 178, value = "No NamespaceContextSelector available, cannot lookup %s") IllegalArgumentException noNamespaceContextSelectorAvailable(String name); /** * Creates an exception indicating the NamespaceContextSelector was not set * * @param name the jndi name * @param e cause of the exception * @return a {@link RuntimeException} for the error. */ @Message(id = 179, value = " Could not lookup jndi name: %s") RuntimeException failToLookupJNDI(String name, @Cause Throwable e); /** * Creates an exception indicating the namespace was wrong * * @param name the jndi name * @return a {@link IllegalArgumentException} for the error. */ @Message(id = 180, value = "Cannot lookup jndi name: %s since it" + " doesn't belong to java:app, java:module, java:comp or java:global namespace") IllegalArgumentException failToLookupJNDINameSpace(String name); /** * Creates an exception indicating it failed to lookup the namespace * * @param namespaceContextSelector selector for the namespace context * @param jndiContext the jndi context it was looked up on * @param ne cause of the exception * @return a {@link IllegalArgumentException} for the error. */ @Message(id = 181, value = "Could not lookup jndi name: %s in context: %s") IllegalArgumentException failToLookupStrippedJNDI(NamespaceContextSelector namespaceContextSelector, Context jndiContext, @Cause Throwable ne); /** * Creates an exception indicating setRollBackOnly was called on none CMB * * @return a {@link IllegalStateException} for the error. */ @Message(id = 182, value = "Enterprise Beans 3.1 FR 13.6.1 Only beans with container-managed transaction demarcation " + "can use setRollbackOnly.") IllegalStateException failToCallSetRollbackOnlyOnNoneCMB(); /** * Creates an exception indicating setRollBackOnly was without a transaction * * @return a {@link IllegalStateException} for the error. */ @Message(id = 183, value = "setRollbackOnly() not allowed without a transaction.") IllegalStateException failToCallSetRollbackOnlyWithNoTx(); /** * Creates an exception indicating EjbJarConfiguration cannot be null * * @return a {@link IllegalArgumentException} for the error. */ @Message(id = 184, value = "EjbJarConfiguration cannot be null") IllegalArgumentException EjbJarConfigurationIsNull(); /** * Creates an exception indicating the security roles is null * * @return a {@link IllegalArgumentException} for the error. */ @Message(id = 185, value = "Cannot set security roles to null") IllegalArgumentException SecurityRolesIsNull(); // /** // * Creates an exception indicating the classname was null or empty // * // * @return a {@link IllegalArgumentException} for the error. // */ // @Message(id = 186, value = "Classname cannot be null or empty: %s") // IllegalArgumentException classnameIsNull(String className); // // /** // * Creates an exception indicating it can't set null roles for the class // * // * @return a {@link IllegalArgumentException} for the error. // */ // @Message(id = 187, value = "Cannot set null roles for class %s") // IllegalArgumentException setRolesForClassIsNull(String className); // // /** // * Creates an exception indicating Jakarta Enterprise Beans method identifier cannot be null while setting roles on method // * // * @return a {@link IllegalArgumentException} for the error. // */ // @Message(id = 188, value = "Jakarta Enterprise Beans method identifier cannot be null while setting roles on method") // IllegalArgumentException ejbMethodIsNull(); // // /** // * Creates an exception indicating roles cannot be null while setting roles on method // * // * @return a {@link IllegalArgumentException} for the error. // */ // @Message(id = 189, value = "Roles cannot be null while setting roles on method: %s") // IllegalArgumentException rolesIsNull(EJBMethodIdentifier ejbMethodIdentifier); // /** // * Creates an exception indicating Jakarta Enterprise Beans method identifier cannot be null while setting roles on view type // * // * @return a {@link IllegalArgumentException} for the error. // */ // @Message(id = 190, value = "Jakarta Enterprise Beans method identifier cannot be null while setting roles on view type: %s") // IllegalArgumentException ejbMethodIsNullForViewType(MethodInterfaceType viewType); // /** // * Creates an exception indicating roles cannot be null while setting roles on view type // * // * @param viewType // * @return a {@link IllegalArgumentException} for the error. // */ // @Message(id = 191, value = "Roles cannot be null while setting roles on view type: %s") // IllegalArgumentException rolesIsNullOnViewType(final MethodInterfaceType viewType); // /** // * Creates an exception indicating roles cannot be null while setting roles on view type and method" // * // * @param viewType // * @return a {@link IllegalArgumentException} for the error. // */ // @Message(id = 192, value = "Roles cannot be null while setting roles on view type: %s and method: %s") // IllegalArgumentException rolesIsNullOnViewTypeAndMethod(MethodInterfaceType viewType, EJBMethodIdentifier ejbMethodIdentifier); /** * Creates an exception indicating it cannot link from a null or empty security role * * @param fromRole role it link from * @return a {@link IllegalArgumentException} for the error. */ @Message(id = 193, value = "Cannot link from a null or empty security role: %s") IllegalArgumentException failToLinkFromEmptySecurityRole(String fromRole); /** * Creates an exception indicating it cannot link to a null or empty security role: * * @param toRole role it link to * @return a {@link IllegalArgumentException} for the error. */ @Message(id = 194, value = "Cannot link to a null or empty security role: %s") IllegalArgumentException failToLinkToEmptySecurityRole(String toRole); /** * Creates an exception indicating that the EjbJarConfiguration was not found as an attachment in deployment unit * * @return a {@link DeploymentUnitProcessingException} for the error. */ @Message(id = 195, value = "EjbJarConfiguration not found as an attachment in deployment unit: %s") DeploymentUnitProcessingException ejbJarConfigNotFound(DeploymentUnit deploymentUnit); /** * Creates an exception indicating the component view instance is not available in interceptor context * * @return a {@link IllegalStateException} for the error. */ @Message(id = 196, value = "ComponentViewInstance not available in interceptor context: %s") IllegalStateException componentViewNotAvailableInContext(InterceptorContext context); // /** // * Creates an exception indicating it fail to call the timeout method // * // * @param method // * @return a {@link RuntimeException} for the error. // */ // @Message(id = 197, value = "Unknown timeout method %s") // RuntimeException failToCallTimeOutMethod(Method method); // // /** // * Creates an exception indicating timeout method was not set for the component // * // * @param componentName name of the component // * @return a {@link IllegalArgumentException} for the error. // */ // @Message(id = 198, value = "Component %s does not have a timeout method") // IllegalArgumentException componentTimeoutMethodNotSet(String componentName); /** * Creates an exception indicating no resource adapter registered with resource adapter name * * @param resourceAdapterName name of the RA * @return a {@link IllegalStateException} for the error. */ @Message(id = 199, value = "No resource adapter registered with resource adapter name %s") IllegalStateException unknownResourceAdapter(String resourceAdapterName); // /** // * Creates an exception indicating multiple resource adapter was registered // * // * @param resourceAdapterName name of the RA // * @return a {@link IllegalStateException} for the error. // */ // @Message(id = 200, value = "found more than one RA registered as %s") // IllegalStateException multipleResourceAdapterRegistered(String resourceAdapterName); // /** // * Creates an exception indicating security is not enabled // * // * @return a {@link UnsupportedOperationException} for the error. // */ // @Message(id = 201, value = "Security is not enabled") // UnsupportedOperationException securityNotEnabled(); /** * Creates an exception indicating it fail to complete task before time out * * @return a {@link TimeoutException} for the error. */ @Message(id = 202, value = "Task did not complete in %s %S") TimeoutException failToCompleteTaskBeforeTimeOut(long timeout, TimeUnit unit); /** * Creates an exception indicating the task was cancelled * * @return a {@link TimeoutException} for the error. */ @Message(id = 203, value = "Task was cancelled") CancellationException taskWasCancelled(); // /** // * Creates an exception indicating that it could not resolve ejbRemove method for interface method on Jakarta Enterprise Beans // * // * @return a {@link DeploymentUnitProcessingException} for the error. // */ // @Message(id = 204, value = "Could not resolve ejbRemove method for interface method on Jakarta Enterprise Beans %s") // DeploymentUnitProcessingException failToResolveEjbRemoveForInterface(String ejbName); // // /** // * Creates an exception indicating that it could not resolve corresponding method for home interface method on Jakarta Enterprise Beans // * // * @return a {@link DeploymentUnitProcessingException} for the error. // */ // @Message(id = 205, value = "Could not resolve corresponding %s for home interface method %s on Jakarta Enterprise Beans %s") // DeploymentUnitProcessingException failToResolveMethodForHomeInterface(String ejbMethodName, Method method, String ejbName); /** * Creates an exception indicating the method is not implemented * * @return a {@link IllegalStateException} for the error. */ @Message(id = 206, value = "Not implemented yet") IllegalStateException methodNotImplemented(); // /** // * Creates an exception indicating a class was attached to a view that is not an EJBObject or an EJBLocalObject // * // * @param aClass the attached class // * @return a {@link RuntimeException} for the error. // */ // @Message(id = 207, value = "%s was attached to a view that is not an EJBObject or an EJBLocalObject") // RuntimeException classAttachToViewNotEjbObject(Class<?> aClass); // // /** // * Creates an exception indicating invocation was not associated with an instance, primary key was null, instance may have been removed // * // * @return a {@link NoSuchEJBException} for the error. // */ // @Message(id = 208, value = "Invocation was not associated with an instance, primary key was null, instance may have been removed") // NoSuchEJBException invocationNotAssociated(); // // /** // * Creates an exception indicating could not re-acquire lock for non-reentrant instance // * // * @return a {@link EJBException} for the error. // */ // @Message(id = 209, value = "Could not re-acquire lock for non-reentrant instance %s") // EJBException failToReacquireLockForNonReentrant(ComponentInstance privateData); // // /** // * Creates an exception indicating could not Could not find entity from method // * // * @return a {@link ObjectNotFoundException} for the error. // */ // @Message(id = 210, value = "Could not find entity from %s with params %s") // ObjectNotFoundException couldNotFindEntity(Method finderMethod, String s); // // // /** // * Creates an exception indicating an invocation was not associated with an instance, primary key was null, instance may have been removed // * // * @return a {@link NoSuchEJBException} for the error. // */ // @Message(id = 211, value = "Invocation was not associated with an instance, primary key was null, instance may have been removed") // NoSuchEJBException primaryKeyIsNull(); // // /** // * Creates an exception indicating an instance has been removed // * // * @return a {@link NoSuchEJBException} for the error. // */ // @Message(id = 212, value = "Instance of %s with primary key %s has been removed") // NoSuchEntityException instanceWasRemoved(String componentName, Object primaryKey); /** * Creates an exception indicating unexpected component * * @return a {@link IllegalStateException} for the error. */ @Message(id = 213, value = "Unexpected component: %s component Expected %s") IllegalStateException unexpectedComponent(Component component, Class<?> entityBeanComponentClass); /** * Creates an exception indicating EjbJarConfiguration hasn't been set * * @return a {@link IllegalStateException} for the error. */ @Message(id = 214, value = "EjbJarConfiguration hasn't been set in %s Cannot create component create service for Jakarta Enterprise Beans %S") IllegalStateException ejbJarConfigNotBeenSet(ComponentCreateServiceFactory serviceFactory, String componentName); // /** // * Creates an exception indicating cannot find any resource adapter service for resource adapter // * // * @return a {@link IllegalStateException} for the error. // */ // @Message(id = 215, value = "Cannot find any resource adapter service for resource adapter %s") // IllegalStateException failToFindResourceAdapter(String resourceAdapterName); // // /** // * Creates an exception indicating No resource-adapter has been specified // * // * @return a {@link IllegalStateException} for the error. // */ // @Message(id = 216, value = "No resource-adapter has been specified for %s") // IllegalStateException resourceAdapterNotSpecified(MessageDrivenComponent messageDrivenComponent); // // /** // * Creates an exception indicating poolConfig cannot be null // * // * @return a {@link IllegalStateException} for the error. // */ // @Message(id = 217, value = "PoolConfig cannot be null") // IllegalArgumentException poolConfigIsNull(); /** * Creates an exception indicating poolConfig cannot be null or empty * * @return a {@link IllegalStateException} for the error. */ @Message(id = 218, value = "PoolConfig cannot be null or empty") IllegalStateException poolConfigIsEmpty(); // /** // * Creates an exception indicating cannot invoke method in a session bean lifecycle method" // * // * @return a {@link IllegalStateException} for the error. // */ // @Message(id = 219, value = "Cannot invoke %s in a session bean lifecycle method") // IllegalStateException failToInvokeMethodInSessionBeanLifeCycle(String method); /** * Creates an exception indicating can't add view class as local view since it's already marked as remote view for bean * * @return a {@link IllegalStateException} for the error. */ @Message(id = 220, value = "[Enterprise Beans 3.1 spec, section 4.9.7] - Can't add view class: %s as local view since it's already marked as remote view for bean: %s") IllegalStateException failToAddClassToLocalView(String viewClassName, String ejbName); /** * Creates an exception indicating business interface type cannot be null * * @return a {@link IllegalStateException} for the error. */ @Message(id = 221, value = "Business interface type cannot be null") IllegalStateException businessInterfaceIsNull(); /** * Creates an exception indicating Bean component does not have an ejb object * * @return a {@link IllegalStateException} for the error. */ @Message(id = 222, value = "Bean %s does not have an %s") IllegalStateException beanComponentMissingEjbObject(String componentName, String ejbLocalObject); /** * Creates an exception indicating Jakarta Enterprise Beans 3.1 FR 13.6.2.9 getRollbackOnly is not allowed with SUPPORTS attribute * * @return a {@link IllegalStateException} for the error. */ @Message(id = 223, value = "Jakarta Enterprise Beans 3.1 FR 13.6.2.9 getRollbackOnly is not allowed with SUPPORTS attribute") IllegalStateException getRollBackOnlyIsNotAllowWithSupportsAttribute(); /** * Creates an exception indicating not a business method. Do not call non-public methods on Jakarta Enterprise Beans's * * @return a {@link EJBException} for the error. */ @Message(id = 224, value = "Not a business method %s. Do not call non-public methods on Jakarta Enterprise Beans's") EJBException failToCallBusinessOnNonePublicMethod(Method method); /** * Creates an exception indicating component instance isn't available for invocation * * @return a {@link Exception} for the error. */ @Message(id = 225, value = "Component instance isn't available for invocation: %s") Exception componentInstanceNotAvailable(InterceptorContext interceptorContext); // /** // * Creates an exception indicating Component with component class isn't a singleton component // * // * @return a {@link IllegalArgumentException} for the error. // */ // @Message(id = 226, value = "Component %s with component class: %s isn't a singleton component") // IllegalArgumentException componentNotSingleton(Component component, Class<?> componentClass); // // /** // * Creates an exception indicating a SingletonComponent cannot be null // * // * @return a {@link IllegalArgumentException} for the error. // */ // @Message(id = 227, value = "SingletonComponent cannot be null") // IllegalArgumentException singletonComponentIsNull(); /** * Creates an exception indicating could not obtain lock within the specified time * * @return a {@link ConcurrentAccessTimeoutException} for the error. */ @Message(id = 228, value = "Enterprise Beans 3.1 FR 4.3.14.1 concurrent access timeout on %s - could not obtain lock within %s %s") ConcurrentAccessTimeoutException failToObtainLock(String ejb, long value, TimeUnit timeUnit); // /** // * Creates an exception indicating it was unable to find method // * // * @return a {@link RuntimeException} for the error. // */ // @Message(id = 229, value = "Unable to find method %s %s") // RuntimeException failToFindMethod(String name, String s); // // /** // * Creates an exception indicating the timerService is not supported for Stateful session bean // * // * @return a {@link IllegalStateException} for the error. // */ // @Message(id = 230, value = "TimerService is not supported for Stateful session bean %s") // IllegalStateException timerServiceNotSupportedForSFSB(String componentName); // // /** // * Creates an exception indicating session id cannot be null // * // * @return a {@link IllegalArgumentException} for the error. // */ // @Message(id = 231, value = "Session id cannot be null") // IllegalArgumentException sessionIdIsNull(); // // /** // * Creates an exception indicating stateful component cannot be null // * // * @return a {@link IllegalArgumentException} for the error. // */ // @Message(id = 232, value = "Stateful component cannot be null") // IllegalArgumentException statefulComponentIsNull(); // // /** // * Creates an exception indicating it could not create session for Stateful bean // * // * @return a {@link RuntimeException} for the error. // */ // @Message(id = 233, value = "Could not create session for Stateful bean %s") // RuntimeException failToCreateStatefulSessionBean(String beanName, @Cause Throwable e); /** * Creates an exception indicating session id hasn't been set for stateful component * * @return a {@link IllegalArgumentException} for the error. */ @Message(id = 234, value = "Session id hasn't been set for stateful component: %s") IllegalStateException statefulSessionIdIsNull(String componentName); /** * Creates an exception indicating @Remove method cannot be null * * @return a {@link IllegalArgumentException} for the error. */ @Message(id = 235, value = "@Remove method identifier cannot be null") IllegalArgumentException removeMethodIsNull(); /** * Creates an exception indicating Component with component specified class: isn't a stateful component * * @return a {@link IllegalArgumentException} for the error. */ @Message(id = 236, value = "Component %s with component class: %s%n isn't a %s component") IllegalArgumentException componentNotInstanceOfSessionComponent(Component component, Class<?> componentClass, String type); /** * Creates an exception indicating both methodIntf and className are set * * @return a {@link IllegalArgumentException} for the error. */ @Message(id = 237, value = "both methodIntf and className are set on %s") IllegalArgumentException bothMethodIntAndClassNameSet(String componentName); /** * Creates an exception indicating Enterprise Beans 3.1 PFD2 4.8.5.1.1 upgrading from read to write lock is not allowed * * @return a {@link IllegalLoopbackException} for the error. */ @Message(id = 238, value = "Enterprise Beans 3.1 PFD2 4.8.5.1.1 upgrading from read to write lock is not allowed") IllegalLoopbackException failToUpgradeToWriteLock(); /** * Creates an exception indicating component cannot be null * * @return a {@link IllegalArgumentException} for the error. */ @Message(id = 239, value = "%s cannot be null") IllegalArgumentException componentIsNull(String name); /** * Creates an exception indicating Invocation context cannot be processed because it's not applicable for a method invocation * * @return a {@link IllegalArgumentException} for the error. */ @Message(id = 240, value = "Invocation context: %s cannot be processed because it's not applicable for a method invocation") IllegalArgumentException invocationNotApplicableForMethodInvocation(InvocationContext invocationContext); /** * Creates an exception Enterprise Beans 3.1 PFD2 4.8.5.5.1 concurrent access timeout on invocation - could not obtain lock within * * @return a {@link ConcurrentAccessTimeoutException} for the error. */ @Message(id = 241, value = "Enterprise Beans 3.1 PFD2 4.8.5.5.1 concurrent access timeout on %s - could not obtain lock within %s") ConcurrentAccessTimeoutException concurrentAccessTimeoutException(String ejb, String s); /** * Creates an exception indicating Illegal lock type for component * * @return a {@link IllegalStateException} for the error. */ @Message(id = 242, value = "Illegal lock type %s on %s for component %s") IllegalStateException failToObtainLockIllegalType(LockType lockType, Method method, SingletonComponent lockableComponent); /** * Creates an exception indicating the inability to call the method as something is missing for the invocation. * * @param methodName the name of the method. * @param missing the missing type. * @return a {@link IllegalStateException} for the error. */ @Message(id = 243, value = "Cannot call %s, no %s is present for this invocation") IllegalStateException cannotCall(String methodName, String missing); /** * Creates an exception indicating No asynchronous invocation in progress * * @return a {@link IllegalStateException} for the error. */ @Message(id = 244, value = "No asynchronous invocation in progress") IllegalStateException noAsynchronousInvocationInProgress(); // /** // * Creates an exception indicating method call is not allowed while dependency injection is in progress // * // * @return a {@link IllegalStateException} for the error. // */ // @Message(id = 245, value = "%s is not allowed while dependency injection is in progress") // IllegalStateException callMethodNotAllowWhenDependencyInjectionInProgress(String method); // /** // * Creates an exception indicating the method is deprecated // * // * @return a {@link UnsupportedOperationException} for the error. // */ // @Message(id = 246, value = "%s is deprecated") // UnsupportedOperationException isDeprecated(String getEnvironment); // /** // * Creates an exception indicating getting parameters is not allowed on lifecycle callbacks // * // * @return a {@link IllegalStateException} for the error. // */ // @Message(id = 247, value = "Getting parameters is not allowed on lifecycle callbacks") // IllegalStateException gettingParametersNotAllowLifeCycleCallbacks(); // // /** // * Creates an exception indicating method is not allowed in lifecycle callbacks (Enterprise Beans 3.1 FR 4.6.1, 4.7.2, 4.8.6, 5.5.1) // * // * @return a {@link IllegalStateException} for the error. // */ // @Message(id = 248, value = "%s is not allowed in lifecycle callbacks (Enterprise Beans 3.1 FR 4.6.1, 4.7.2, 4.8.6, 5.5.1)") // IllegalStateException notAllowedInLifecycleCallbacks(String name); // // /** // * Creates an exception indicating Setting parameters is not allowed on lifecycle callbacks // * // * @return a {@link IllegalStateException} for the error. // */ // @Message(id = 249, value = "Setting parameters is not allowed on lifecycle callbacks") // IllegalStateException setParameterNotAllowOnLifeCycleCallbacks(); // // /** // * Creates an exception indicating Got wrong number of arguments // * // * @return a {@link IllegalArgumentException} for the error. // */ // @Message(id = 250, value = "Got wrong number of arguments, expected %s, got %s on %s") // IllegalArgumentException wrongNumberOfArguments(int length, int length1, Method method); // // /** // * Creates an exception indicating parameter has the wrong type // * // * @return a {@link IllegalArgumentException} for the error. // */ // @Message(id = 251, value = "Parameter %s has the wrong type, expected %, got %s on %s") // IllegalArgumentException wrongParameterType(int i, Class<?> expectedType, Class<?> actualType, Method method); // // /** // * Creates an exception indicating No current invocation context available // * // * @return a {@link IllegalStateException} for the error. // */ // @Message(id = 252, value = "No current invocation context available") // IllegalStateException noCurrentContextAvailable(); // /** // * Creates an exception indicating the method should be overridden // * // * @return a {@link IllegalStateException} for the error. // */ // @Message(id = 253, value = "Should be overridden") // IllegalStateException shouldBeOverridden(); // /** // * Creates an exception indicating could not find session bean with name // * // * @return a {@link DeploymentUnitProcessingException} for the error. // */ // @Message(id = 254, value = "Could not find session bean with name %s") // DeploymentUnitProcessingException couldNotFindSessionBean(String beanName); /** * Creates an exception indicating <role-name> cannot be null or empty in <security-role-ref> for bean * * @return a {@link DeploymentUnitProcessingException} for the error. */ @Message(id = 255, value = "<role-name> cannot be null or empty in <security-role-ref>%nfor bean: %s") DeploymentUnitProcessingException roleNamesIsNull(String ejbName); /** * Creates an exception indicating Default interceptors cannot specify a method to bind to in ejb-jar.xml * * @return a {@link DeploymentUnitProcessingException} for the error. */ @Message(id = 256, value = "Default interceptors cannot specify a method to bind to in ejb-jar.xml") DeploymentUnitProcessingException defaultInterceptorsNotBindToMethod(); // /** // * Creates an exception indicating Could not load component class // * // * @return a {@link DeploymentUnitProcessingException} for the error. // */ // @Message(id = 257, value = "Could not load component class %s") // DeploymentUnitProcessingException failToLoadComponentClass(String componentClassName); /** * Creates an exception indicating Two ejb-jar.xml bindings for %s specify an absolute order * * @return a {@link DeploymentUnitProcessingException} for the error. */ @Message(id = 258, value = "Two ejb-jar.xml bindings for %s specify an absolute order") DeploymentUnitProcessingException twoEjbBindingsSpecifyAbsoluteOrder(String component); /** * Creates an exception indicating Could not find method specified referenced in ejb-jar.xml * * @return a {@link DeploymentUnitProcessingException} for the error. */ @Message(id = 259, value = "Could not find method %s.%s referenced in ejb-jar.xml") DeploymentUnitProcessingException failToFindMethodInEjbJarXml(String name, String methodName); /** * Creates an exception indicating More than one method found on class referenced in ejb-jar.xml. Specify the parameter types to resolve the ambiguity * * @return a {@link DeploymentUnitProcessingException} for the error. */ @Message(id = 260, value = "More than one method %s found on class %s referenced in ejb-jar.xml. Specify the parameter types to resolve the ambiguity") DeploymentUnitProcessingException multipleMethodReferencedInEjbJarXml(String methodName, String name); /** * Creates an exception indicating could not find method with parameter types referenced in ejb-jar.xml * * @return a {@link DeploymentUnitProcessingException} for the error. */ @Message(id = 261, value = "Could not find method %s.%s with parameter types %s referenced in ejb-jar.xml") DeploymentUnitProcessingException failToFindMethodWithParameterTypes(String name, String methodName, MethodParametersMetaData methodParams); /** * Creates an exception indicating could not load component class * * @return a {@link DeploymentUnitProcessingException} for the error. */ @Message(id = 262, value = "Could not load component class for component %s") DeploymentUnitProcessingException failToLoadComponentClass(@Cause Throwable t, String componentName); // /** // * Creates an exception indicating Could not load Jakarta Enterprise Beans view class // * // * @return a {@link RuntimeException} for the error. // */ // @Message(id = 263, value = "Could not load Jakarta Enterprise Beans view class ") // RuntimeException failToLoadEjbViewClass(@Cause Throwable e); /** * Creates an exception indicating Could not merge data * * @return a {@link DeploymentUnitProcessingException} for the error. */ @Message(id = 264, value = "Could not merge data for %s") DeploymentUnitProcessingException failToMergeData(String componentName, @Cause Throwable e); /** * Creates an exception indicating it could not load Jakarta Enterprise Beans class * * @return a {@link DeploymentUnitProcessingException} for the error. */ @Message(id = 265, value = "Could not load Jakarta Enterprise Beans class %s") DeploymentUnitProcessingException failToLoadEjbClass(String ejbClassName, @Cause Throwable e); /** * Creates an exception indicating only one annotation method is allowed on bean * * @return a {@link RuntimeException} for the error. */ @Message(id = 266, value = "Only one %s method is allowed on bean %s") RuntimeException multipleAnnotationsOnBean(String annotationType, String ejbClassName); /** * Creates an exception indicating it could not determine type of corresponding implied Enterprise Beans 2.x local interface (see Enterprise Beans 3.1 21.4.5) * due to multiple create* methods with different return types on home * * @return a {@link DeploymentUnitProcessingException} for the error. */ @Message(id = 267, value = "Could not determine type of corresponding implied Enterprise Beans 2.x local interface (see Enterprise Beans 3.1 21.4.5)%n due to multiple create* methods with different return types on home %s") DeploymentUnitProcessingException multipleCreateMethod(Class<?> localHomeClass); /** * Creates an exception indicating it Could not find Jakarta Enterprise Beans referenced by @DependsOn annotation * * @return a {@link DeploymentUnitProcessingException} for the error. */ @Message(id = 268, value = "Could not find Jakarta Enterprise Beans %s referenced by @DependsOn annotation in %s") DeploymentUnitProcessingException failToFindEjbRefByDependsOn(String annotationValue, String componentClassName); /** * Creates an exception indicating more than one Jakarta Enterprise Beans called referenced by @DependsOn annotation in Components * * @return a {@link DeploymentUnitProcessingException} for the error. */ @Message(id = 269, value = "More than one Jakarta Enterprise Beans called %s referenced by @DependsOn annotation in %s Components:%s") DeploymentUnitProcessingException failToCallEjbRefByDependsOn(String annotationValue, String componentClassName, Set<ComponentDescription> components); /** * Creates an exception indicating Async method does not return void or Future * * @return a {@link DeploymentUnitProcessingException} for the error. */ @Message(id = 270, value = "Async method %s does not return void or Future") DeploymentUnitProcessingException wrongReturnTypeForAsyncMethod(Method method); /** * Creates an exception indicating it could not load application exception class %s in ejb-jar.xml * * @return a {@link DeploymentUnitProcessingException} for the error. */ @Message(id = 271, value = "Could not load application exception class %s in ejb-jar.xml") DeploymentUnitProcessingException failToLoadAppExceptionClassInEjbJarXml(String exceptionClassName, @Cause Throwable e); /** * Creates an exception indicating the Jakarta Enterprise Beans entity bean implemented TimedObject but has a different * timeout method specified either via annotations or via the deployment descriptor. * * @return an {@link DeploymentUnitProcessingException} for the error. */ @Message(id = 272, value = "Jakarta Enterprise Beans %s entity bean %s implemented TimedObject, but has a different timeout " + "method specified either via annotations or via the deployment descriptor") DeploymentUnitProcessingException invalidEjbEntityTimeout(String versionId, Class<?> componentClass); /** * Creates an exception indicating component does not have an Enterprise Beans 2.x local interface * * @return an {@link RuntimeException} for the error. */ @Message(id = 273, value = "%s does not have an Enterprise Beans 2.x local interface") RuntimeException invalidEjbLocalInterface(String componentName); /** * Creates an exception indicating Local Home not allowed * * @return an {@link DeploymentUnitProcessingException} for the error. */ @Message(id = 274, value = "Local Home not allowed for %s") DeploymentUnitProcessingException localHomeNotAllow(EJBComponentDescription description); /** * Creates an exception indicating Could not resolve corresponding ejbCreate or @Init method for home interface method on Jakarta Enterprise Beans * * @return an {@link DeploymentUnitProcessingException} for the error. */ @Message(id = 275, value = "Could not resolve corresponding ejbCreate or @Init method for home interface method %s on Jakarta Enterprise Beans %s") DeploymentUnitProcessingException failToCallEjbCreateForHomeInterface(Method method, String ejbClassName); /** * Creates an exception indicating EJBComponent has not been set in the current invocation context * * @return an {@link IllegalStateException} for the error. */ @Message(id = 276, value = "EJBComponent has not been set in the current invocation context %s") IllegalStateException failToGetEjbComponent(InterceptorContext currentInvocationContext); // /** // * Creates an exception indicating Value cannot be null // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 277, value = "Value cannot be null") // IllegalArgumentException valueIsNull(); // /** // * Creates an exception indicating Cannot create class from a null schedule expression // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 278, value = "Cannot create %s from a null schedule expression") // IllegalArgumentException invalidScheduleExpression(String name); // /** // * Creates an exception indicating second cannot be null in schedule expression // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 279, value = "Second cannot be null in schedule expression %s") // IllegalArgumentException invalidScheduleExpressionSecond(ScheduleExpression schedule); // /** // * Creates an exception indicating Minute cannot be null in schedule expression // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 280, value = "Minute cannot be null in schedule expression %s") // IllegalArgumentException invalidScheduleExpressionMinute(ScheduleExpression schedule); // /** // * Creates an exception indicating hour cannot be null in schedule expression // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 281, value = "Hour cannot be null in schedule expression %s") // IllegalArgumentException invalidScheduleExpressionHour(ScheduleExpression schedule); // /** // * Creates an exception indicating day-of-month cannot be null in schedule expression // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 282, value = "day-of-month cannot be null in schedule expression %s") // IllegalArgumentException invalidScheduleExpressionDayOfMonth(ScheduleExpression schedule); // /** // * Creates an exception indicating day-of-week cannot be null in schedule expression // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 283, value = "day-of-week cannot be null in schedule expression %s") // IllegalArgumentException invalidScheduleExpressionDayOfWeek(ScheduleExpression schedule); // /** // * Creates an exception indicating Month cannot be null in schedule expression // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 284, value = "Month cannot be null in schedule expression %s") // IllegalArgumentException invalidScheduleExpressionMonth(ScheduleExpression schedule); // /** // * Creates an exception indicating Year cannot be null in schedule expression // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 285, value = "Year cannot be null in schedule expression %s") // IllegalArgumentException invalidScheduleExpressionYear(ScheduleExpression schedule); /** * Creates an exception indicating invalid value of a certain type. * * @param type types of schedule attribute value, e.g., INCREMENT, RANGE, LIST, month, minute, etc * @param value schedule attribute value * @return an {@link IllegalArgumentException} for the error. */ @Message(id = 286, value = "Invalid schedule %s value: %s") IllegalArgumentException invalidScheduleValue(String type, String value); // /** // * Creates an exception indicating Invalid list expression // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 287, value = "Invalid list expression: %s") // IllegalArgumentException invalidListExpression(String list); // /** // * Creates an exception indicating Invalid increment value // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 288, value = "Invalid increment value: %s") // IllegalArgumentException invalidIncrementValue(String value); // /** // * Creates an exception indicating there are no valid seconds for expression // * // * @return an {@link IllegalStateException} for the error. // */ // @Message(id = 289, value = "There are no valid seconds for expression: %s") // IllegalStateException invalidExpressionSeconds(String origValue); // /** // * Creates an exception indicating there are no valid minutes for expression // * // * @return an {@link IllegalStateException} for the error. // */ // @Message(id = 290, value = "There are no valid minutes for expression: %s") // IllegalStateException invalidExpressionMinutes(String origValue); /** * Creates an exception indicating Invalid value it doesn't support values of specified types * * @return an {@link IllegalArgumentException} for the error. */ @Message(id = 291, value = "Invalid value: %s since %s doesn't support values of types %s") IllegalArgumentException invalidScheduleExpressionType(String value, String name, String type); /** * Creates an exception indicating A list value can only contain either a range or an individual value * * @return an {@link IllegalArgumentException} for the error. */ @Message(id = 292, value = "A list value can only contain either a range or an individual value. Invalid value: %s") IllegalArgumentException invalidListValue(String listItem); // /** // * Creates an exception indicating it could not parse schedule expression // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 293, value = "Could not parse: %s in schedule expression") // IllegalArgumentException couldNotParseScheduleExpression(String origValue); /** * Creates an exception indicating invalid value range * * @return an {@link IllegalArgumentException} for the error. */ @Message(id = 294, value = "Invalid value: %s Valid values are between %s and %s") IllegalArgumentException invalidValuesRange(Integer value, int min, int max); // /** // * Creates an exception indicating invalid value for day-of-month // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 295, value = "Invalid value for day-of-month: %s") // IllegalArgumentException invalidValueDayOfMonth(Integer value); // /** // * Creates an exception indicating relative day-of-month cannot be null or empty // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 296, value = "Relative day-of-month cannot be null or empty") // IllegalArgumentException relativeDayOfMonthIsNull(); // /** // * Creates an exception indicating is not relative value day-of-month // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 297, value = "%s is not a relative value") // IllegalArgumentException invalidRelativeValue(String relativeDayOfMonth); // /** // * Creates an exception indicating value is null, cannot determine if it's relative // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 298, value = "Value is null, cannot determine if it's relative") // IllegalArgumentException relativeValueIsNull(); // /** // * Creates an exception indicating null timerservice cannot be registered" // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 299, value = "null timerservice cannot be registered") // IllegalArgumentException timerServiceNotRegistered(); // // /** // * Creates an exception indicating the timer service is already registered // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 300, value = "Timer service with timedObjectId: %s is already registered") // IllegalStateException timerServiceAlreadyRegistered(String timedObjectId); // // /** // * Creates an exception indicating the null timedObjectId cannot be used for unregistering timerservice // * // * @return an {@link IllegalStateException} for the error. // */ // @Message(id = 301, value = "null timedObjectId cannot be used for unregistering timerservice") // IllegalStateException timedObjectIdIsNullForUnregisteringTimerService(); // // /** // * Creates an exception indicating cannot unregister timer service because it's not registered" // * // * @return an {@link IllegalStateException} for the error. // */ // @Message(id = 302, value = "Cannot unregister timer service with timedObjectId: %s because it's not registered") // IllegalStateException failToUnregisterTimerService(String timedObjectId); /** * Creates an exception indicating the invoker cannot be null * * @return an {@link IllegalArgumentException} for the error. */ @Message(id = 303, value = "Invoker cannot be null") IllegalArgumentException invokerIsNull(); // /** // * Creates an exception indicating the transaction manager cannot be null // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 304, value = "Transaction manager cannot be null") // IllegalArgumentException transactionManagerIsNull(); /** * Creates an exception indicating the Executor cannot be null * * @return an {@link IllegalArgumentException} for the error. */ @Message(id = 305, value = "Executor cannot be null") IllegalArgumentException executorIsNull(); /** * Creates an exception indicating the invalid parameter name and value while creating a timer * * @return an {@link IllegalArgumentException} for the error. */ @Message(id = 306, value = "Invalid timer parameter: %s = %s") IllegalArgumentException invalidTimerParameter(String name, String valueAsString); // /** // * Creates an exception indicating the value cannot be negative while creating a timer // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 307, value = "%s cannot be negative while creating a timer") // IllegalArgumentException invalidInitialExpiration(String type); // /** // * Creates an exception indicating the expiration cannot be null while creating a single action timer // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 308, value = "expiration cannot be null while creating a single action timer") // IllegalArgumentException expirationIsNull(); // /** // * Creates an exception indicating the expiration.getTime() cannot be negative while creating a single action timer // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 309, value = "expiration.getTime() cannot be negative while creating a single action timer") // IllegalArgumentException invalidExpirationActionTimer(); // /** // * Creates an exception indicating duration cannot be negative while creating single action timer // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 310, value = "duration cannot be negative while creating single action timer") // IllegalArgumentException invalidDurationActionTimer(); // /** // * Creates an exception indicating Duration cannot negative while creating the timer // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 311, value = "Duration cannot negative while creating the timer") // IllegalArgumentException invalidDurationTimer(); // /** // * Creates an exception indicating the expiration date cannot be null while creating a timer // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 312, value = "Expiration date cannot be null while creating a timer") // IllegalArgumentException expirationDateIsNull(); // /** // * Creates an exception indicating the expiration.getTime() cannot be negative while creating a timer // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 313, value = "expiration.getTime() cannot be negative while creating a timer") // IllegalArgumentException invalidExpirationTimer(); // /** // * Creates an exception indicating the initial duration cannot be negative while creating timer // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 314, value = "Initial duration cannot be negative while creating timer") // IllegalArgumentException invalidInitialDurationTimer(); // /** // * Creates an exception indicating the interval cannot be negative while creating timer // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 315, value = "Interval cannot be negative while creating timer") // IllegalArgumentException invalidIntervalTimer(); // /** // * Creates an exception indicating the initial expiration date cannot be null while creating a timer // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 316, value = "initial expiration date cannot be null while creating a timer") // IllegalArgumentException initialExpirationDateIsNull(); // /** // * Creates an exception indicating the interval duration cannot be negative while creating timer // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 317, value = "interval duration cannot be negative while creating timer") // IllegalArgumentException invalidIntervalDurationTimer(); // /** // * Creates an exception indicating the creation of timers is not allowed during lifecycle callback of non-singleton Jakarta Enterprise Beans // * // * @return an {@link IllegalStateException} for the error. // */ // @Message(id = 318, value = "Creation of timers is not allowed during lifecycle callback of non-singleton Jakarta Enterprise Beans") // IllegalStateException failToCreateTimerDoLifecycle(); // /** // * Creates an exception indicating initial expiration is null // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 319, value = "initial expiration is null") // IllegalArgumentException initialExpirationIsNull(); // /** // * Creates an exception indicating the interval duration is negative // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 320, value = "interval duration is negative") // IllegalArgumentException invalidIntervalDuration(); // /** // * Creates an exception indicating the schedule is null // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 321, value = "schedule is null") // IllegalArgumentException scheduleIsNull(); // /** // * Creates an exception indicating it could not start transaction // * // * @return an {@link RuntimeException} for the error. // */ // @Message(id = 322, value = "Could not start transaction") // RuntimeException failToStartTransaction(@Cause Throwable t); // // /** // * Creates an exception indicating the transaction cannot be ended since no transaction is in progress // * // * @return an {@link IllegalStateException} for the error. // */ // @Message(id = 323, value = "Transaction cannot be ended since no transaction is in progress") // IllegalStateException noTransactionInProgress(); // // /** // * Creates an exception indicating could not end transaction // * // * @return an {@link RuntimeException} for the error. // */ // @Message(id = 324, value = "Could not end transaction") // RuntimeException failToEndTransaction(@Cause Throwable e); /** * Creates an exception indicating it cannot invoke timer service methods in lifecycle callback of non-singleton beans * * @return an {@link IllegalStateException} for the error. */ @Message(id = 325, value = "Cannot invoke timer service methods in lifecycle callback of non-singleton beans") IllegalStateException failToInvokeTimerServiceDoLifecycle(); /** * Creates an exception indicating timer cannot be null * * @return an {@link IllegalStateException} for the error. */ @Message(id = 326, value = "Timer cannot be null") IllegalStateException timerIsNull(); /** * Creates an exception indicating timer handles are only available for persistent timers * * @return an {@link IllegalStateException} for the error. */ @Message(id = 327, value = "%s Timer handles are only available for persistent timers.") IllegalStateException invalidTimerHandlersForPersistentTimers(String s); /** * Creates an exception indicating no more timeouts for timer * * @return an {@link NoMoreTimeoutsException} for the error. */ @Message(id = 328, value = "No more timeouts for timer %s") NoMoreTimeoutsException noMoreTimeoutForTimer(Timer timer); /** * Creates an exception indicating the timer is not a calendar based timer" * * @return an {@link IllegalStateException for the error. */ @Message(id = 329, value = "Timer %s is not a calendar based timer") IllegalStateException invalidTimerNotCalendarBaseTimer(final Timer timer); /** * Creates an exception indicating the Timer has expired * * @return an {@link NoSuchObjectLocalException} for the error. */ @Message(id = 330, value = "Timer %s has expired") NoSuchObjectLocalException timerHasExpired(String id); /** * Creates an exception indicating the timer was canceled * * @return an {@link NoSuchObjectLocalException} for the error. */ @Message(id = 331, value = "Timer %s was canceled") NoSuchObjectLocalException timerWasCanceled(String id); // /** // * Creates an exception indicating the timer is not persistent // * // * @return an {@link IllegalStateException} for the error. // */ // @Message(id = 332, value = "Timer %s is not persistent") // IllegalStateException failToPersistTimer(TimerImpl timer); // // /** // * Creates an exception indicating it could not register with tx for timer cancellation // * // * @return an {@link RuntimeException} for the error. // */ // @Message(id = 333, value = "Could not register with tx for timer cancellation") // RuntimeException failToRegisterWithTxTimerCancellation(@Cause Throwable e); // // /** // * Creates an exception indicating it could not deserialize info in timer // * // * @return an {@link RuntimeException} for the error. // */ // @Message(id = 334, value = "Could not deserialize info in timer ") // RuntimeException failToDeserializeInfoInTimer(@Cause Throwable e); // /** // * Creates an exception indicating the Id cannot be null // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 335, value = "Id cannot be null") // IllegalArgumentException idIsNull(); // // /** // * Creates an exception indicating Timed objectid cannot be null // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 336, value = "Timed objectid cannot be null") // IllegalArgumentException timedObjectNull(); // // /** // * Creates an exception indicating the timer service cannot be null // * // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 337, value = "Timer service cannot be null") // IllegalArgumentException timerServiceIsNull(); /** * Creates an exception indicating the timerservice with timedObjectId is not registered * * @return an {@link EJBException} for the error. */ @Message(id = 338, value = "Timerservice with timedObjectId: %s is not registered") EJBException timerServiceWithIdNotRegistered(String timedObjectId); /** * Creates an exception indicating the timer for the handle is not active. * * @return an {@link NoSuchObjectLocalException} for the error. */ @Message(id = 339, value = "Timer for handle with timer id: %s, timedObjectId: %s is not active") NoSuchObjectLocalException timerHandleIsNotActive(String timerId, String timedObjectId); // /** // * Creates an exception indicating it could not find timeout method // * // * @return an {@link IllegalStateException} for the error. // */ // @Message(id = 340, value = "Could not find timeout method: %s") // IllegalStateException failToFindTimeoutMethod(TimeoutMethod timeoutMethodInfo); /** * Creates an exception indicating it cannot invoke getTimeoutMethod on a timer which is not an auto-timer * * @return an {@link IllegalStateException} for the error. */ @Message(id = 341, value = "Cannot invoke getTimeoutMethod on a timer which is not an auto-timer") IllegalStateException failToInvokegetTimeoutMethod(); /** * Creates an exception indicating it could not load declared class of timeout method * * @return an {@link RuntimeException} for the error. */ @Message(id = 342, value = "Could not load declaring class: %s of timeout method") RuntimeException failToLoadDeclaringClassOfTimeOut(String declaringClass); /** * Creates an exception indicating it cannot invoke timeout method * * @return an {@link RuntimeException} for the error. */ @Message(id = 343, value = "Cannot invoke timeout method because method %s is not a timeout method") RuntimeException failToInvokeTimeout(Method method); /** * Creates an exception indicating it could not create timer file store directory * * @return an {@link RuntimeException} for the error. */ @Message(id = 344, value = "Could not create timer file store directory %s") RuntimeException failToCreateTimerFileStoreDir(File baseDir); /** * Creates an exception indicating timer file store directory does not exist" * * @return an {@link RuntimeException} for the error. */ @Message(id = 345, value = "Timer file store directory %s does not exist") RuntimeException timerFileStoreDirNotExist(File baseDir); /** * Creates an exception indicating the timer file store directory is not a directory * * @return an {@link RuntimeException} for the error. */ @Message(id = 346, value = "Timer file store directory %s is not a directory") RuntimeException invalidTimerFileStoreDir(File baseDir); /** * Creates an exception indicating Jakarta Enterprise Beans are enabled for security but doesn't have a security domain set * * @return an {@link IllegalStateException} for the error. */ @Message(id = 347, value = "Jakarta Enterprise Beans %s are enabled for security but doesn't have a security domain set") IllegalStateException invalidSecurityForDomainSet(String componentName); /** * Creates an exception indicating component configuration is not an Jakarta Enterprise Beans component" * * @return an {@link IllegalArgumentException} for the error. */ @Message(id = 348, value = "%s is not an Jakarta Enterprise Beans component") IllegalArgumentException invalidComponentConfiguration(String componentName); /** * Creates an exception indicating it could not load view class for ejb * * @return an {@link RuntimeException} for the error. */ @Message(id = 349, value = "Could not load view class for ejb %s") RuntimeException failToLoadViewClassEjb(String beanName, @Cause Throwable e); /** * Creates an exception indicating the component named with component class is not an Jakarta Enterprise Beans component * * @return an {@link IllegalArgumentException} for the error. */ @Message(id = 350, value = "Component named %s with component class %s is not an Jakarta Enterprise Beans component") IllegalArgumentException invalidEjbComponent(String componentName, Class<?> componentClass); // /** // * Creates an exception indicating no timed object invoke for component // * // * @return an {@link StartException} for the error. // */ // @Message(id = 351, value = "No timed object invoke for %s") // StartException failToInvokeTimedObject(EJBComponent component); // // /** // * Creates an exception indicating TimerService is not started // * // * @return an {@link IllegalStateException} for the error. // */ // @Message(id = 352, value = "TimerService is not started") // IllegalStateException failToStartTimerService(); /** * Creates an exception indicating resourceBundle based descriptions are not supported * * @return an {@link UnsupportedOperationException} for the error. */ @Message(id = 353, value = "ResourceBundle based descriptions of %s are not supported") UnsupportedOperationException resourceBundleDescriptionsNotSupported(String name); /** * Creates an exception indicating a runtime attribute is not marshallable * * @return an {@link UnsupportedOperationException} for the error. */ @Message(id = 354, value = "Runtime attribute %s is not marshallable") UnsupportedOperationException runtimeAttributeNotMarshallable(String name); // /** // * Creates an exception indicating an invalid value for the specified element // * // * @return an {@link String} for the error. // */ // @Message(id = 355, value = "Invalid value: %s for '%s' element %s") // String invalidValueForElement(String value, String element, Location location); /** * Creates an exception indicating Jakarta Enterprise Beans component type does not support pools * * @return an {@link IllegalStateException} for the error. */ @Message(id = 356, value = "Jakarta Enterprise Beans component type %s does not support pools") IllegalStateException invalidComponentType(String simpleName); /** * Creates an exception indicating Unknown Jakarta Enterprise Beans Component type * * @return an {@link IllegalStateException} for the error. */ @Message(id = 357, value = "Unknown Jakarta Enterprise Beans Component type %s") IllegalStateException unknownComponentType(EJBComponentType ejbComponentType); // /** // * Creates an exception indicating Method for view shouldn't be // * marked for both @PermitAll and @DenyAll at the same time // * // * @return an {@link IllegalStateException} for the error. // */ // @Message(id = 358, value = "Method %s for view %s shouldn't be marked for both %s and %s at the same time") // IllegalStateException invalidSecurityAnnotation(Method componentMethod, String viewClassName, final String s, final String s1); // // /** // * Creates an exception indicating method named with params not found on component class // * // * @return an {@link RuntimeException} for the error. // */ // @Message(id = 359, value = "Method named %s with params %s not found on component class %s") // RuntimeException failToFindComponentMethod(String name, String s, Class<?> componentClass); /** * Creates an exception indicating the Jakarta Enterprise Beans method security metadata cannot be null * * @return an {@link IllegalArgumentException} for the error. */ @Message(id = 360, value = "Jakarta Enterprise Beans method security metadata cannot be null") IllegalArgumentException ejbMethodSecurityMetaDataIsNull(); /** * Creates an exception indicating the view classname cannot be null or empty * * @return an {@link IllegalArgumentException} for the error. */ @Message(id = 361, value = "View classname cannot be null or empty") IllegalArgumentException viewClassNameIsNull(); /** * Creates an exception indicating View method cannot be null * * @return an {@link IllegalArgumentException} for the error. */ @Message(id = 362, value = "View method cannot be null") IllegalArgumentException viewMethodIsNull(); /** * Creates an exception indicating class cannot handle method of view class * * @return an {@link IllegalStateException} for the error. */ @Message(id = 363, value = "%s cannot handle method %s of view class %s.Expected view method to be %s on view class %s") IllegalStateException failProcessInvocation(String name, final Method invokedMethod, String viewClassOfInvokedMethod, Method viewMethod, String viewClassName); /** * Creates an exception indicating the Invocation on method is not allowed * * @return an {@link EJBAccessException} for the error. */ @Message(id = 364, value = "Invocation on method: %s of bean: %s is not allowed") EJBAccessException invocationOfMethodNotAllowed(Method invokedMethod, String componentName); /** * Creates an exception indicating an unknown Jakarta Enterprise Beans Component description type * * @return an {@link IllegalArgumentException} for the error. */ @Message(id = 365, value = "Unknown Jakarta Enterprise Beans Component description type %s") IllegalArgumentException unknownComponentDescriptionType(Class<?> aClass); /** * Creates an exception indicating unknown attribute * * @return an {@link IllegalStateException} for the error. */ @Message(id = 366, value = "Unknown attribute %s") IllegalStateException unknownAttribute(String attributeName); /** * Creates an exception indicating Unknown operation * * @return an {@link IllegalStateException} for the error. */ @Message(id = 367, value = "Unknown operation %s") IllegalStateException unknownOperations(String opName); /** * Creates an exception indicating no Jakarta Enterprise Beans component registered for address * * @return an {@link String} for the error. */ @Message(id = 368, value = "No Jakarta Enterprise Beans component registered for address %s") String noComponentRegisteredForAddress(PathAddress operationAddress); /** * Creates an exception indicating No Jakarta Enterprise Beans component is available for address * * @return an {@link String} for the error. */ @Message(id = 369, value = "No Jakarta Enterprise Beans component is available for address %s") String noComponentAvailableForAddress(PathAddress operationAddress); /** * Creates an exception indicating Jakarta Enterprise Beans component for specified address is in invalid state * * @return an {@link String} for the error. */ @Message(id = 370, value = "Jakarta Enterprise Beans component for address %s is in %n state %s, must be in state %s") String invalidComponentState(PathAddress operationAddress, ServiceController.State controllerState, ServiceController.State up); // /** // * Creates an exception indicating specified components is not an Jakarta Enterprise Beans component" // * // * @param componentName // * @return an {@link IllegalArgumentException} for the error. // */ // @Message(id = 371, value = "%s is not an Jakarta Enterprise Beans component") // IllegalArgumentException invalidComponentIsNotEjbComponent(final String componentName); /** * Creates an exception indicating Component class has multiple @Timeout annotations * * @return a {@link DeploymentUnitProcessingException} for the error. */ @Message(id = 372, value = "Component class %s has multiple @Timeout annotations") DeploymentUnitProcessingException componentClassHasMultipleTimeoutAnnotations(Class<?> componentClass); /** * Creates an exception indicating the current component is not an Jakarta Enterprise Beans. * * @param component the component. * @return an {@link IllegalStateException} for the error. */ @Message(id = 373, value = "Current component is not an Jakarta Enterprise Beans %s") IllegalStateException currentComponentNotAEjb(ComponentInstance component); /** * Creates an exception indicating the method invocation is not allowed in lifecycle methods. * * @param methodName the name of the method. * @return an {@link IllegalStateException} for the error. */ @Message(id = 374, value = "%s not allowed in lifecycle methods") IllegalStateException lifecycleMethodNotAllowed(String methodName); // @Message(id = 375, value = "%s is not allowed in lifecycle methods of stateless session beans") // IllegalStateException lifecycleMethodNotAllowedFromStatelessSessionBean(String methodName); /** * Creates an exception indicating Cannot call getInvokedBusinessInterface when invoking through ejb object * * @param name type of object * @return a {@link IllegalStateException} for the error. */ @Message(id = 376, value = "Cannot call %s when invoking through %s or %s") IllegalStateException cannotCall(String methodName, String name, String localName); @Message(id = 377, value = "%s is not allowed from stateful beans") IllegalStateException notAllowedFromStatefulBeans(String method); @Message(id = 378, value = "Failed to acquire a permit within %s %s") EJBException failedToAcquirePermit(long timeout, TimeUnit timeUnit); @Message(id = 379, value = "Acquire semaphore was interrupted") EJBException acquireSemaphoreInterrupted(); // /** // * Creates an exception indicating the method is deprecated // * // * @return a {@link IllegalStateException} for the error. // */ // @Message(id = 380, value = "%s is deprecated") // IllegalStateException isDeprecatedIllegalState(String getEnvironment); // @Message(id = 381, value = "Could not find method %s on entity bean") // RuntimeException couldNotFindEntityBeanMethod(String method); @Message(id = 382, value = "Could not determine ClassLoader for stub %s") RuntimeException couldNotFindClassLoaderForStub(String stub); /** * Creates an exception indicating that there was no message listener of the expected type * in the resource adapter * * @param messageListenerType The message listener type * @param resourceAdapterName The resource adapter name * @return a {@link IllegalStateException} for the error. */ @Message(id = 383, value = "No message listener of type %s found in resource adapter %s") IllegalStateException unknownMessageListenerType(String resourceAdapterName, String messageListenerType); /** * Thrown when an Jakarta Enterprise Beans 2 Jakarta Enterprise Beans does not implement a method on an Jakarta Enterprise Beans 2 * * @param method The method * @param viewClass The view * @param ejb The ejb */ @Message(id = 384, value = "Could not find method %s from view %s on Jakarta Enterprise Beans class %s") DeploymentUnitProcessingException couldNotFindViewMethodOnEjb(final Method method, String viewClass, String ejb); /** * Creates and returns an exception indicating that the param named <code>paramName</code> cannot be null * or empty string. * * @param paramName The param name * @return an {@link IllegalArgumentException} for the exception */ @Message(id = 385, value = "%s cannot be null or empty") IllegalArgumentException stringParamCannotBeNullOrEmpty(final String paramName); /** * Exception that is thrown when invoking remove while an Jakarta Enterprise Beans is in a transaction */ @Message(id = 386, value = "Jakarta Enterprise Beans 4.6.4 Cannot remove Jakarta Enterprise Beans via Enterprise Beans 2.x remove() method while participating in a transaction") RemoveException cannotRemoveWhileParticipatingInTransaction(); @Message(id = 387, value = "Transaction propagation over IIOP is not supported") RemoteException transactionPropagationNotSupported(); @Deprecated @Message(id = 388, value = "Cannot call method %s in afterCompletion callback") IllegalStateException cannotCallMethodInAfterCompletion(String methodName); /** * Exception thrown if a method cannot be invoked at the given time */ @Message(id = 389, value = "Cannot call %s when state is %s") IllegalStateException cannotCallMethod(String methodName, String state); @Deprecated @Message(id = 390, value = "%s is already associated with serialization group %s") IllegalStateException existingSerializationGroup(Object key, Object group); @Deprecated @Message(id = 391, value = "%s is not compatible with serialization group %s") IllegalStateException incompatibleSerializationGroup(Object object, Object group); @Deprecated @Message(id = 392, value = "Cache entry %s is in use") IllegalStateException cacheEntryInUse(Object entry); @Deprecated @Message(id = 393, value = "Cache entry %s is not in use") IllegalStateException cacheEntryNotInUse(Object entry); @Deprecated @Message(id = 394, value = "Failed to acquire lock on %s") RuntimeException lockAcquisitionInterrupted(@Cause Throwable cause, Object id); @Deprecated @Message(id = 395, value = "%s is already a member of serialization group %s") IllegalStateException duplicateSerializationGroupMember(Object id, Object groupId); @Deprecated @Message(id = 396, value = "%s is not a member of serialization group %s") IllegalStateException missingSerializationGroupMember(Object id, Object groupId); @Deprecated @Message(id = 397, value = "%s already exists in cache") IllegalStateException duplicateCacheEntry(Object id); @Deprecated @Message(id = 398, value = "%s is missing from cache") IllegalStateException missingCacheEntry(Object id); @Message(id = 399, value = "Incompatible cache implementations in nested hierarchy") IllegalStateException incompatibleCaches(); @Deprecated @Message(id = 400, value = "Failed to passivate %s") RuntimeException passivationFailed(@Cause Throwable cause, Object id); @Deprecated @Message(id = 401, value = "Failed to activate %s") RuntimeException activationFailed(@Cause Throwable cause, Object id); @Deprecated @Message(id = 402, value = "Failed to create passivation directory: %s") RuntimeException passivationDirectoryCreationFailed(String path); @Deprecated @Message(id = 403, value = "Failed to create passivation directory: %s") RuntimeException passivationPathNotADirectory(String path); @Deprecated @Message(id = 404, value = "Group creation context already exists") IllegalStateException groupCreationContextAlreadyExists(); @Message(id = 405, value = "No Jakarta Enterprise Beans found with interface of type '%s' and name '%s' for binding %s") String ejbNotFound(String typeName, String beanName, String binding); @Message(id = 406, value = "No Jakarta Enterprise Beans found with interface of type '%s' for binding %s") String ejbNotFound(String typeName, String binding); @Message(id = 407, value = "More than one Jakarta Enterprise Beans found with interface of type '%s' and name '%s' for binding %s. Found: %s") String moreThanOneEjbFound(String typeName, String beanName, String binding, Set<EJBViewDescription> componentViews); @Message(id = 408, value = "More than one Jakarta Enterprise Beans found with interface of type '%s' for binding %s. Found: %s") String moreThanOneEjbFound(String typeName, String binding, Set<EJBViewDescription> componentViews); /** * Returns a {@link DeploymentUnitProcessingException} to indicate that the {@link org.jboss.ejb3.annotation.Clustered} * annotation cannot be used on a message driven bean * * @param unit The deployment unit * @param componentName The MDB component name * @param componentClassName The MDB component class name * @return the exception */ @Deprecated @Message(id = 409, value = "@Clustered annotation cannot be used with message driven beans. %s failed since %s bean is marked with @Clustered on class %s") DeploymentUnitProcessingException clusteredAnnotationIsNotApplicableForMDB(final DeploymentUnit unit, final String componentName, final String componentClassName); /** * Returns a {@link DeploymentUnitProcessingException} to indicate that the {@link org.jboss.ejb3.annotation.Clustered} * annotation cannot be used on an entity bean * * @param unit The deployment unit * @param componentName The entity bean component name * @param componentClassName The entity bean component class name * @return the exception */ @Deprecated @Message(id = 410, value = "@Clustered annotation cannot be used with entity beans. %s failed since %s bean is marked with @Clustered on class %s") DeploymentUnitProcessingException clusteredAnnotationIsNotApplicableForEntityBean(final DeploymentUnit unit, final String componentName, final String componentClassName); /** * Returns a {@link DeploymentUnitProcessingException} to indicate that the {@link org.jboss.ejb3.annotation.Clustered} * annotation is <b>currently</b> not supported on singleton Jakarta Enterprise Beans. * * @param unit The deployment unit * @param componentName The singleton bean component name * @param componentClassName The singleton bean component class name * @return the exception */ @Deprecated @Message(id = 411, value = "@Clustered annotation is currently not supported for singleton Jakarta Enterprise Beans. %s failed since %s bean is marked with @Clustered on class %s") DeploymentUnitProcessingException clusteredAnnotationNotYetImplementedForSingletonBean(final DeploymentUnit unit, final String componentName, final String componentClassName); /** * Returns a {@link DeploymentUnitProcessingException} to indicate that the {@link org.jboss.ejb3.annotation.Clustered} * annotation cannot be used on the Jakarta Enterprise Beans component represented by <code>componentName</code> * * @param unit The deployment unit * @param componentName The component name * @param componentClassName The component class name * @return the exception */ @Deprecated @Message(id = 412, value = "%s failed since @Clustered annotation cannot be used for %s bean on class %s") DeploymentUnitProcessingException clusteredAnnotationIsNotApplicableForBean(final DeploymentUnit unit, final String componentName, final String componentClassName); /** * Exception thrown if the session-type of a session bean is not specified */ @Message(id = 413, value = "<session-type> not specified for Jakarta Enterprise Beans %s. This must be present in ejb-jar.xml") DeploymentUnitProcessingException sessionTypeNotSpecified(String bean); /** * Creates an exception indicating Default interceptors specify an absolute ordering * * @return a {@link DeploymentUnitProcessingException} for the error. */ @Message(id = 414, value = "Default interceptors cannot specify an <interceptor-order> element in ejb-jar.xml") DeploymentUnitProcessingException defaultInterceptorsNotSpecifyOrder(); // /** // * Creates an returns a {@link IllegalStateException} to indicate that a cache is not clustered // * // * @return the exception // */ // @Message(id = 415, value = "Cache is not clustered") // IllegalStateException cacheIsNotClustered(); /** * Creates and returns an exception indicating that the param named <code>paramName</code> cannot be null * * @param paramName The param name * @return an {@link IllegalArgumentException} for the exception */ @Message(id = 416, value = "%s cannot be null") IllegalArgumentException paramCannotBeNull(final String paramName); // @Message(id = 417, value = "A GroupMembershipNotifier is already registered by the name of %s") // IllegalArgumentException groupMembershipNotifierAlreadyRegistered(final String groupName); // // @Message(id = 418, value = "No GroupMembershipNotifier registered by the name of %s") // IllegalArgumentException groupMembershipNotifierNotRegistered(final String groupName); /** * Creates and returns an exception indicating that the pool name configured for a bean cannot be an empty string * * @param ejbName The EJB name * @return an {@link IllegalArgumentException} for the exception */ @Message(id = 419, value = "Pool name cannot be empty string for bean %s") IllegalArgumentException poolNameCannotBeEmptyString(final String ejbName); /** * The user attempts to look up the Jakarta Enterprise Beans context in a war when no Jakarta Enterprise Beans context is active */ @Message(id = 420, value = "No EjbContext available as no Jakarta Enterprise Beans invocation is active") IllegalStateException noEjbContextAvailable(); @Message(id = 421, value = "Invocation cannot proceed as component is shutting down") EJBComponentUnavailableException componentIsShuttingDown(); // @Message(id = 422, value = "Could not open message outputstream for writing to Channel") // IOException failedToOpenMessageOutputStream(@Cause Throwable e); @Message(id = 423, value = "Could not create session for stateful bean %s") RuntimeException failedToCreateSessionForStatefulBean(@Cause Exception e, String beanName); // @Message(id = 424, value = "No thread context classloader available") // IllegalStateException tcclNotAvailable(); // // @Message(id = 425, value = "Cannot write to null DataOutput") // IllegalArgumentException cannotWriteToNullDataOutput(); // // @Message(id = 426, value = "No client-mapping entries found for node %s in cluster %s") // IllegalStateException clientMappingMissing(String nodeName, String clusterName); // // @Message(id = 427, value = "Could not load class") // RuntimeException classNotFoundException(@Cause ClassNotFoundException cnfe); // // @Message(id = 428, value = "Jakarta Enterprise Beans module identifiers cannot be null") // IllegalArgumentException ejbModuleIdentifiersCannotBeNull(); // // @Message(id = 429, value = "MessageInputStream cannot be null") // IllegalArgumentException messageInputStreamCannotBeNull(); // // @Message(id = 430, value = "Unknown transaction request type %s") // IllegalArgumentException unknownTransactionRequestType(String txRequestType); // // @Message(id = 431, value = "Could not close channel") // RuntimeException couldNotCloseChannel(@Cause IOException ioe); // // @Message(id = 432, value = "No subordinate transaction present for xid %s") // RuntimeException noSubordinateTransactionPresentForXid(Xid xid); // // @Message(id = 433, value = "Failed to register transaction synchronization") // RuntimeException failedToRegisterTransactionSynchronization(@Cause Exception e); // // @Message(id = 434, value = "Failed to get current transaction") // RuntimeException failedToGetCurrentTransaction(@Cause Exception e); // // @Message(id = 435, value = "Could not obtain lock on %s to passivate %s") // IllegalStateException couldNotObtainLockForGroup(String groupId, String groupMember); @Message(id = 436, value = "Unknown channel creation option type %s") IllegalArgumentException unknownChannelCreationOptionType(String optionType); @Message(id = 437, value = "Could not determine remote interface from home interface %s for bean %s") DeploymentUnitProcessingException couldNotDetermineRemoteInterfaceFromHome(final String homeClass, final String beanName); @Message(id = 438, value = "Could not determine local interface from local home interface %s for bean %s") DeploymentUnitProcessingException couldNotDetermineLocalInterfaceFromLocalHome(final String localHomeClass, final String beanName); // @Message(id = 439, value = "Unsupported marshalling version: %d") // IllegalArgumentException unsupportedMarshallingVersion(int version); // // @Message(id = 440, value = "%s method %s must be public") // DeploymentUnitProcessingException ejbMethodMustBePublic(final String type, final Method method); // @Message(id = 441, value = "Jakarta Enterprise Beans business method %s must be public") // DeploymentUnitProcessingException ejbBusinessMethodMustBePublic(final Method method); @Message(id = 442, value = "Unexpected Error") @Signature(String.class) EJBException unexpectedError(@Cause Throwable cause); @Message(id = 443, value = "Enterprise Beans 3.1 FR 13.3.3: BMT bean %s should complete transaction before returning.") String transactionNotComplete(String componentName); // @Message(id = 444, value = "Timer service resource %s is not suitable for the target. Only a configuration with a single file-store and no other configured data-store is supported on target") // String untransformableTimerService(PathAddress address); @Deprecated @Message(id = 445, value = "Detected asymmetric usage of cache") IllegalStateException asymmetricCacheUsage(); /** * Creates an exception indicating that timer is active. * * @return an {@link IllegalStateException} for the error. */ @Message(id = 446, value = "The timer %s is already active.") IllegalStateException timerIsActive(Timer timer); @Message(id = 447, value = "Transaction '%s' was already rolled back") RollbackException transactionAlreadyRolledBack(Transaction tx); @Message(id = 448, value = "Transaction '%s' is in unexpected state (%s)") EJBException transactionInUnexpectedState(Transaction tx, String txStatus); @Message(id = 449, value = "Timerservice API is not allowed on stateful session bean %s") String timerServiceMethodNotAllowedForSFSB(final String ejbComponent); @Message(id = 450, value = "Entity Beans are no longer supported, beans %s cannot be deployed") DeploymentUnitProcessingException entityBeansAreNotSupported(String beanName); @Message(id = 451, value = "Attribute '%s' is not supported on current version servers; it is only allowed if its value matches '%s'") OperationFailedException inconsistentAttributeNotSupported(String attributeName, String mustMatch); // @Message(id = 452, value = "Unexpected end of document") // XMLStreamException unexpectedEndOfDocument(@Param Location location); @LogMessage(level = ERROR) @Message(id = 453, value = "Failed to persist timer %s") void failedToPersistTimer(Timer timerid, @Cause Exception e); @Message(id = 454, value = "Only one instance on <container-transaction> with an ejb-name of * can be present.") DeploymentUnitProcessingException mustOnlyBeSingleContainerTransactionElementWithWildcard(); @Message(id = 455, value = "<container-transaction> elements that use the wildcard Jakarta Enterprise Beans name * can only use a method name of *") DeploymentUnitProcessingException wildcardContainerTransactionElementsMustHaveWildcardMethodName(); @LogMessage(level = ERROR) @Message(id = 456, value = "Failed to refresh timers for %s") void failedToRefreshTimers(String timedObjectId); @Message(id = 457, value = "Unexpected Error") @Signature(String.class) EJBTransactionRolledbackException unexpectedErrorRolledBack(@Cause Error error); //@LogMessage(level = ERROR) //@Message(id = 458, value = "Failure in caller transaction.") //void failureInCallerTransaction(@Cause Throwable cause); @Message(id = 459, value = "Module %s containing bean %s is not deployed in ear but it specifies resource adapter name '%s' in a relative format.") DeploymentUnitProcessingException relativeResourceAdapterNameInStandaloneModule(String module, String bean, String adapterName); /** * Logs a waring message that the current datasource configuration does not ensure consistency in a clustered environment. */ @LogMessage(level = WARN) @Message(id = 460, value = "The transaction isolation need to be equal or stricter than READ_COMMITTED to ensure that the timer run once-and-only-once") void wrongTransactionIsolationConfiguredForTimer(); /** * Transaction rollback after problems not successful */ @LogMessage(level = ERROR) @Message(id = 461, value = "Update timer failed and it was not possible to rollback the transaction!") void timerUpdateFailedAndRollbackNotPossible(@Cause Throwable rbe); /** * Logs a warning message indicating that the database dialect cannot be detected automatically. */ @LogMessage(level = WARN) @Message(id = 462, value = "Timer service database-data-store database attribute is not configured, and is not detected from connection metadata or JDBC driver name.") void databaseDialectNotConfiguredOrDetected(); @LogMessage(level = WARN) @Message(id = 463, value = "Invalid transaction attribute type %s on SFSB lifecycle method %s of class %s, valid types are REQUIRES_NEW and NOT_SUPPORTED. Method will be treated as NOT_SUPPORTED.") void invalidTransactionTypeForSfsbLifecycleMethod(TransactionAttributeType txAttr, MethodIdentifier method, Class<?> clazz); @Message(id = 464, value = "The \"" + EJB3SubsystemModel.DISABLE_DEFAULT_EJB_PERMISSIONS + "\" attribute may not be set to true") OperationFailedException disableDefaultEjbPermissionsCannotBeTrue(); @Message(id = 465, value = "Invalid client descriptor configuration: 'profile' and 'remoting-ejb-receivers' cannot be used together") DeploymentUnitProcessingException profileAndRemotingEjbReceiversUsedTogether(); @Message(id = 466, value = "Failed to process business interfaces for Jakarta Enterprise Beans class %s") DeploymentUnitProcessingException failedToProcessBusinessInterfaces(Class<?> ejbClass, @Cause Exception e); @Message(id = 467, value = "The request was rejected as the container is suspended") EJBComponentUnavailableException containerSuspended(); @Message(id = 468, value = "Timer invocation failed") OperationFailedException timerInvocationFailed(@Cause Exception e); @Message(id = 469, value = "Indexed child resources can only be registered if the parent resource supports ordered children. The parent of '%s' is not indexed") IllegalStateException indexedChildResourceRegistrationNotAvailable(PathElement address); // @LogMessage(level = INFO) // @Message(id = 470, value = "Could not create a connection for cluster node %s in cluster %s") // void couldNotCreateClusterConnection(@Cause Throwable cause, String nodeName, String clusterName); @Message(id = 471, value = "RMI/IIOP Violation: %s%n") RuntimeException rmiIiopVoliation(String violation); @Message(id = 472, value = "Cannot obtain exception repository id for %s:%n%s") RuntimeException exceptionRepositoryNotFound(String name, String message); @LogMessage(level = INFO) @Message(id = 473, value = "JNDI bindings for session bean named '%s' in deployment unit '%s' are as follows:%s") void jndiBindings(final String ejbName, final DeploymentUnit deploymentUnit, final StringBuilder bindings); @LogMessage(level = ERROR) @Message(id = 474, value = "Attribute '%s' is not supported on current version servers; it is only allowed if its value matches '%s'. This attribute should be removed.") void logInconsistentAttributeNotSupported(String attributeName, String mustMatch); @LogMessage(level = INFO) @Message(id = 475, value = "MDB delivery started: %s,%s") void mdbDeliveryStarted(String appName, String componentName); @LogMessage(level = INFO) @Message(id = 476, value = "MDB delivery stopped: %s,%s") void mdbDeliveryStopped(String appName, String componentName); @Message(id = 477, value = "MDB delivery group is missing: %s") DeploymentUnitProcessingException missingMdbDeliveryGroup(String deliveryGroupName); @LogMessage(level = ERROR) @Message(id = 480, value = "Loaded timer (%s) for Jakarta Enterprise Beans (%s) and this node that is marked as being in a timeout. The original timeout may not have been processed. Please use graceful shutdown to ensure timeout tasks are finished before shutting down.") void loadedPersistentTimerInTimeout(String timer, String timedObject); @LogMessage(level = INFO) @Message(id = 481, value = "Strict pool %s is using a max instance size of %d (per class), which is derived from thread worker pool sizing.") void strictPoolDerivedFromWorkers(String name, int max); @LogMessage(level = INFO) @Message(id = 482, value = "Strict pool %s is using a max instance size of %d (per class), which is derived from the number of CPUs on this host.") void strictPoolDerivedFromCPUs(String name, int max); @Message(id = 483, value = "Attributes are mutually exclusive: %s, %s") XMLStreamException mutuallyExclusiveAttributes(@Param Location location, String attribute1, String attribute2); // @LogMessage(level = WARN) // @Message(id = 484, value = "Could not send a cluster removal message for cluster: (%s) to the client on channel %s") // void couldNotSendClusterRemovalMessage(@Cause Throwable cause, Group group, Channel channel); @LogMessage(level = WARN) @Message(id = 485, value = "Transaction type %s is unspecified for the %s method of the %s message-driven bean. It will be handled as NOT_SUPPORTED.") void invalidTransactionTypeForMDB(TransactionAttributeType transactionAttributeType, String methond, String componentName); @LogMessage(level = INFO) @Message(id = 486, value = "Parameter 'default-clustered-sfsb-cache' was defined for the 'add' operation for resource '%s'. " + "This parameter is deprecated and its previous behavior has been remapped to attribute 'default-sfsb-cache'. " + "As a result the 'default-sfsb-cache' attribute has been set to '%s' and the " + "'default-sfsb-passivation-disabled-cache' attribute has been set to '%s'.") void remappingCacheAttributes(String address, ModelNode defClustered, ModelNode passivationDisabled); @LogMessage(level = ERROR) @Message(id = 487, value = "Unexpected invocation state %s") void unexpectedInvocationState(int state); // @Message(id = 488, value = "Unauthenticated (anonymous) access to this Jakarta Enterprise Beans method is not authorized") // SecurityException ejbAuthenticationRequired(); @LogMessage(level = ERROR) @Message(id = 489, value = "Timer %s not running as transaction could not be started") void timerNotRunning(@Cause NotSupportedException e, TimerImpl timer); @Message(id = 490, value = "Multiple security domains not supported") DeploymentUnitProcessingException multipleSecurityDomainsDetected(); @Message(id = 491, value = "The transaction begin request was rejected as the container is suspended") EJBException cannotBeginUserTransaction(); @LogMessage(level = INFO) @Message(id = 492, value = "Jakarta Enterprise Beans subsystem suspension waiting for active transactions, %d transaction(s) remaining") void suspensionWaitingActiveTransactions(int activeTransactionCount); @LogMessage(level = INFO) @Message(id = 493, value = "Jakarta Enterprise Beans subsystem suspension complete") void suspensionComplete(); @Message(id = 494, value = "Failed to obtain SSLContext") RuntimeException failedToObtainSSLContext(@Cause Exception cause); @LogMessage(level = WARN) @Message(id = 495, value = "Ignoring the persisted start or end date for scheduled expression of timer ID:%s as it is not valid : %s.") void scheduleExpressionDateFromTimerPersistenceInvalid(String timerId, String parserMessage); @Message(id = 496, value = "Could not create an instance of Jakarta Enterprise Beans client interceptor %s") DeploymentUnitProcessingException failedToCreateEJBClientInterceptor(@Cause Exception e, String ejbClientInterceptorClassName); @LogMessage(level = WARN) @Message(id = 497, value = "Failed to persist timer %s on startup. This is likely due to another cluster member making the same change, and should not affect operation.") void failedToPersistTimerOnStartup(TimerImpl activeTimer, @Cause Exception e); @Message(id = 499, value = "Cannot read derived size - service %s unreachable") OperationFailedException cannotReadStrictMaxPoolDerivedSize(ServiceName serviceName); @LogMessage(level = ERROR) @Message(id = 500, value = "Legacy org.jboss.security.annotation.SecurityDomain annotation is used in class: %s, please use org.jboss.ejb3.annotation.SecurityDomain instead.") void legacySecurityDomainAnnotationIsUsed(String cls); @Message(id = 501, value = "Failed to activate MDB %s") RuntimeException failedToActivateMdb(String componentName, @Cause Exception e); @LogMessage(level = ERROR) @Message(id = 502, value = "Exception checking if timer %s should run") void exceptionCheckingIfTimerShouldRun(Timer timer, @Cause Exception e); @LogMessage(level = WARN) @Message(id = 503, value = "[Jakarta Enterprise Beans 3.2 spec, section 5.6.4] Message Driven Bean 'onMessage' method can not be final (MDB: %s).") void mdbOnMessageMethodCantBeFinal(String className); @LogMessage(level = WARN) @Message(id = 504, value = "[Jakarta Enterprise Beans 3.2 spec, section 5.6.4] Message Driven Bean 'onMessage' method can not be private (MDB: %s).") void mdbOnMessageMethodCantBePrivate(String className); @LogMessage(level = WARN) @Message(id = 505, value = "[Jakarta Enterprise Beans 3.2 spec, section 5.6.4] Message Driven Bean 'onMessage' method can not be static (MDB: %s).") void mdbOnMessageMethodCantBeStatic(String className); @LogMessage(level = WARN) @Message(id = 506, value = "[Jakarta Enterprise Beans 3.2 spec, section 5.6.2] Message Driven Bean can not have a 'finalize' method. (MDB: %s)") void mdbCantHaveFinalizeMethod(String className); @LogMessage(level = ERROR) @Message(id = 507, value = "Failed to persist timer's state %s. Timer has to be restored manually") void exceptionPersistPostTimerState(Timer timer, @Cause Exception e); @LogMessage(level = WARN) @Message(id = 508, value = "Failed to persist timer's state %s due to %s") void exceptionPersistTimerState(Timer timer, Exception e); @LogMessage(level = WARN) @Message(id = 509, value = "Clustered Jakarta Enterprise Beans in Node: %s are bound to INADDR_ANY(%s). Either use a non-wildcard server bind address or add client-mapping entries to the relevant socket-binding for the Remoting connector") void clusteredEJBsBoundToINADDRANY(String nodeName, String ip); @LogMessage(level = WARN) @Message(id = 510, value = "@RunAs annotation is required when using @RunAsPrincipal on class %s") void missingRunAsAnnotation(String className); @Message(id = 511, value = "Cannot build reflection index for server interceptor class %s") RuntimeException cannotBuildIndexForServerInterceptor(String interceptorClass, @Cause Exception e); @Message(id = 512, value = "Server interceptor class %s does not have a no parameter constructor") RuntimeException serverInterceptorNoEmptyConstructor(String interceptorClass, @Cause Exception e); @Message(id = 513, value = "Method %s in server interceptor %s annotated with %s has invalid signature") RuntimeException serverInterceptorInvalidMethod(String methodName, String interceptorClass, String annotationClass, @Cause Exception e); @Message(id = 514, value = "Cannot load server interceptor module %s") RuntimeException cannotLoadServerInterceptorModule(String moduleId, @Cause Exception e); @LogMessage(level = WARN) @Message(id = 515, value = "[Jakarta Enterprise Beans 3.2 spec, section 4.9.2] Singleton session beans are not allowed to implement 'jakarta.ejb.SessionBean' interface. This interface on bean '%s' is going to be ignored and should be removed.") void singletonCantImplementSessionBean(String className); @LogMessage(level = INFO) @Message(id = 516, value = "IIOP bindings for session bean named '%s' in deployment unit '%s' are as follows: %s") void iiopBindings(final String componentName, final String moduleName, final String name); @LogMessage(level = ERROR) @Message(id = 517, value = "[Jakarta Enterprise Beans 3.2 spec, section 4.1] Spec violation for class %s. Session Jakarta Enterprise Beans should have only one of the following types : Stateful, Stateless, Singleton.") void typeSpecViolation(String className); @Message(id = 518, value = "Exception resolving class %s for unmarshalling; it has either been blocklisted or not allowlisted") InvalidClassException cannotResolveFilteredClass(String clazz); @Message(id = 519, value = "Invalid unmarshalling filter specfication %s; specifications must describe class or package name matching patterns") IllegalArgumentException invalidFilterSpec(String spec); @Message(id = 521, value = "Some classes referenced by annotation: %s in class: %s are missing.") DeploymentUnitProcessingException missingClassInAnnotation(String anCls, String resCls); @LogMessage(level = WARN) @Message(id = 522, value = "The default pool name %s could not be resolved from its value: %s") void defaultPoolExpressionCouldNotBeResolved(String defaultPoolName, String defaultPoolValue); @LogMessage(level = WARN) @Message(id = 523, value = "Timer %s has not been deployed") void timerNotDeployed(String timer); @Message(id = 524, value = "Timer %s cannot be added") RuntimeException timerCannotBeAdded(TimerImpl timer); @LogMessage(level = WARN) @Message(id = 525, value = "The 'mappedName' in Jakarta Enterprise Beans annotations is not supported. Value of '%s' for Jakarta Enterprise Beans '%s' will be ignored.") void mappedNameNotSupported(String mappedName, String ejb); @Message(id = 526, value = "Timer %s does not exist") OperationFailedException timerNotFound(String timerId); @LogMessage(level = ERROR) @Message(id = 527, value = "Remoting connector (address %s, port %s) is not correctly configured for EJB client invocations, the connector must be listed in <remote/> 'connectors' attribute to receive EJB client invocations") void connectorNotConfiguredForEJBClientInvocations(String address, int port); @LogMessage(level = DEBUG) @Message(id = 528, value = "Jakarta Enterprise Beans business method %s must be public") void ejbBusinessMethodMustBePublic(final Method method); @LogMessage(level = WARN) @Message(id = 529, value = "Failed to retrieve info from database for timer: %s") void failedToRetrieveTimerInfo(final TimerImpl timer, @Cause Exception e); @Message(id = 530, value = "The deployment is configured to use a legacy security domain '%s' which is no longer supported.") IllegalStateException legacySecurityUnsupported(String domainName); @LogMessage(level = WARN) @Message(id = 531, value = "No client mappings registry provider found for %s; using legacy provider based on static configuration") void legacyClientMappingsRegistryProviderInUse(String name); @LogMessage(level = WARN) @Message(id = 532, value = "Database detected from configuration is: '%s'. If this is incorrect, please specify the correct database.") void unknownDatabaseName(String name); }
155,858
46.736294
275
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/cache/EJBBoundCacheParser.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.cache; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.jboss.metadata.ejb.parser.jboss.ejb3.AbstractEJBBoundMetaDataParser; import org.jboss.metadata.property.PropertyReplacer; /** * Parser for <code>urn:ejb-cache</code> namespace. The <code>urn:ejb-cache</code> namespace elements * can be used to configure cache names for Jakarta Enterprise Beans. * * @author Jaikiran Pai * @author Stuart Douglas */ public class EJBBoundCacheParser extends AbstractEJBBoundMetaDataParser<EJBBoundCacheMetaData> { public static final String NAMESPACE_URI_1_0 = "urn:ejb-cache:1.0"; public static final String NAMESPACE_URI_2_0 = "urn:ejb-cache:2.0"; private static final String ROOT_ELEMENT_CACHE = "cache"; private static final String CACHE_REF = "cache-ref"; @Override public EJBBoundCacheMetaData parse(final XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException { final String element = reader.getLocalName(); // we only parse <cache> (root) element if (!ROOT_ELEMENT_CACHE.equals(element)) { throw unexpectedElement(reader); } final EJBBoundCacheMetaData ejbBoundCacheMetaData = new EJBBoundCacheMetaData(); this.processElements(ejbBoundCacheMetaData, reader, propertyReplacer); return ejbBoundCacheMetaData; } @Override protected void processElement(final EJBBoundCacheMetaData cacheMetaData, final XMLStreamReader reader, final PropertyReplacer propertyReplacer) throws XMLStreamException { final String namespaceURI = reader.getNamespaceURI(); final String elementName = reader.getLocalName(); // if it doesn't belong to our namespace then let the super handle this if (!NAMESPACE_URI_1_0.equals(namespaceURI) && !NAMESPACE_URI_2_0.equals(namespaceURI)) { super.processElement(cacheMetaData, reader, propertyReplacer); return; } if (CACHE_REF.equals(elementName)) { final String cacheName = getElementText(reader, propertyReplacer); // set the cache name in the metadata cacheMetaData.setCacheName(cacheName); } else { throw unexpectedElement(reader); } } }
3,346
42.467532
175
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/cache/EJBBoundCacheMetaData.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.cache; import org.jboss.metadata.ejb.parser.jboss.ejb3.AbstractEJBBoundMetaData; /** * Metadata represents the pool name configured for Jakarta Enterprise Beans via the jboss-ejb3.xml deployment descriptor * * @author Jaikiran Pai */ public class EJBBoundCacheMetaData extends AbstractEJBBoundMetaData { private static final long serialVersionUID = -3246398329247802494L; private String cacheName; public String getCacheName() { return cacheName; } public void setCacheName(final String cacheName) { this.cacheName = cacheName; } }
1,631
35.266667
121
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/cache/CacheInfo.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.cache; /** * @author Paul Ferraro * */ public class CacheInfo { private final String name; public CacheInfo(String name) { this.name = name; } public String getName() { return name; } @Override public boolean equals(Object object) { if (!(object instanceof CacheInfo)) return false; return this.name.equals(((CacheInfo) object).name); } @Override public int hashCode() { return this.name.hashCode(); } @Override public String toString() { return this.name; } }
1,624
28.017857
70
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/deployment/ApplicationExceptions.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.deployment; import org.jboss.as.ejb3.logging.EjbLogger; import java.rmi.RemoteException; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * User: jpai */ public class ApplicationExceptions { private final Map<Class<?>, org.jboss.as.ejb3.tx.ApplicationExceptionDetails> applicationExceptions = new HashMap<Class<?>, org.jboss.as.ejb3.tx.ApplicationExceptionDetails>(); public ApplicationExceptions() { } public org.jboss.as.ejb3.tx.ApplicationExceptionDetails getApplicationException(Class<?> exceptionClass) { return this.applicationExceptions.get(exceptionClass); } public Map<Class<?>, org.jboss.as.ejb3.tx.ApplicationExceptionDetails> getApplicationExceptions() { return Collections.unmodifiableMap(this.applicationExceptions); } public void addApplicationException(Class<?> exceptionClass, org.jboss.as.ejb3.tx.ApplicationExceptionDetails applicationException) { if (exceptionClass == null) { throw EjbLogger.ROOT_LOGGER.paramCannotBeNull("Exception class"); } if (applicationException == null) { throw EjbLogger.ROOT_LOGGER.paramCannotBeNull("ApplicationException"); } // Enterprise Beans 3.1 spec, section 14.1.1 // application exception *must* be of type Exception if (!Exception.class.isAssignableFrom(exceptionClass)) { throw EjbLogger.ROOT_LOGGER.cannotBeApplicationExceptionBecauseNotAnExceptionType(exceptionClass); } // Enterprise Beans 3.1 spec, section 14.1.1: // application exception *cannot* be of type java.rmi.RemoteException if (RemoteException.class.isAssignableFrom(exceptionClass)) { throw EjbLogger.ROOT_LOGGER.rmiRemoteExceptionCannotBeApplicationException(exceptionClass); } // add it to our map this.applicationExceptions.put(exceptionClass, applicationException); } }
3,008
38.077922
180
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/deployment/ApplicableMethodInformation.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.deployment; import java.lang.reflect.Method; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.util.MethodInfoHelper; import org.jboss.metadata.ejb.spec.MethodInterfaceType; import org.wildfly.security.manager.WildFlySecurityManager; /** * Metadata store for method level information that can be applied to a method via various different deployment * descriptor styles * * @author Stuart Douglas */ public class ApplicableMethodInformation<T> { private final String componentName; /** * Enterprise Beans 3.1 FR 13.3.7, the default transaction attribute is <i>REQUIRED</i>. */ private T defaultAttribute; /** * applied to all view methods of a given type */ private final Map<MethodInterfaceType, T> perViewStyle1 = new HashMap<MethodInterfaceType, T>(); /** * Applied to all methods with a given name on a given view type */ private final PopulatingMap<MethodInterfaceType, Map<String, T>> perViewStyle2 = new PopulatingMap<MethodInterfaceType, Map<String, T>>() { @Override Map<String, T> populate() { return new HashMap<String, T>(); } }; /** * Applied to an exact method on a view type */ private final PopulatingMap<MethodInterfaceType, PopulatingMap<String, Map<ArrayKey, T>>> perViewStyle3 = new PopulatingMap<MethodInterfaceType, PopulatingMap<String, Map<ArrayKey, T>>>() { @Override PopulatingMap<String, Map<ArrayKey, T>> populate() { return new PopulatingMap<String, Map<ArrayKey, T>>() { @Override Map<ArrayKey, T> populate() { return new HashMap<ArrayKey, T>(); } }; } }; /** * Map of bean class to attribute */ private final Map<String, T> style1 = new HashMap<String, T>(); /** * map of bean method name to attribute */ private final Map<String, T> style2 = new HashMap<String, T>(); public ApplicableMethodInformation(final String componentName, final T defaultAttribute) { this.componentName = componentName; this.defaultAttribute = defaultAttribute; } /** * map of exact bean method to attribute */ private final PopulatingMap<String, PopulatingMap<String, Map<ArrayKey, T>>> style3 = new PopulatingMap<String, PopulatingMap<String, Map<ArrayKey, T>>>() { @Override PopulatingMap<String, Map<ArrayKey, T>> populate() { return new PopulatingMap<String, Map<ArrayKey, T>>() { @Override Map<ArrayKey, T> populate() { return new HashMap<ArrayKey, T>(); } }; } }; public T getAttribute(MethodInterfaceType methodIntf, Method method) { return getAttribute(methodIntf, method, null); } public T getAttribute(MethodInterfaceType methodIntf, Method method, MethodInterfaceType defaultMethodIntf) { assert methodIntf != null : "methodIntf is null"; assert method != null : "method is null"; Method classMethod = resolveRealMethod(method); String[] methodParams = MethodInfoHelper.getCanonicalParameterTypes(classMethod); final String methodName = classMethod.getName(); final String className = classMethod.getDeclaringClass().getName(); ArrayKey methodParamsKey = new ArrayKey((Object[]) methodParams); T attr = get(get(get(perViewStyle3, methodIntf), methodName), methodParamsKey); if (attr != null) return attr; attr = get(get(perViewStyle2, methodIntf), methodName); if (attr != null) return attr; attr = get(perViewStyle1, methodIntf); if (attr != null) return attr; attr = get(get(get(style3, className), methodName), methodParamsKey); if (attr != null) return attr; attr = get(style2, methodName); if (attr != null) return attr; attr = get(style1, className); if (attr != null) return attr; if(defaultMethodIntf == null) { return defaultAttribute; } else { return getAttribute(defaultMethodIntf, method); } } public List<T> getAllAttributes(MethodInterfaceType methodIntf, Method method) { assert methodIntf != null : "methodIntf is null"; Method classMethod = resolveRealMethod(method); String[] methodParams = MethodInfoHelper.getCanonicalParameterTypes(classMethod); final String methodName = classMethod.getName(); final String className = classMethod.getDeclaringClass().getName(); final List<T> ret = new ArrayList<T>(); ArrayKey methodParamsKey = new ArrayKey((Object[]) methodParams); T attr = get(get(get(perViewStyle3, methodIntf), methodName), methodParamsKey); if (attr != null) ret.add(attr); attr = get(get(perViewStyle2, methodIntf), methodName); if (attr != null) ret.add(attr); attr = get(perViewStyle1, methodIntf); if (attr != null) ret.add(attr); attr = get(get(get(style3, className), methodName), methodParamsKey); if (attr != null) ret.add(attr); attr = get(style2, methodName); if (attr != null) ret.add(attr); attr = get(style1, className); if (attr != null) ret.add(attr); return ret; } private Method resolveRealMethod(final Method method) { if (method.isBridge() || method.isSynthetic()) { Method[] declaredMethods = WildFlySecurityManager.doUnchecked(new PrivilegedAction<Method[]>() { @Override public Method[] run() { return method.getDeclaringClass().getDeclaredMethods(); } }); methodLoop: for (Method m : declaredMethods) { if (m.getName().equals(method.getName()) && m.getParameterCount() == method.getParameterCount() && !m.isBridge() && !m.isSynthetic()) { if(!method.getReturnType().isAssignableFrom(m.getReturnType())) { continue methodLoop; } for(int i = 0; i < method.getParameterCount(); ++i) { if(!method.getParameterTypes()[i].isAssignableFrom(m.getParameterTypes()[i])) { continue methodLoop; } } return m; } } } return method; } public T getViewAttribute(MethodInterfaceType methodIntf, final Method method) { assert methodIntf != null : "methodIntf is null"; Method classMethod = resolveRealMethod(method); String[] methodParams = MethodInfoHelper.getCanonicalParameterTypes(classMethod); final String methodName = classMethod.getName(); ArrayKey methodParamsKey = new ArrayKey((Object[]) methodParams); T attr = get(get(get(perViewStyle3, methodIntf), methodName), methodParamsKey); if (attr != null) return attr; attr = get(get(perViewStyle2, methodIntf), methodName); if (attr != null) return attr; attr = get(perViewStyle1, methodIntf); if (attr != null) return attr; return null; } /** * @param className The class name * @return The attribute that has been applied directly to the given class */ public T getClassLevelAttribute(String className) { return style1.get(className); } /** * Style 1 (13.3.7.2.1 @1) * * @param methodIntf the method-intf the annotations apply to or null if Jakarta Enterprise Beans class itself * @param attribute */ public void setAttribute(MethodInterfaceType methodIntf, String className, T attribute) { if (methodIntf != null && className != null) throw EjbLogger.ROOT_LOGGER.bothMethodIntAndClassNameSet(componentName); if (methodIntf == null) { style1.put(className, attribute); } else perViewStyle1.put(methodIntf, attribute); } public T getAttributeStyle1(MethodInterfaceType methodIntf, String className) { if (methodIntf != null && className != null) throw EjbLogger.ROOT_LOGGER.bothMethodIntAndClassNameSet(componentName); if (methodIntf == null) { return style1.get(className); } else { return perViewStyle1.get(methodIntf); } } /** * Style 2 (13.3.7.2.1 @2) * * @param methodIntf the method-intf the annotations apply to or null if Jakarta Enterprise Beans class itself * @param transactionAttribute * @param methodName */ public void setAttribute(MethodInterfaceType methodIntf, T transactionAttribute, String methodName) { if (methodIntf == null) style2.put(methodName, transactionAttribute); else perViewStyle2.pick(methodIntf).put(methodName, transactionAttribute); } public T getAttributeStyle2(MethodInterfaceType methodIntf, String methodName) { if (methodIntf == null) return style2.get(methodName); else return perViewStyle2.pick(methodIntf).get(methodName); } /** * Style 3 (13.3.7.2.1 @3) * * @param methodIntf the method-intf the annotations apply to or null if Jakarta Enterprise Beans class itself * @param transactionAttribute * @param methodName * @param methodParams */ public void setAttribute(MethodInterfaceType methodIntf, T transactionAttribute, final String className, String methodName, String... methodParams) { ArrayKey methodParamsKey = new ArrayKey((Object[]) methodParams); if (methodIntf == null) style3.pick(className).pick(methodName).put(methodParamsKey, transactionAttribute); else perViewStyle3.pick(methodIntf).pick(methodName).put(methodParamsKey, transactionAttribute); } public T getAttributeStyle3(MethodInterfaceType methodIntf, final String className, String methodName, String... methodParams) { ArrayKey methodParamsKey = new ArrayKey((Object[]) methodParams); if (methodIntf == null) return style3.pick(className).pick(methodName).get(methodParamsKey); else return perViewStyle3.pick(methodIntf).pick(methodName).get(methodParamsKey); } public T getDefaultAttribute() { return defaultAttribute; } public void setDefaultAttribute(final T defaultAttribute) { this.defaultAttribute = defaultAttribute; } /** * Returns true if the given transaction specification was expliitly specified at a method level, returns * false if it was inherited from the default */ public boolean isMethodLevel(MethodInterfaceType methodIntf, Method method, MethodInterfaceType defaultMethodIntf) { assert methodIntf != null : "methodIntf is null"; assert method != null : "method is null"; Method classMethod = resolveRealMethod(method); String[] methodParams = MethodInfoHelper.getCanonicalParameterTypes(classMethod); final String methodName = classMethod.getName(); final String className = classMethod.getDeclaringClass().getName(); ArrayKey methodParamsKey = new ArrayKey((Object[]) methodParams); T attr = get(get(get(perViewStyle3, methodIntf), methodName), methodParamsKey); if (attr != null) return true; attr = get(get(perViewStyle2, methodIntf), methodName); if (attr != null) return true; attr = get(perViewStyle1, methodIntf); if (attr != null) return false; attr = get(get(get(style3, className), methodName), methodParamsKey); if (attr != null) return true; attr = get(style2, methodName); if (attr != null) return true; attr = get(style1, className); if (attr != null) return false; if(defaultMethodIntf == null) { return false; } else { return isMethodLevel(defaultMethodIntf, method, null); } } /** * Makes an array usable as a key. * * @author <a href="mailto:[email protected]">Carlo de Wolf</a> */ private static class ArrayKey { private final Object[] a; private final int hashCode; private transient String s; ArrayKey(Object... a) { this.a = a; this.hashCode = Arrays.hashCode(a); } @Override public boolean equals(Object obj) { if (!(obj instanceof ArrayKey)) return false; return Arrays.equals(a, ((ArrayKey) obj).a); } @Override public int hashCode() { return hashCode; } @Override public String toString() { if (s == null) this.s = Arrays.toString(a); return s; } } /** * @author <a href="mailto:[email protected]">Carlo de Wolf</a> */ private abstract static class PopulatingMap<K, V> extends HashMap<K, V> { V pick(K key) { V value = get(key); if (value == null) { value = populate(); put(key, value); } return value; } abstract V populate(); } private static <K, V> V get(Map<K, V> map, K key) { if (map == null) return null; return map.get(key); } }
15,136
35.126492
193
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/deployment/DeploymentRepository.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.deployment; import java.util.Map; /** * @author Radoslav Husar */ public interface DeploymentRepository { void add(DeploymentModuleIdentifier identifier, ModuleDeployment deployment); boolean startDeployment(DeploymentModuleIdentifier identifier); void addListener(DeploymentRepositoryListener listener); void removeListener(DeploymentRepositoryListener listener); void remove(DeploymentModuleIdentifier identifier); void suspend(); void resume(); boolean isSuspended(); /** * Returns all deployments. These deployments may not be in a started state, i.e. not all components might be ready to receive invocations. * * @return all deployments */ Map<DeploymentModuleIdentifier, ModuleDeployment> getModules(); /** * Returns all deployments that are in a started state, i.e. all components are ready to receive invocations. * * @return all started deployments */ Map<DeploymentModuleIdentifier, ModuleDeployment> getStartedModules(); }
2,087
32.142857
143
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/deployment/ApplicationExceptionDescriptions.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.deployment; import java.util.Collections; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.jboss.as.ejb3.logging.EjbLogger; import org.jboss.as.ejb3.tx.ApplicationExceptionDetails; /** * @author Stuart Douglas */ public class ApplicationExceptionDescriptions { private final Map<String, ApplicationExceptionDetails> applicationExceptions = new ConcurrentHashMap<String, ApplicationExceptionDetails>(); public void addApplicationException(final String exceptionClassName, final boolean rollback, final boolean inherited) { if (exceptionClassName == null || exceptionClassName.isEmpty()) { throw EjbLogger.ROOT_LOGGER.stringParamCannotBeNullOrEmpty("Exception class name"); } //TODO: Is this a good idea? ApplicationException's equals/hashCode //will not work the way that would be expected ApplicationExceptionDetails appException = new ApplicationExceptionDetails(exceptionClassName, inherited, rollback); // add it to the map this.applicationExceptions.put(exceptionClassName, appException); } public Map<String, ApplicationExceptionDetails> getApplicationExceptions() { return Collections.unmodifiableMap(this.applicationExceptions); } }
2,319
41.181818
144
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/deployment/DeploymentModuleIdentifier.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.deployment; import org.jboss.as.ejb3.logging.EjbLogger; import java.io.Serializable; import java.util.Objects; /** * Identifier for a deployed module, consisting of application + distinct + module name. * * @author Stuart Douglas */ public final class DeploymentModuleIdentifier implements Serializable { private final String applicationName; private final String moduleName; private final String distinctName; public DeploymentModuleIdentifier(String applicationName, String moduleName, String distinctName) { if (applicationName == null) { throw EjbLogger.ROOT_LOGGER.paramCannotBeNull("Application name"); } if (moduleName == null) { throw EjbLogger.ROOT_LOGGER.paramCannotBeNull("Module name"); } if (distinctName == null) { throw EjbLogger.ROOT_LOGGER.paramCannotBeNull("Distinct name"); } this.applicationName = applicationName; this.moduleName = moduleName; this.distinctName = distinctName; } public String getApplicationName() { return applicationName; } public String getModuleName() { return moduleName; } public String getDistinctName() { return distinctName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DeploymentModuleIdentifier that = (DeploymentModuleIdentifier) o; if (!applicationName.equals(that.applicationName)) return false; if (!Objects.equals(distinctName, that.distinctName)) return false; if (!moduleName.equals(that.moduleName)) return false; return true; } @Override public int hashCode() { int result = applicationName.hashCode(); result = 31 * result + moduleName.hashCode(); result = 31 * result + (distinctName != null ? distinctName.hashCode() : 0); return result; } @Override public String toString() { return "DeploymentModuleIdentifier{" + "applicationName='" + applicationName + '\'' + ", moduleName='" + moduleName + '\'' + ", distinctName='" + distinctName + '\'' + '}'; } }
3,343
32.777778
103
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/deployment/EjbJarDescription.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.deployment; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.jboss.as.ee.component.EEModuleDescription; import org.jboss.as.ejb3.logging.EjbLogger; /** * User: jpai */ public class EjbJarDescription { private final EEModuleDescription eeModuleDescription; private final Set<String> applicationLevelSecurityRoles = new HashSet<String>(); /** * True if this represents EJB's packaged in a war */ private final boolean war; public EjbJarDescription(EEModuleDescription eeModuleDescription, boolean war) { this.war = war; if (eeModuleDescription == null) { throw EjbLogger.ROOT_LOGGER.paramCannotBeNull("EE module description"); } this.eeModuleDescription = eeModuleDescription; } public void addSecurityRole(final String role) { if (role == null || role.trim().isEmpty()) { throw EjbLogger.ROOT_LOGGER.stringParamCannotBeNullOrEmpty("Security role"); } this.applicationLevelSecurityRoles.add(role); } /** * Returns the security roles that have been defined at the application level (via security-role elements in the * ejb-jar.xml). Note that this set does *not* include the roles that have been defined at each individual component * level (via @DeclareRoles, @RolesAllowed annotations or security-role-ref element) * <p/> * Returns an empty set if no roles have been defined at the application level. * * @return */ public Set<String> getSecurityRoles() { return Collections.unmodifiableSet(this.applicationLevelSecurityRoles); } public boolean hasComponent(String componentName) { return eeModuleDescription.hasComponent(componentName); } public EEModuleDescription getEEModuleDescription() { return this.eeModuleDescription; } public boolean isWar() { return war; } }
3,006
32.786517
120
java
null
wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/deployment/ModuleDeployment.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.ejb3.deployment; import org.jboss.as.ee.component.deployers.StartupCountdown; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.jboss.msc.value.InjectedValue; import java.util.Collections; import java.util.Map; /** * Represents a deployed module on AS7 * * @author Stuart Douglas */ public class ModuleDeployment implements Service<ModuleDeployment> { public static final ServiceName SERVICE_NAME = ServiceName.of("moduleDeploymentRuntimeInformation"); public static final ServiceName START_SERVICE_NAME = ServiceName.of("moduleDeploymentRuntimeInformationStart"); private final DeploymentModuleIdentifier identifier; private final InjectedValue<DeploymentRepository> deploymentRepository = new InjectedValue<DeploymentRepository>(); private final Map<String, EjbDeploymentInformation> ejbs; public ModuleDeployment(DeploymentModuleIdentifier identifier, Map<String, EjbDeploymentInformation> ejbs) { this.identifier = identifier; this.ejbs = Collections.unmodifiableMap(ejbs); } public DeploymentModuleIdentifier getIdentifier() { return identifier; } public Map<String, EjbDeploymentInformation> getEjbs() { return ejbs; } public InjectedValue<DeploymentRepository> getDeploymentRepository() { return deploymentRepository; } @Override public void start(StartContext context) throws StartException { deploymentRepository.getValue().add(identifier, ModuleDeployment.this); } @Override public void stop(StopContext context) { deploymentRepository.getValue().remove(identifier); } @Override public ModuleDeployment getValue() throws IllegalStateException, IllegalArgumentException { return this; } /** * service that marks a module a started */ public static final class ModuleDeploymentStartService implements Service<Void> { private final DeploymentModuleIdentifier identifier; private final InjectedValue<DeploymentRepository> deploymentRepository = new InjectedValue<DeploymentRepository>(); private final StartupCountdown countdown; public ModuleDeploymentStartService(DeploymentModuleIdentifier identifier, StartupCountdown countdown) { this.identifier = identifier; this.countdown = countdown; } @Override public void start(StartContext startContext) throws StartException { Runnable action = new Runnable() { @Override public void run() { deploymentRepository.getValue().startDeployment(identifier); } }; if (countdown == null) action.run(); else countdown.addCallback(action); } @Override public void stop(StopContext stopContext) { } @Override public Void getValue() throws IllegalStateException, IllegalArgumentException { return null; } public InjectedValue<DeploymentRepository> getDeploymentRepository() { return deploymentRepository; } } }
4,360
34.169355
123
java