public void start() throws Exception { log.info("Starting Gravity..."); synchronized (this) { if (!started) { adapterFactory = new AdapterFactory(this); internalStart(); serverChannel = new ServerChannel(this, ServerChannel.class.getName(), null, null); if (gravityConfig.isUseUdp()) { ServiceLoader<UdpReceiverFactory> loader = ServiceLoader.load(UdpReceiverFactory.class); Iterator<UdpReceiverFactory> factories = loader.iterator(); if (factories.hasNext()) { udpReceiverFactory = factories.next(); udpReceiverFactory.setPort(gravityConfig.getUdpPort()); udpReceiverFactory.setNio(gravityConfig.isUdpNio()); udpReceiverFactory.setConnected(gravityConfig.isUdpConnected()); udpReceiverFactory.setSendBufferSize(gravityConfig.getUdpSendBufferSize()); udpReceiverFactory.start(); } else log.warn("UDP receiver factory not found"); } started = true; } } log.info("Gravity successfully started."); }
/* * (non-Javadoc) * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (log.isInfoEnabled()) try { GraniteContext context = HttpGraniteContext.createThreadIntance( graniteConfig, servicesConfig, getServletContext(), request, response); if (context == null) throw new ServletException("GraniteContext not Initialized!!"); // AMFContextImpl amf = (AMFContextImpl) context.getAMFContext(); // Phase1 Deserializing AMF0 request if (log.isInfoEnabled()) log.info(">>>>> Deserializing AMF0 request from..." + request.getRequestURI()); AMF0Deserializer deserializer = new AMF0Deserializer(new DataInputStream(request.getInputStream())); AMF0Message amf0Request = deserializer.getAMFMessage(); // Phase2 Processing AMF0 request if (log.isInfoEnabled()) log.info(">>>>> Processing AMF0 request: " + amf0Request); AMF0Message amf0Response = AMF0MessageProcessor.process(amf0Request); if (log.isInfoEnabled()) log.info("<<<<< Returning AMF0 response: " + amf0Response); // Phase3 Send back response to the client response.setContentType(AMF0Message.CONTENT_TYPE); AMF0Serializer serializer = new AMF0Serializer(new DataOutputStream(response.getOutputStream())); serializer.serializeMessage(amf0Response); if (log.isInfoEnabled()) log.info("...End of Processing AMF Request......"); } catch (Exception e) { log.error(e, "Could not handle AMF request"); throw new ServletException(e); } }
private Message handleSecurityMessage(CommandMessage message) { GraniteConfig config = GraniteContext.getCurrentInstance().getGraniteConfig(); Message response = null; if (!config.hasSecurityService()) log.warn( "Ignored security operation (no security settings in granite-config.xml): %s", message); else if (!config.getSecurityService().acceptsContext()) log.info( "Ignored security operation (security service does not handle this kind of granite context)", message); else { SecurityService securityService = config.getSecurityService(); try { if (message.isLoginOperation()) securityService.login( message.getBody(), (String) message.getHeader(Message.CREDENTIALS_CHARSET_HEADER)); else securityService.logout(); } catch (Exception e) { if (e instanceof SecurityServiceException) log.debug(e, "Could not process security operation: %s", message); else log.error(e, "Could not process security operation: %s", message); response = new ErrorMessage(message, e, true); } } if (response == null) { response = new AcknowledgeMessage(message, true); // For SDK 2.0.1_Hotfix2. if (message.isSecurityOperation()) response.setBody("success"); } return response; }
public void receive(AsyncMessage message) throws MessageReceivingException { if (message == null) throw new NullPointerException("message cannot be null"); GravityInternal gravity = getGravity(); if (udpReceiver != null) { if (udpReceiver.isClosed()) return; try { udpReceiver.receive(message); } catch (MessageReceivingException e) { if (e.getCause() instanceof SocketException) { log.debug(e, "Closing unreachable UDP channel %s", getId()); udpReceiver.close(false); } else log.error(e, "Cannot access UDP channel %s", getId()); } return; } receivedQueueLock.lock(); try { if (receivedQueue.size() + 1 > gravity.getGravityConfig().getMaxMessagesQueuedPerChannel()) throw new MessageReceivingException( message, "Could not queue message (channel's queue is full) for channel: " + this); log.debug( "Channel %s queue message %s for client %s", getId(), message.getMessageId(), message.getClientId()); receivedQueue.add(message); } finally { receivedQueueLock.unlock(); } if (hasAsyncHttpContext()) receiver.queue(gravity); }
public Object authorize(AbstractSecurityContext context) throws Exception { log.debug("Authorize: %s", context); log.debug( "Is %s secured? %b", context.getDestination().getId(), context.getDestination().isSecured()); startAuthorization(context); HttpGraniteContext graniteContext = (HttpGraniteContext) GraniteContext.getCurrentInstance(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); SecurityContext securityContextBefore = null; int securityContextHashBefore = 0; if (graniteContext.getRequest().getAttribute(FILTER_APPLIED) == null) { securityContextBefore = loadSecurityContextFromSession(); if (securityContextBefore == null) securityContextBefore = SecurityContextHolder.getContext(); else securityContextHashBefore = securityContextBefore.hashCode(); SecurityContextHolder.setContext(securityContextBefore); authentication = securityContextBefore.getAuthentication(); } if (context.getDestination().isSecured()) { if (!isAuthenticated(authentication) || authentication instanceof AnonymousAuthenticationToken) { log.debug("Is not authenticated!"); throw SecurityServiceException.newNotLoggedInException("User not logged in"); } if (!userCanAccessService(context, authentication)) { log.debug("Access denied for: %s", authentication.getName()); throw SecurityServiceException.newAccessDeniedException("User not in required role"); } } try { Object returnedObject = securityInterceptor != null ? securityInterceptor.invoke(context) : endAuthorization(context); return returnedObject; } catch (AccessDeniedException e) { throw SecurityServiceException.newAccessDeniedException(e.getMessage()); } catch (InvocationTargetException e) { handleAuthorizationExceptions(e); throw e; } finally { if (graniteContext.getRequest().getAttribute(FILTER_APPLIED) == null) { // Do this only when not already filtered by Spring Security SecurityContext securityContextAfter = SecurityContextHolder.getContext(); SecurityContextHolder.clearContext(); saveSecurityContextInSession(securityContextAfter, securityContextHashBefore); } } }
protected boolean userCanAccessService( AbstractSecurityContext context, Authentication authentication) { log.debug("Is authenticated as: %s", authentication.getName()); for (String role : context.getDestination().getRoles()) { if (isUserInRole(authentication, role)) { log.debug("Allowed access to %s in role %s", authentication.getName(), role); return true; } log.debug("Access denied for %s not in role %s", authentication.getName(), role); } return false; }
@Validate public void start() { log.debug("Start OSGiServiceSimple: " + toString()); if (servicesConfig.findServiceById(id) == null) { // Clear destinations destinations.clear(); servicesConfig.addService(this); started = true; } else { log.error("Service \"" + id + "\" already registered"); } }
protected void createUdpReceiver(UdpReceiverFactory factory, AsyncHttpContext asyncHttpContext) { OutputStream os = null; try { Message connectMessage = asyncHttpContext.getConnectMessage(); if (udpReceiver == null || udpReceiver.isClosed()) udpReceiver = factory.newReceiver(this, asyncHttpContext.getRequest(), connectMessage); AsyncMessage reply = udpReceiver.acknowledge(connectMessage); HttpServletRequest request = asyncHttpContext.getRequest(); HttpServletResponse response = asyncHttpContext.getResponse(); GraniteContext context = HttpGraniteContext.createThreadIntance( gravity.getGraniteConfig(), gravity.getServicesConfig(), null, request, response); ((AMFContextImpl) context.getAMFContext()) .setCurrentAmf3Message(asyncHttpContext.getConnectMessage()); GravityServletUtil.serialize( gravity, response, new AsyncMessage[] {reply}, ContentType.forMimeType(request.getContentType())); } catch (ServletException e) { log.error(e, "Could not send UDP connect acknowledgement to channel: %s", this); } catch (IOException e) { log.error(e, "Could not send UDP connect acknowledgement to channel: %s", this); } finally { try { GraniteContext.release(); } catch (Exception e) { // should never happen... } // Close output stream. try { if (os != null) { try { os.close(); } catch (IOException e) { log.warn(e, "Could not close output stream (ignored)"); } } } finally { releaseAsyncHttpContext(asyncHttpContext); } } }
/** * @author Cameron INGRAM * @author Venkat DANDA */ public class SeamServiceInvoker extends ServiceInvoker<SeamServiceFactory> { private static final long serialVersionUID = 1L; private static final Logger log = Logger.getLogger(SeamServiceInvoker.class); public static final String CAPITALIZED_DESTINATION_ID = "{capitalized.destination.id}"; public static final String DESTINATION_ID = "{destination.id}"; public SeamServiceInvoker(Destination destination, SeamServiceFactory factory, Object instance) throws ServiceException { super(destination, factory); this.invokee = instance; } @Override protected void beforeInvocation(ServiceInvocationContext context) { log.debug("Before Invocation"); } @Override protected Object afterInvocation(ServiceInvocationContext context, Object result) { log.debug("After Invocation"); return result; } }
public Principal login(Object credentials, String charset) { List<String> decodedCredentials = Arrays.asList(decodeBase64Credentials(credentials, charset)); HttpGraniteContext context = (HttpGraniteContext) GraniteContext.getCurrentInstance(); HttpServletRequest httpRequest = context.getRequest(); String user = decodedCredentials.get(0); String password = decodedCredentials.get(1); Authentication auth = new UsernamePasswordAuthenticationToken(user, password); Principal principal = null; ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext( httpRequest.getSession().getServletContext()); if (ctx != null) { AbstractAuthenticationManager authenticationManager = BeanFactoryUtils.beanOfTypeIncludingAncestors(ctx, AbstractAuthenticationManager.class); try { Authentication authentication = authenticationManager.authenticate(auth); SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(authentication); principal = authentication; SecurityContextHolder.setContext(securityContext); saveSecurityContextInSession(securityContext, 0); endLogin(credentials, charset); } catch (AuthenticationException e) { handleAuthenticationExceptions(e); } } log.debug("User %s logged in", user); return principal; }
@Invalidate public void stop() { log.debug("Stop OSGiServiceSimple: " + toString()); if (servicesConfig != null) { servicesConfig.removeService(id); started = false; } }
public boolean handleMarkerItem(ScannedItem item) { try { return handleProperties(item.loadAsProperties()); } catch (Exception e) { log.error(e, "Could not load properties: %s", item); } return true; }
public Channel removeChannel(String channelId, boolean timeout) { if (channelId == null) return null; // Remove existing channel id/subscriptions in distributed data (clustering). try { DistributedData gdd = graniteConfig.getDistributedDataFactory().getInstance(); if (gdd != null) { log.debug("Removing channel id from distributed data: %s", channelId); gdd.removeChannelId(channelId); } } catch (Exception e) { log.error(e, "Could not remove channel id from distributed data: %s", channelId); } TimeChannel<?> timeChannel = channels.get(channelId); Channel channel = null; if (timeChannel != null) { try { if (timeChannel.getTimerTask() != null) timeChannel.getTimerTask().cancel(); } catch (Exception e) { // Should never happen... } channel = timeChannel.getChannel(); try { for (Subscription subscription : channel.getSubscriptions()) { try { Message message = subscription.getUnsubscribeMessage(); handleMessage(channel.getFactory(), message, true); } catch (Exception e) { log.error( e, "Error while unsubscribing channel: %s from subscription: %s", channel, subscription); } } } finally { channels.remove(channelId); channel.destroy(timeout); } } return channel; }
public void init(FilterConfig config) throws ServletException { String dumpDirString = ServletParams.get(config, DUMP_DIR, String.class, null); if (dumpDirString != null) { File dumpDir = new File(dumpDirString); if (!dumpDir.exists() || !dumpDir.isDirectory() || !dumpDir.canWrite()) log.warn("Ignoring dump directory (is it a writable directory?): %s", dumpDir); else this.dumpDir = dumpDir; } }
private boolean handleProperties(Properties properties) { if (properties.getProperty("dependsOn") != null) { String dependsOn = properties.getProperty("dependsOn"); try { TypeUtil.forName(dependsOn); } catch (ClassNotFoundException e) { // Class not found, skip scan for this package return true; } } String classGetterName = properties.getProperty("classGetter"); if (!classGetterSet && classGetterName != null) { try { classGetter = TypeUtil.newInstance(classGetterName, ClassGetter.class); } catch (Throwable t) { log.error(t, "Could not create instance of: %s", classGetterName); } } String amf3MessageInterceptorName = properties.getProperty("amf3MessageInterceptor"); if (amf3MessageInterceptor == null && amf3MessageInterceptorName != null) { try { amf3MessageInterceptor = TypeUtil.newInstance(amf3MessageInterceptorName, AMF3MessageInterceptor.class); } catch (Throwable t) { log.error(t, "Could not create instance of: %s", amf3MessageInterceptorName); } } for (Map.Entry<?, ?> me : properties.entrySet()) { if (me.getKey().toString().startsWith("converter.")) { String converterName = me.getValue().toString(); try { converterClasses.add(TypeUtil.forName(converterName, Converter.class)); } catch (Exception e) { throw new GraniteConfigException( "Could not get converter class for: " + converterName, e); } } } return false; }
private void dumpBytes(String label, byte[] bytes) { StringBuilder hexSb = new StringBuilder(); StringBuilder charSb = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { int b = bytes[i] & 0xFF; if (hexSb.length() > 0) { hexSb.append(' '); charSb.append(' '); } hexSb.append(HEXS.charAt(b >> 4)).append(HEXS.charAt(b & 0x0F)); if (b >= 0x20 && b <= 0x7e) charSb.append(' ').append((char) b); else charSb.append("##"); } log.info("[RAW %s] {\n%s\n%s\n}", label.toUpperCase(), hexSb.toString(), charSb.toString()); if (dumpDir != null) { File file = new File( dumpDir.getPath() + File.separator + label + "_" + System.currentTimeMillis() + ".amf"); for (int i = 1; i < 100 && file.exists(); i++) file = new File(file.getAbsolutePath() + "." + i); OutputStream os = null; try { os = new FileOutputStream(file); os.write(bytes); } catch (Exception e) { log.error(e, "Could not write dump file: %s", file); } finally { if (os != null) try { os.close(); } catch (Exception e) { } } } }
protected List<ExtendedObjectCodec> detectExtendedObjectCodecs() { log.info("Auto detecting extended object codec..."); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); for (String factoryName : CODEC_EXTENSION_FACTORY_NAMES) { try { CodecExtensionFactory factory = (CodecExtensionFactory) classLoader.loadClass(factoryName).newInstance(); List<ExtendedObjectCodec> extendedObjectCodecs = factory.getCodecs(); log.info("Using %s: %s", factoryName, extendedObjectCodecs); return extendedObjectCodecs; } catch (Throwable t) { log.debug(t, "Could not load factory: %s", factoryName); } } log.info("No extended object codec detected"); return Collections.emptyList(); }
public void contextInitialized(ServletContextEvent event) { log.info("Loading JMF shared context"); ServletContext servletContext = event.getServletContext(); List<ExtendedObjectCodec> extendedObjectCodecs = loadExtendedObjectCodecs(servletContext); List<String> defaultStoredStrings = loadDefaultStoredStrings(servletContext); SharedContext sharedContext = new DefaultSharedContext( new DefaultCodecRegistry(extendedObjectCodecs), null, defaultStoredStrings); servletContext.setAttribute(SHARED_CONTEXT_KEY, sharedContext); SharedContext dumpSharedContext = new DefaultSharedContext(new DefaultCodecRegistry(), null, defaultStoredStrings); servletContext.setAttribute(DUMP_SHARED_CONTEXT_KEY, dumpSharedContext); log.info("JMF shared context loaded"); }
/* (non-Javadoc) * @see org.granite.tide.ejb.EJBServiceContextIntf#postCall(org.granite.messaging.service.ServiceInvocationContext, java.lang.Object, java.lang.String) */ @Override public IInvocationResult postCall( ServiceInvocationContext context, Object result, String componentName, Class<?> componentClass) { try { AbstractContext threadContext = AbstractContext.instance(); List<ContextUpdate> results = new ArrayList<ContextUpdate>(threadContext.size()); DataContext dataContext = DataContext.get(); Set<Object[]> dataUpdates = dataContext != null ? dataContext.getDataUpdates() : null; Object[][] updates = null; if (dataUpdates != null && !dataUpdates.isEmpty()) updates = dataUpdates.toArray(new Object[dataUpdates.size()][]); for (Map.Entry<String, Object> entry : threadContext.entrySet()) results.add(new ContextUpdate(entry.getKey(), null, entry.getValue(), 3, false)); InvocationResult ires = new InvocationResult(result, results); if (context.getBean() != null) { if (context.getBean().getClass().isAnnotationPresent(BypassTideMerge.class)) ires.setMerge(false); else { try { Method m = context .getBean() .getClass() .getMethod( context.getMethod().getName(), context.getMethod().getParameterTypes()); if (m.isAnnotationPresent(BypassTideMerge.class)) ires.setMerge(false); } catch (Exception e) { log.warn("Could not find bean method", e); } } } ires.setUpdates(updates); ires.setEvents(new ArrayList<ContextEvent>(threadContext.getRemoteEvents())); if (componentName != null) { EjbComponent component = ejbLookupCache.get(componentName); if (component != null && component.ejbMetadata != null && component.ejbMetadata.isStateful() && component.ejbMetadata.isRemoveMethod(context.getMethod())) ejbLookupCache.remove(componentName); } return ires; } finally { AbstractContext.remove(); } }
public void encode(ExtendedObjectOutput out, Object v) throws IOException, IllegalAccessException, InvocationTargetException { String detachedState = null; if (v instanceof HibernateProxy) { HibernateProxy proxy = (HibernateProxy) v; // Only write initialized flag, detachedState & id if v is an uninitialized proxy. if (proxy.getHibernateLazyInitializer().isUninitialized()) { Class<?> persistentClass = proxy.getHibernateLazyInitializer().getPersistentClass(); if (!serializableProxyAdapters.containsKey(persistentClass)) { try { SerializableProxyAdapter proxyAdapter = new SerializableProxyAdapter(proxy); serializableProxyAdapters.putIfAbsent(persistentClass, proxyAdapter); } catch (Exception e) { throw new IOException("Could not create SerializableProxyAdapter for: " + proxy); } } Serializable id = proxy.getHibernateLazyInitializer().getIdentifier(); log.debug("Writing uninitialized HibernateProxy %s with id %s", detachedState, id); out.writeBoolean(false); out.writeUTF(null); out.writeObject(id); return; } // Proxy is initialized, get the underlying persistent object. log.debug("Writing initialized HibernateProxy..."); v = proxy.getHibernateLazyInitializer().getImplementation(); } // Write initialized flag & detachedState. out.writeBoolean(true); out.writeUTF(null); // Write all properties in lexical order. List<Property> properties = out.getReflection().findSerializableProperties(v.getClass()); for (Property property : properties) out.getAndWriteProperty(v, property); }
protected void internalStart() { gravityPool = new GravityPool(gravityConfig); channelsTimer = new Timer(); if (graniteConfig.isRegisterMBeans()) { try { ObjectName name = new ObjectName( "org.graniteds:type=Gravity,context=" + graniteConfig.getMBeanContextName()); log.info("Registering MBean: %s", name); OpenMBean mBean = OpenMBean.createMBean(this); MBeanServerLocator.getInstance().register(mBean, name, true); } catch (Exception e) { log.error( e, "Could not register Gravity MBean for context: %s", graniteConfig.getMBeanContextName()); } } }
private void scanConfig(String graniteConfigProperties) { // if config overriding exists Scanner scanner = ScannerFactory.createScanner( this, graniteConfigProperties != null ? graniteConfigProperties : GRANITE_CONFIG_PROPERTIES); try { scanner.scan(); } catch (Exception e) { log.error(e, "Could not scan classpath for configuration"); } }
private Message handleUnsubscribeMessage( final ChannelFactory<?> channelFactory, CommandMessage message) { Channel channel = getChannel(channelFactory, (String) message.getClientId()); if (channel == null) return handleUnknownClientMessage(message); AsyncMessage reply = null; ServiceAdapter adapter = adapterFactory.getServiceAdapter(message); reply = (AcknowledgeMessage) adapter.manage(channel, message); postManage(channel); if (!(reply instanceof ErrorMessage)) { // Remove subscription message in distributed data (clustering). try { DistributedData gdd = graniteConfig.getDistributedDataFactory().getInstance(); if (gdd != null) { String subscriptionId = (String) message.getHeader(AsyncMessage.DESTINATION_CLIENT_ID_HEADER); log.debug( "Removing subscription message from channel info: %s - %s", channel.getId(), subscriptionId); gdd.removeSubcription(channel.getId(), subscriptionId); } } catch (Exception e) { log.error( e, "Could not remove subscription from distributed data: %s - %s", channel.getId(), message.getHeader(AsyncMessage.DESTINATION_CLIENT_ID_HEADER)); } } reply.setDestination(message.getDestination()); reply.setClientId(channel.getId()); reply.getHeaders().putAll(message.getHeaders()); return reply; }
private void handleClass(Class<?> clazz) { if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) return; if (Externalizer.class.isAssignableFrom(clazz)) { try { scannedExternalizers.add(TypeUtil.newInstance(clazz, Externalizer.class)); } catch (Exception e) { log.error(e, "Could not create new instance of: %s", clazz); } } if (ExceptionConverter.class.isAssignableFrom(clazz)) { try { exceptionConverters.add(TypeUtil.newInstance(clazz, ExceptionConverter.class)); } catch (Exception e) { if (!clazz .getName() .equals("org.granite.tide.hibernate.HibernateValidatorExceptionConverter")) // GDS-582 log.error(e, "Could not create new instance of: %s", clazz); } } }
public void stop(boolean now) throws Exception { log.info("Stopping Gravity (now=%s)...", now); synchronized (this) { if (adapterFactory != null) { try { adapterFactory.stopAll(); } catch (Exception e) { log.error(e, "Error while stopping adapter factory"); } adapterFactory = null; } if (serverChannel != null) { try { removeChannel(serverChannel.getId(), false); } catch (Exception e) { log.error(e, "Error while removing server channel: %s", serverChannel); } serverChannel = null; } if (channelsTimer != null) { try { channelsTimer.cancel(); } catch (Exception e) { log.error(e, "Error while cancelling channels timer"); } channelsTimer = null; } if (gravityPool != null) { try { if (now) gravityPool.shutdownNow(); else gravityPool.shutdown(); } catch (Exception e) { log.error(e, "Error while stopping thread pool"); } gravityPool = null; } if (udpReceiverFactory != null) { try { udpReceiverFactory.stop(); } catch (Exception e) { log.error(e, "Error while stopping udp receiver factory"); } udpReceiverFactory = null; } started = false; } log.info("Gravity sucessfully stopped."); }
@Override public Set<Class<?>> scan(Set<String> packageNames) { Set<Class<?>> classes = new HashSet<Class<?>>(); Scanner scanner = ScannerFactory.createScanner(new MessagingScannedItemHandler(packageNames, classes), null); try { scanner.scan(); } catch (Exception e) { log.error(e, "Could not scan classpath for @RemoteAlias"); } return classes; }
public void handleScannedItem(ScannedItem item) { if ("class".equals(item.getExtension()) && item.getName().indexOf('$') == -1) { try { handleClass(item.loadAsClass()); } catch (NoClassDefFoundError e) { // Ignore errors with Tide classes depending on Gravity } catch (LinkageError e) { // Ignore errors with GraniteDS/Hibernate classes depending on Hibernate 3 when using // Hibernate 4 } catch (Throwable t) { log.error(t, "Could not load class: %s", item); } } }
public void registerExceptionConverter( Class<? extends ExceptionConverter> exceptionConverterClass, boolean first) { for (ExceptionConverter ec : exceptionConverters) { if (ec.getClass() == exceptionConverterClass) return; } try { ExceptionConverter exceptionConverter = TypeUtil.newInstance(exceptionConverterClass, ExceptionConverter.class); if (first) exceptionConverters.add(0, exceptionConverter); else exceptionConverters.add(exceptionConverter); } catch (Exception e) { log.error(e, "Could not instantiate exception converter: %s", exceptionConverterClass); } }
public boolean access(String channelId) { if (channelId != null) { TimeChannel<?> timeChannel = channels.get(channelId); if (timeChannel != null) { synchronized (timeChannel) { TimerTask timerTask = timeChannel.getTimerTask(); if (timerTask != null) { log.debug("Canceling TimerTask: %s", timerTask); timerTask.cancel(); timeChannel.setTimerTask(null); } timerTask = new ChannelTimerTask(this, channelId); timeChannel.setTimerTask(timerTask); long timeout = gravityConfig.getChannelIdleTimeoutMillis(); log.debug("Scheduling TimerTask: %s for %s ms.", timerTask, timeout); channelsTimer.schedule(timerTask, timeout); return true; } } } return false; }
@SuppressWarnings("unchecked") public <C extends Channel> C getChannel(ChannelFactory<C> channelFactory, String clientId) { if (clientId == null) return null; TimeChannel<C> timeChannel = (TimeChannel<C>) channels.get(clientId); if (timeChannel == null) { // Look for existing channel id/subscriptions in distributed data (clustering). log.debug("Lookup channel %s in distributed data", clientId); try { DistributedData gdd = graniteConfig.getDistributedDataFactory().getInstance(); if (gdd != null && gdd.hasChannelId(clientId)) { log.debug("Found channel id in distributed data: %s", clientId); String channelFactoryClassName = gdd.getChannelFactoryClassName(clientId); String clientType = gdd.getChannelClientType(clientId); channelFactory = (ChannelFactory<C>) TypeUtil.newInstance( channelFactoryClassName, new Class<?>[] {Gravity.class}, new Object[] {this}); C channel = channelFactory.newChannel(clientId, clientType); timeChannel = new TimeChannel<C>(channel); if (channels.putIfAbsent(clientId, timeChannel) == null) { for (CommandMessage subscription : gdd.getSubscriptions(clientId)) { log.debug("Resubscribing channel: %s - %s", clientId, subscription); handleSubscribeMessage(channelFactory, subscription, false); } access(clientId); } } } catch (Exception e) { log.error( e, "Could not recreate channel/subscriptions from distributed data: %s", clientId); } } return (timeChannel != null ? timeChannel.getChannel() : null); }