List of usage examples for org.apache.commons.configuration Configuration getLong
Long getLong(String key, Long defaultValue);
From source file:org.janusgraph.olap.PageRankVertexProgram.java
@Override public void loadState(final Graph graph, final Configuration configuration) { dampingFactor = configuration.getDouble(DAMPING_FACTOR, 0.85D); maxIterations = configuration.getInt(MAX_ITERATIONS, 10); vertexCount = configuration.getLong(VERTEX_COUNT, 1L); }
From source file:org.jwebsocket.sso.Main.java
/** * * @param args//from w w w . j av a 2 s. com */ public static void main(String[] args) { // set up log4j logging // later this should be read from a shared log4j properties or xml file! Properties lProps = new Properties(); lProps.setProperty("log4j.rootLogger", "INFO, console"); lProps.setProperty("log4j.logger.org.apache.activemq.spring", "WARN"); lProps.setProperty("log4j.logger.org.apache.activemq.web.handler", "WARN"); lProps.setProperty("log4j.logger.org.springframework", "WARN"); lProps.setProperty("log4j.logger.org.apache.xbean", "WARN"); lProps.setProperty("log4j.logger.org.apache.camel", "INFO"); lProps.setProperty("log4j.logger.org.eclipse.jetty", "WARN"); lProps.setProperty("log4j.appender.console", "org.apache.log4j.ConsoleAppender"); lProps.setProperty("log4j.appender.console.layout", "org.apache.log4j.PatternLayout"); lProps.setProperty("log4j.appender.console.layout.ConversionPattern", // "%p: %m%n" "%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p - %C{1}: %m%n"); // set here the jWebSocket log level: lProps.setProperty("log4j.logger.org.jwebsocket", "DEBUG"); lProps.setProperty("log4j.appender.console.threshold", "DEBUG"); PropertyConfigurator.configure(lProps); mLog.info("jWebSocket SSO (OAuth) Demo Client"); Configuration lConfig = null; boolean lConfigLoaded; try { // loading properties files lConfig = new PropertiesConfiguration("/private/SSO.properties"); } catch (ConfigurationException ex) { } if (null == lConfig) { mLog.info("Configuration file could not be opened."); return; } final String lSMHost = lConfig.getString("SMHost"); final String lOAuthHost = lConfig.getString("OAuthHost"); final String lOAuthAppId = lConfig.getString("OAuthAppId"); final String lOAuthAppSecret = lConfig.getString("OAuthAppSecret"); final String lOAuthUsername = lConfig.getString("OAuthUsername"); final String lOAuthPassword = lConfig.getString("OAuthPassword"); long lOAuthTimeout = lConfig.getLong("OAuthTimeout", 5000); // TODO: Validate config data here! lConfigLoaded = true; if (!lConfigLoaded) { mLog.error("Config not loaded."); System.exit(1); } OAuth lOAuth = new OAuth(); lOAuth.setOAuthHost(lOAuthHost); lOAuth.setOAuthAppId(lOAuthAppId); lOAuth.setOAuthAppSecret(lOAuthAppSecret); // SiteMinder.setSMHost(lSMHost); // String lSMSession = SiteMinder.getSSOSession(5000); // mLog.info("Getting SM Session: " + lSMSession); // // if (true) { // return; // } int lMaxTotalProcesses = 1; int lMaxUserRequests = 2; int lLoopDelay = 1; int lRequestDelay = 1; Map<String, Object> lJSON; for (int lCount = 0; lCount < lMaxTotalProcesses; lCount++) { mLog.info("================== " + (lCount + 1) + "/" + lMaxTotalProcesses + " =================="); String lSessionCookie = lOAuth.getSSOSession(lOAuthUsername, lOAuthPassword, 5000); mLog.info("Getting Session Cookie: " + (null == lSessionCookie ? "[null]" : lSessionCookie.replace("\r", "\\r").replace("\n", "\\n"))); try { lJSON = lOAuth.parseJSON(lSessionCookie); } catch (IOException ex) { mLog.error(ex.getMessage()); break; } String lAuthSession = lOAuth.authSession(lOAuth.getSessionId(), 5000); mLog.info("Authenticate Session: " + (null == lAuthSession ? "[null]" : lAuthSession.replace("\r", "\\r").replace("\n", "\\n"))); try { lJSON = lOAuth.parseJSON(lAuthSession); } catch (IOException ex) { mLog.error(ex.getMessage()); break; } // mLog.info("JSON Direct Authentication: " + lOAuth.authDirect(lOAuthUsername, lOAuthPassword)); String lAccessToken = lOAuth.getAccessToken(); mLog.info("JSON Obtaining Bearer Token: " + lAccessToken); for (int lGetUserIdx = 0; lGetUserIdx < lMaxUserRequests; lGetUserIdx++) { // intentionally cause a failure at last loop iteration if (lMaxUserRequests == lGetUserIdx + 1) { lAccessToken += "xx"; } try { String lUsername = lOAuth.getUser(lAccessToken); mLog.info((lGetUserIdx + 1) + " of " + lMaxUserRequests + ": JSON User from Access Token: " + (null == lUsername ? "[null]" : lUsername.replace("\r", "\\r").replace("\n", "\\n"))); try { lJSON = lOAuth.parseJSON(lUsername); } catch (IOException ex) { mLog.error("Parsing JSON: " + ex.getMessage()); break; } /* try { String lRes = lOAuth.refreshAccessToken(lOAuthTimeout); mLog.info("JSON Refresh Access Token: " + (null == lRes ? "[null]" : lRes.replace("\r", "\\r").replace("\n", "\\n"))); } catch (Exception ex) { mLog.error("Refreshing Access Token: " + ex.getMessage()); break; } */ try { Thread.currentThread().sleep(lRequestDelay); } catch (InterruptedException lEx) { } } catch (Exception ex) { mLog.error(ex.getMessage()); break; } } } }
From source file:org.restcomm.connect.http.filters.FileCacheServlet.java
/** * Process the actual request.// w ww. j a v a2 s .c o m * * @param request The request to be processed. * @param response The response to be created. * @param content Whether the request body should be written (GET) or not * (HEAD). * @throws IOException If something fails at I/O level. */ private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException { // Validate the requested file ------------------------------------------------------------ // Get requested file by path info. String requestedFile = request.getPathInfo(); if (logger.isDebugEnabled()) { logger.debug("Requested path:" + requestedFile); } // Check if file is actually supplied to the request URL. if (requestedFile == null) { logger.debug("No file requested, return 404."); // Do your thing if the file is not supplied to the request URL. // Throw an exception, or send 404, or show default/warning page, or just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } Configuration rootConfiguration = (Configuration) request.getServletContext() .getAttribute(Configuration.class.getName()); Configuration runtimeConfiguration = rootConfiguration.subset("runtime-settings"); String basePath = runtimeConfiguration.getString("cache-path"); int bufferSize = runtimeConfiguration.getInteger("cache-buffer-size", DEFAULT_BUFFER_SIZE); long expireTime = runtimeConfiguration.getLong("cache-expire-time", DEFAULT_EXPIRE_TIME); // URL-decode the file name (might contain spaces and on) and prepare file object. String fDecodedPath = URLDecoder.decode(requestedFile, "UTF-8"); File file = new File(basePath, fDecodedPath); // Check if file actually exists in filesystem. if (!file.exists()) { logger.debug("Requested file not found, return 404."); // Do your thing if the file appears to be non-existing. // Throw an exception, or send 404, or show default/warning page, or just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Prepare some variables. The ETag is an unique identifier of the file. String fileName = file.getName(); long length = file.length(); long lastModified = file.lastModified(); String eTag = fileName + "_" + length + "_" + lastModified; long expires = System.currentTimeMillis() + expireTime; // Validate request headers for caching --------------------------------------------------- // If-None-Match header should contain "*" or ETag. If so, then return 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) { logger.debug("IfNoneMatch/Etag not matching, return 304."); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // If-Modified-Since header should be greater than LastModified. If so, then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) { logger.debug("IfModifiedSince not matching, return 304."); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // Validate request headers for resume ---------------------------------------------------- // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, eTag)) { logger.debug("ifMatch not matching, return 412."); response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) { logger.debug("ifUnmodifiedSince not matching, return 412."); response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Prepare and initialize response -------------------------------------------------------- // Get content type by file name and content disposition. String contentType = getServletContext().getMimeType(fileName); String disposition = "inline"; // If content type is unknown, then set the default value. // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "application/octet-stream"; } // If content type is text, expand content type with the one and right character encoding. if (contentType.startsWith("text")) { contentType += ";charset=UTF-8"; } // Else, expect for images, determine content disposition. If content type is supported by // the browser, then set to inline, else attachment which will pop a 'save as' dialogue. else if (!contentType.startsWith("image")) { String accept = request.getHeader("Accept"); disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(bufferSize); response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", eTag); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", expires); // Send requested file (part(s)) to client ------------------------------------------------ // Prepare streams. FileInputStream input = null; OutputStream output = null; if (content) { logger.debug("Content requested,streaming."); // Open streams. input = new FileInputStream(file); output = response.getOutputStream(); long streamed = stream(input, output, bufferSize); if (logger.isDebugEnabled()) { logger.debug("Bytes streamed:" + streamed); } } }
From source file:org.seedstack.jcache.internal.CachePlugin.java
@Override @SuppressWarnings("unchecked") public InitState init(InitContext initContext) { Configuration cachesConf = initContext.dependency(ConfigurationProvider.class).getConfiguration() .subset(CachePlugin.CACHE_PLUGIN_CONFIGURATION_PREFIX); String defaultProvider = cachesConf.getString("default-provider"); String[] cacheNames = cachesConf.getStringArray("caches"); if (defaultProvider != null) { LOGGER.info("Caching default provider is configured to {}", defaultProvider); } else {/*from ww w. j av a 2 s. co m*/ LOGGER.info("Caching default provider is not specified and will be autodetected from classpath"); } if (cacheNames != null) { for (String cacheName : cacheNames) { Configuration cacheConf = cachesConf.subset("cache." + cacheName); MutableConfiguration cacheConfiguration = new MutableConfiguration(); // Expiry policy String expiryPolicyFactory = cacheConf.getString("expiry-policy-factory"); String expiryPolicy = cacheConf.getString("expiry-policy"); Long expiryDuration = cacheConf.getLong("expiry-duration", 900); if (expiryPolicyFactory != null) { try { cacheConfiguration .setExpiryPolicyFactory((Factory) Class.forName(expiryPolicyFactory).newInstance()); } catch (Exception e) { throw new PluginException( "Unable to instantiate custom expiry policy factory " + expiryPolicyFactory, e); } } else if (expiryPolicy != null && !expiryPolicy.isEmpty()) { try { cacheConfiguration .setExpiryPolicyFactory(BuiltinExpiryPolicy.valueOf(expiryPolicy.toUpperCase()) .getFactory(new Duration(TimeUnit.SECONDS, expiryDuration))); } catch (Exception e) { throw new PluginException("Unable to instantiate built-in expiry policy " + expiryPolicy, e); } } String providerClassname = cacheConf.getString("provider", defaultProvider); if (providerClassname == null) { LOGGER.info("Configuring jcache {} with autodetected provider", cacheName); caches.put(cacheName, Caching.getCachingProvider().getCacheManager().createCache(cacheName, cacheConfiguration)); } else { LOGGER.info("Configuring jcache {} with provider {}", cacheName, providerClassname); caches.put(cacheName, Caching.getCachingProvider(providerClassname).getCacheManager() .createCache(cacheName, cacheConfiguration)); } } } return InitState.INITIALIZED; }
From source file:org.seedstack.seed.cache.internal.CachePlugin.java
@Override @SuppressWarnings("unchecked") public InitState init(InitContext initContext) { ApplicationPlugin confPlugin = (ApplicationPlugin) initContext.pluginsRequired().iterator().next(); Configuration cachesConf = confPlugin.getApplication().getConfiguration() .subset(CachePlugin.CACHE_PLUGIN_CONFIGURATION_PREFIX); String defaultProvider = cachesConf.getString("default-provider"); String[] cacheNames = cachesConf.getStringArray("caches"); if (defaultProvider != null) { LOGGER.info("Caching default provider is configured to {}", defaultProvider); } else {/* www . ja v a2 s.com*/ LOGGER.info("Caching default provider is not specified and will be autodetected from classpath"); } if (cacheNames != null) { for (String cacheName : cacheNames) { Configuration cacheConf = cachesConf.subset("cache." + cacheName); MutableConfiguration cacheConfiguration = new MutableConfiguration(); // Expiry policy String expiryPolicyFactory = cacheConf.getString("expiry-policy-factory"); String expiryPolicy = cacheConf.getString("expiry-policy"); Long expiryDuration = cacheConf.getLong("expiry-duration", 900); if (expiryPolicyFactory != null) { try { cacheConfiguration .setExpiryPolicyFactory((Factory) Class.forName(expiryPolicyFactory).newInstance()); } catch (Exception e) { throw new PluginException( "Unable to instantiate custom expiry policy factory " + expiryPolicyFactory, e); } } else if (expiryPolicy != null && !expiryPolicy.isEmpty()) { try { cacheConfiguration .setExpiryPolicyFactory(BuiltinExpiryPolicy.valueOf(expiryPolicy.toUpperCase()) .getFactory(new Duration(TimeUnit.SECONDS, expiryDuration))); } catch (Exception e) { throw new PluginException("Unable to instantiate built-in expiry policy " + expiryPolicy, e); } } String providerClassname = cacheConf.getString("provider", defaultProvider); if (providerClassname == null) { LOGGER.info("Configuring cache {} with autodetected provider", cacheName); caches.put(cacheName, Caching.getCachingProvider().getCacheManager().createCache(cacheName, cacheConfiguration)); } else { LOGGER.info("Configuring cache {} with provider {}", cacheName, providerClassname); caches.put(cacheName, Caching.getCachingProvider(providerClassname).getCacheManager() .createCache(cacheName, cacheConfiguration)); } } } return InitState.INITIALIZED; }
From source file:org.sonar.plugins.web.markup.validation.RemoteValidationService.java
public RemoteValidationService(Configuration configuration) { this.configuration = configuration; waitBetweenRequests = configuration.getLong(MarkupValidatorConstants.PAUSE_BETWEEN_VALIDATIONS, DEFAULT_PAUSE_BETWEEN_VALIDATIONS); }
From source file:org.topazproject.mulgara.resolver.CacheInvalidator.java
private static final long getInvIval(Configuration config) { return config.getLong("cacheInvalidator.invalidationInterval", 5000L); }
From source file:org.topazproject.mulgara.resolver.TransactionLogger.java
/** * Create a new logger instance. //from www .j a v a 2 s.c o m * * @param config the configuration to use * @param base the prefix under which the current <var>config</var> was retrieved * @param sf ignored * @param dbURI ignored * @throws IOException */ public TransactionLogger(Configuration config, String base, SessionFactory sf, URI dbURI) throws IOException { super(getFlushIval(config), 0, "TransactionLogger-Worker", true, logger); config = config.subset("transactionLogger"); base += ".transactionLogger"; String fileName = config.getString("log.fileName", null); long maxSize = config.getLong("log.maxSize", -1L); long maxAge = config.getLong("log.maxAge", -1L); int bufSize = config.getInt("writeBufferSize", -1); if (fileName == null) throw new IllegalArgumentException("Missing configuration entry '" + base + ".log.fileName'"); txLog = new TxLog(fileName, maxSize, maxAge, bufSize); worker.start(); }
From source file:org.topazproject.mulgara.resolver.TransactionLogger.java
private static final long getFlushIval(Configuration config) { return config.getLong("transactionLogger.flushInterval", 30000L); }
From source file:tld.yourname.jms.client.JMSClient.java
/** * * @param aArgs//from w ww . j a va 2 s . c om */ @SuppressWarnings("SleepWhileInLoop") public static void main(String[] aArgs) { // set up log4j logging // later this should be read from a shared log4j properties or xml file! Properties lProps = new Properties(); lProps.setProperty("log4j.rootLogger", "INFO, console"); lProps.setProperty("log4j.logger.org.apache.activemq.spring", "WARN"); lProps.setProperty("log4j.logger.org.apache.activemq.web.handler", "WARN"); lProps.setProperty("log4j.logger.org.springframework", "WARN"); lProps.setProperty("log4j.logger.org.apache.xbean", "WARN"); lProps.setProperty("log4j.logger.org.apache.camel", "INFO"); lProps.setProperty("log4j.logger.org.eclipse.jetty", "WARN"); lProps.setProperty("log4j.appender.console", "org.apache.log4j.ConsoleAppender"); lProps.setProperty("log4j.appender.console.layout", "org.apache.log4j.PatternLayout"); lProps.setProperty("log4j.appender.console.layout.ConversionPattern", // "%p: %m%n" "%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p - %C{1}: %m%n"); // set here the jWebSocket log level: lProps.setProperty("log4j.logger.org.jwebsocket", "DEBUG"); lProps.setProperty("log4j.appender.console.threshold", "DEBUG"); PropertyConfigurator.configure(lProps); // only for debug purposes // JMSLogging.setFullTextLogging(true); mLog.info("jWebSocket JMS Gateway Demo Client"); Configuration lConfig = null; boolean lConfigLoaded; try { // try to load properties files from local folder or jar String lPath = "JMSClient.properties"; mLog.debug("Tring to read properties from: " + lPath); lConfig = new PropertiesConfiguration(lPath); } catch (ConfigurationException ex) { } if (null == lConfig) { try { // try to load properties files from JWEBSOCKET_HOME/conf/JMSPlugIn String lPath = Tools.expandEnvVarsAndProps("${JWEBSOCKET_HOME}conf/JMSPlugIn/JMSClient.properties"); // String lPath = Tools.expandEnvVarsAndProps("${JWEBSOCKET_HOME}conf/JMSPlugIn/JMSClient.properties"); mLog.debug("Tring to read properties from: " + lPath); lConfig = new PropertiesConfiguration(lPath); } catch (ConfigurationException ex) { } } if (null == lConfig) { mLog.error("Configuration file could not be opened."); return; } // the URL of the message broker String lBrokerURL = lConfig.getString("BrokerURL", "tcp://127.0.0.1:61616"); // "failover:(tcp://0.0.0.0:61616,tcp://127.0.0.1:61616)?initialReconnectDelay=100&randomize=false"; // the name of the JMS Gateway topic String lGatewayTopic = lConfig.getString("GatewayTopic", "org.jwebsocket.jms.gateway"); // endpoint id of JMS Gateway String lGatewayId = lConfig.getString("GatewayId", "org.jwebsocket.jms.gateway"); String lEndPointId = lConfig.getString("EndPointId", UUID.randomUUID().toString()); lTargetEndPointId = lConfig.getString("TargetEndPointId", lGatewayId); // get authentication information against jWebSocket final String lJWSUsername = lConfig.getString("JWSUsername"); final String lJWSPassword = lConfig.getString("JWSPassword"); final boolean lFullTextLogging = lConfig.getBoolean("FullTextLogging", false); // set up OAuth Authenticator boolean lUseOAuth = lConfig.getBoolean("UseOAuth", false); if (lUseOAuth) { String lOAuthHost = lConfig.getString("OAuthHost"); String lOAuthAppId = lConfig.getString("OAuthAppId"); String lOAuthAppSecret = lConfig.getString("OAuthAppSecret"); String lOAuthUsername = lConfig.getString("OAuthUsername"); String lOAuthPassword = lConfig.getString("OAuthPassword"); long lOAuthTimeout = lConfig.getLong("OAuthTimeout", 5000); lUseOAuth = lUseOAuth && null != lOAuthHost && null != lOAuthAppId && null != lOAuthAppSecret && null != lOAuthUsername && null != lOAuthPassword; if (lUseOAuth) { lOAuthAuthenticator.init(lOAuthHost, lOAuthAppId, lOAuthAppSecret, lOAuthUsername, lOAuthPassword, lOAuthTimeout); try { lOAuthAuthenticator.authDirect(lOAuthUsername, lOAuthPassword); } catch (JMSEndpointException lEx) { mLog.error("User '" + lOAuthUsername + "' could not be authenticated at client: " + lEx.getClass().getSimpleName() + ": " + lEx.getMessage()); } lAuthenticatorManager.addAuthenticator(lAuthenticatorManager); } else { mLog.error("Missing OAuth required configuration parameters!"); } } // set up LDAP Authenticator boolean lUseLDAP = lConfig.getBoolean("UseLDAP", false); if (lUseLDAP) { String lLDAPURL = lConfig.getString("LDAPURL"); String lBaseDNGroups = lConfig.getString("BaseDNGroups"); String lBaseDNUsers = lConfig.getString("BaseDNUsers"); String lBindUsername = lConfig.getString("BindUsername"); String lBindPassword = lConfig.getString("BindPassword"); if (lUseLDAP) { lLDAPAuthenticator.init(lLDAPURL, lBaseDNGroups, lBaseDNUsers); // to authenticatie the client, if required try { lLDAPAuthenticator.bind(lBindUsername, lBindPassword); } catch (JMSEndpointException lEx) { mLog.error("User '" + lBindUsername + "' could not be authenticated at client: " + lEx.getClass().getSimpleName() + ": " + lEx.getMessage()); } lAuthenticatorManager.addAuthenticator(lLDAPAuthenticator); } else { mLog.error("Missing LDAP required configuration parameters!"); } } // setup memory authenticator boolean lUseMemory = true; if (lUseMemory) { // statically adding user credentials (password require to be MD5 value) lMemoryAuthenticator.addCredentials("root", "63a9f0ea7bb98050796b649e85481845"); //root:root // registering the authenticator lAuthenticatorManager.addAuthenticator(lMemoryAuthenticator); } // TODO: Validate config data here! lConfigLoaded = true; if (!lConfigLoaded) { mLog.error("Config not loaded."); System.exit(1); } mLog.info("Using: " + lBrokerURL + ", " + "topic: " + lGatewayTopic + ", " + "gateway-id: " + lGatewayId + ", " + "endpoint-id: " + lEndPointId); // todo: Comment that for production purposes JMSLogging.setFullTextLogging(lFullTextLogging); try { lJWSEndPoint = JWSEndPoint.getInstance(lBrokerURL, lGatewayTopic, // gateway topic lGatewayId, // gateway endpoint id lEndPointId, // unique node id 5, // thread pool size, messages being processed concurrently JMSEndPoint.TEMPORARY // durable (for servers) or temporary (for clients) ); // in case you will require the server LoadBalancer features // set the CPU updater for the instance // lCpuUpdater = new JWSLoadBalancerCpuUpdater(lJWSEndPoint, lTargetEndPointId); // lCpuUpdater.autoStart(); } catch (JMSException lEx) { mLog.fatal("JMSEndpoint could not be instantiated: " + lEx.getMessage()); System.exit(0); } // on welcome message from jWebSocket, authenticate against jWebSocket lJWSEndPoint.addRequestListener("org.jwebsocket.jms.gateway", "welcome", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { mLog.info("Received 'welcome' from '" + aSourceId + "."); if ("org.jwebsocket.jms.gateway".equals(aSourceId)) { // create a login token... mLog.info("Authenticating against jWebSocket..."); Token lToken = TokenFactory.createToken("org.jwebsocket.plugins.system", "login"); if (null != lJWSUsername && null != lJWSPassword) { lToken.setString("username", lJWSUsername); lToken.setString("password", lJWSPassword); } // and send it to the gateway (which is was the source of the message) sendToken(aSourceId, lToken, new JWSResponseTokenListener(JWSResponseTokenListener.RESP_TIME_FIELD) { @Override public void onTimeout() { mLog.info("Login timed out!"); } @Override public void onFailure(Token aReponse) { mLog.error("Login failure!"); } @Override public void onSuccess(Token aReponse) { if (mLog.isInfoEnabled()) { mLog.info("Login success (response received in " + aReponse.getLong(JWSResponseTokenListener.RESP_TIME_FIELD) + "ms)."); } } }, 1000); } } }); // process response of the JMS Gateway login... lJWSEndPoint.addResponseListener("org.jwebsocket.plugins.system", "login", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { mLog.info("Login successful, initiating client communication process..."); // runProgressTest(); // runOAuthTest(); Map<String, Object> lArgs = new FastMap<String, Object>(); // echo on login int lCode = aToken.getInteger("code", -1); if (0 == lCode) { if (mLog.isInfoEnabled()) { mLog.info("Authentication against jWebSocket JMS Gateway successful."); } } else { mLog.error("Authentication against jWebSocket JMS Gateway failed!"); } lArgs.put("echo", "This is the echo message"); lArgs.put("targetId", lTargetEndPointId); lJWSEndPoint.sendPayload( // lTargetEndPointId, "org.jwebsocket.jms.gateway", // target id "org.jwebsocket.jms.demo", // ns "echo", // type lArgs, "any additional payload if required", new JWSResponseTokenListener(JWSResponseTokenListener.RESP_TIME_FIELD) { @Override public void onTimeout() { mLog.info("Echo timed out!"); } @Override public void onFailure(Token aReponse) { mLog.error("Echo failure!"); } @Override public void onSuccess(Token aReponse) { if (mLog.isInfoEnabled()) { mLog.info("Echo success (response received in " + aReponse.getLong(JWSResponseTokenListener.RESP_TIME_FIELD) + "ms)."); } } }, 10000); } }); // process response echo request to the JMS demo plug-in... lJWSEndPoint.addResponseListener("org.jwebsocket.plugins.jmsdemo", "echo", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { mLog.info("Response from '" + aSourceId + "' to 'echo' received: " + (JMSLogging.isFullTextLogging() ? aToken.toString() : aToken.getLogString())); } }); // process response of the JMS Gateway login... lJWSEndPoint.addResponseListener("org.jwebsocket.svcep.demo", "sso1", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { int lCode = aToken.getInteger("code", -1); if (0 == lCode) { if (mLog.isInfoEnabled()) { mLog.info("Username was detected by server: '" + aToken.getString("username") + "'"); } } } }); // process response of the get data response... lJWSEndPoint.addResponseListener("tld.yourname.jms", "getData", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { int lCode = aToken.getInteger("code", -1); if (0 == lCode) { if (mLog.isInfoEnabled()) { mLog.info("Data transfer successful."); } } else { mLog.error("Data transfer failed!"); } // reading a file using Apache Commons IO into a byte array File lFile = new File("Apache License 2.0.txt"); byte[] lBA = null; try { lBA = FileUtils.readFileToByteArray(lFile); } catch (IOException lEx) { mLog.error("Demo file " + lFile.getAbsolutePath() + " could not be loaded!"); } // if the file could properly being read... if (null != lBA) { // base64 encode it w/o any compression String lBase64Encoded = Tools.base64Encode(lBA); // or compress it as an zip archive String lBase64Zipped = null; try { lBase64Zipped = Tools.base64Encode(Tools.zip(lBA, false)); } catch (Exception lEx) { mLog.error("File could not be compressed: " + lEx.getMessage()); } Token lToken = TokenFactory.createToken(); // put base64 encoded only version into message lToken.setString("fileAsBase64", lBase64Encoded); // and the zipped version as well (for demo purposes) lToken.setString("fileAsZip", lBase64Zipped); // generate the payload as JSON String lPayload = JSONProcessor.tokenToPacket(lToken).getUTF8(); // add some optional arguments to be passed to the target Map<String, Object> lArgs = new FastMap<String, Object>(); lArgs.put("arg1", "value1"); lArgs.put("arg2", "value2"); // send the payload to the target (here the JMS demo service) lJWSEndPoint.sendPayload("JMSServer", "tld.yourname.jms", "transferFile", lArgs, lPayload); } // and shut down the client mLog.info("Gracefully shutting down..."); lJWSEndPoint.shutdown(); } }); // start the endpoint all all listener have been assigned lJWSEndPoint.start(); // add a listener to listen in coming messages // lJMSClient.addListener(new JMSClientMessageListener(lJMSClient)); // this is a console app demo // so wait in a thread loop until the client get shut down try { while (lJWSEndPoint.isOpen()) { Thread.sleep(1000); } } catch (InterruptedException lEx) { // ignore a potential exception here } // check if JMS client has already been shutdown by logic if (!lJWSEndPoint.isShutdown()) { // if not yet done... mLog.info("Shutting down JMS Client Endpoint..."); // shut the client properly down lJWSEndPoint.shutdown(); } // and show final status message in the console mLog.info("JMS Client Endpoint properly shutdown."); }