List of usage examples for org.apache.commons.configuration Configuration getBoolean
Boolean getBoolean(String key, Boolean defaultValue);
From source file:org.zaproxy.zap.extension.pscan.PluginPassiveScanner.java
public void loadFrom(Configuration conf) { this.setEnabled(conf.getBoolean("pscans." + getClass().getCanonicalName() + ".enabled", true)); this.setLevel(AlertThreshold.valueOf(conf.getString("pscans." + getClass().getCanonicalName() + ".level", AlertThreshold.DEFAULT.name()))); }
From source file:science.atlarge.graphalytics.graphmat.GraphmatPlatform.java
public GraphmatPlatform() { LOG.info("Parsing GraphMat configuration file."); Configuration granulaConfig; try {/*from w ww.java 2s . com*/ benchmarkConfig = ConfigurationUtil.loadConfiguration(BENCHMARK_PROPERTIES_FILE); granulaConfig = ConfigurationUtil.loadConfiguration(GRANULA_PROPERTIES_FILE); } catch (InvalidConfigurationException e) { LOG.warn("Could not find or load \"{}\"", BENCHMARK_PROPERTIES_FILE); LOG.warn("Could not find or load \"{}\"", GRANULA_PROPERTIES_FILE); benchmarkConfig = new PropertiesConfiguration(); granulaConfig = new PropertiesConfiguration(); } boolean granulaEnabled = granulaConfig.getBoolean(GRANULA_ENABLE_KEY, false); BINARY_DIRECTORY = granulaEnabled ? "./bin/granula" : BINARY_DIRECTORY; }
From source file:science.atlarge.graphalytics.powergraph.PowergraphPlatform.java
public PowergraphPlatform() { Configuration granulaConfig; try {// w w w . jav a 2 s .c o m benchmarkConfig = ConfigurationUtil.loadConfiguration(BENCHMARK_PROPERTIES_FILE); granulaConfig = ConfigurationUtil.loadConfiguration(GRANULA_PROPERTIES_FILE); } catch (InvalidConfigurationException e) { LOG.warn("failed to load " + BENCHMARK_PROPERTIES_FILE, e); LOG.warn("Could not find or load \"{}\"", GRANULA_PROPERTIES_FILE); benchmarkConfig = new PropertiesConfiguration(); granulaConfig = new PropertiesConfiguration(); } boolean granulaEnabled = granulaConfig.getBoolean(GRANULA_ENABLE_KEY, false); POWERGRAPH_BINARY_NAME = granulaEnabled ? "./bin/granula/main" : POWERGRAPH_BINARY_NAME; }
From source file:tld.yourname.jms.client.ClockServiceStressTest.java
/** * * @param aArgs//from w w w . jav a2 s.c o m */ @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", "ERROR, 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", "ERROR"); lProps.setProperty("log4j.appender.console.threshold", "ERROR"); 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()); // get authentication information against jWebSocket final String lJWSUsername = lConfig.getString("JWSUsername"); final String lJWSPassword = lConfig.getString("JWSPassword"); final boolean lFullTextLogging = lConfig.getBoolean("FullTextLogging", false); 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 4, // 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) { 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 stress test..."); startStressTest(); } }); // 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."); }
From source file:tld.yourname.jms.client.JMSClient.java
/** * * @param aArgs/*from w ww . j av a 2 s .com*/ */ @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."); }
From source file:tld.yourname.jms.client.OntologyPlugInUsage.java
/** * * @param aArgs/*from w w w . j a va 2 s . c o m*/ */ 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", "ERROR, 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; 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()); // get authentication information against jWebSocket final String lJWSUsername = lConfig.getString("JWSUsername"); final String lJWSPassword = lConfig.getString("JWSPassword"); final boolean lFullTextLogging = lConfig.getBoolean("FullTextLogging", false); 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 4, // 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) { 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 stress test..."); getActionPlugInAPI(); } }); // 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."); }
From source file:tld.yourname.jms.server.DemoService1.java
/** * * @param aArgs/* ww w . j a v a 2 s.co m*/ * @return */ public JWSEndPoint start(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", "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); // setting the endpoint service authenticator, clients commonly require // to authenticate againts endpoint services final JWSAutoSelectAuthenticator lAuthenticator = new JWSAutoSelectAuthenticator(); final JWSOAuthAuthenticator lOAuthAuthenticator = new JWSOAuthAuthenticator(); final JWSLDAPAuthenticator lLDAPAuthenticator = new JWSLDAPAuthenticator(); // hardcoding memory authenticator for example JWSMemoryAuthenticator lMemoryAuth = new JWSMemoryAuthenticator(); lMemoryAuth.addCredentials("admin", "21232f297a57a5a743894a0e4a801fc3"); //admin:admin lAuthenticator.addAuthenticator(lMemoryAuth); mLog.info("jWebSocket JMS Gateway Server Endpoint"); Configuration lConfig = null; boolean lConfigLoaded; try { // try to load properties files from local folder or jar String lPath = "JMSServer.properties"; mLog.debug("Trying 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/DemoService1.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 null; } // 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()); // 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; lOAuthAuthenticator.init(lOAuthHost, lOAuthAppId, lOAuthAppSecret, lOAuthTimeout); lAuthenticator.addAuthenticator(lOAuthAuthenticator); } // 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"); lLDAPAuthenticator.init(lLDAPURL, lBaseDNGroups, lBaseDNUsers); lAuthenticator.addAuthenticator(lLDAPAuthenticator); } // 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); // instantiate a new jWebSocket JMS Gateway Client 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) ); } catch (JMSException lEx) { mLog.fatal("JMSEndpoint could not be instantiated: " + lEx.getMessage()); System.exit(0); } lJWSEndPoint.addRequestListener("org.jwebsocket.jms.gateway", "welcome", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { mLog.info("Received 'welcome', authenticating against jWebSocket..."); Token lToken = TokenFactory.createToken("org.jwebsocket.plugins.system", "login"); lToken.setString("username", lJWSUsername); lToken.setString("password", lJWSPassword); sendToken(aSourceId, lToken); } }); // on response of the login... lJWSEndPoint.addResponseListener("org.jwebsocket.plugins.system", "login", 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("Authentication against jWebSocket successful."); } } else { mLog.error("Authentication against jWebSocket failed!"); } } }); // adding service 'getTime' command implementation ... lJWSEndPoint.addRequestListener("somecompany.service.clock", "getTime", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { try { String lUser = lAuthenticator.authenticate(aToken); if (null == lUser) { lJWSEndPoint.respondPayload(aToken, -1, // return code "access denied", // return message null, null); } else { if (mLog.isInfoEnabled()) { mLog.info("Processing 'getTime' request from '" + lUser + "' user..."); } lJWSEndPoint.respondPayload(aToken, 0, // return code "OK", // return message new MapAppender().append("time", System.currentTimeMillis()).getMap(), null); } } catch (JMSEndpointException lEx) { mLog.error("Unexpected error during service request processing", lEx); } } }); // on response of the login... lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "echo", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { String lPayload = aToken.getString("payload"); if (mLog.isInfoEnabled()) { mLog.info("Processing 'demo1 with Payload '" + lPayload + "'"); } Map<String, Object> lAdditionalResults = new FastMap<String, Object>(); lAdditionalResults.putAll(aToken.getMap()); // lAdditionalResults.remove("sourceId"); lAdditionalResults.remove("payload"); lJWSEndPoint.respondPayload(aToken, 0, // return code "Ok", // return message lAdditionalResults, aToken.getString("payload")); } }); // on response of the login... lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "testProgress", new JWSMessageListener(lJWSEndPoint) { @Override @SuppressWarnings("SleepWhileInLoop") public void processToken(String aSourceId, Token aToken) { int lMax = 10; for (int lIdx = 0; lIdx < lMax; lIdx++) { mLog.debug("Progress iteration " + lIdx + "..."); try { Thread.sleep(333); } catch (InterruptedException lEx) { } lJWSEndPoint.sendProgress(aToken, ((lIdx + 1.0) / lMax) * 100, 0, "Iteration #" + lIdx, null); } lJWSEndPoint.respondPayload(aToken, 0, // return code "Ok", // return message null, aToken.getString("payload")); } }); // start the endpoint all all listener have been assigned lJWSEndPoint.start(); return lJWSEndPoint; }
From source file:tld.yourname.jms.server.DemoService2.java
/** * * @param aArgs//from ww w . j av a 2 s . c o m * @return */ public JWSEndPoint start(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", "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); // setting the endpoint service authenticator, clients commonly require // to authenticate againts endpoint services final JWSAutoSelectAuthenticator lAuthenticator = new JWSAutoSelectAuthenticator(); final JWSOAuthAuthenticator lOAuthAuthenticator = new JWSOAuthAuthenticator(); final JWSLDAPAuthenticator lLDAPAuthenticator = new JWSLDAPAuthenticator(); // hardcoding memory authenticator for example JWSMemoryAuthenticator lMemoryAuth = new JWSMemoryAuthenticator(); lMemoryAuth.addCredentials("admin", "21232f297a57a5a743894a0e4a801fc3"); //admin:admin lAuthenticator.addAuthenticator(lMemoryAuth); mLog.info("jWebSocket JMS Gateway Server Endpoint"); Configuration lConfig = null; boolean lConfigLoaded; try { // try to load properties files from local folder or jar String lPath = "JMSServer.properties"; mLog.debug("Trying 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/DemoService2.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 null; } // 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()); // 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; lOAuthAuthenticator.init(lOAuthHost, lOAuthAppId, lOAuthAppSecret, lOAuthTimeout); lAuthenticator.addAuthenticator(lOAuthAuthenticator); } // 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"); lLDAPAuthenticator.init(lLDAPURL, lBaseDNGroups, lBaseDNUsers); lAuthenticator.addAuthenticator(lLDAPAuthenticator); } // 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); // instantiate a new jWebSocket JMS Gateway Client 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) ); } catch (JMSException lEx) { mLog.fatal("JMSEndpoint could not be instantiated: " + lEx.getMessage()); System.exit(0); } lJWSEndPoint.addRequestListener("org.jwebsocket.jms.gateway", "welcome", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { mLog.info("Received 'welcome', authenticating against jWebSocket..."); Token lToken = TokenFactory.createToken("org.jwebsocket.plugins.system", "login"); lToken.setString("username", lJWSUsername); lToken.setString("password", lJWSPassword); sendToken(aSourceId, lToken); } }); // on response of the login... lJWSEndPoint.addResponseListener("org.jwebsocket.plugins.system", "login", 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("Authentication against jWebSocket successful."); } } else { mLog.error("Authentication against jWebSocket failed!"); } } }); // adding service 'getTime' command implementation ... lJWSEndPoint.addRequestListener("somecompany.service.clock", "getTime", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { try { String lUser = lAuthenticator.authenticate(aToken); if (null == lUser) { lJWSEndPoint.respondPayload(aToken, -1, // return code "access denied", // return message null, null); } else { if (mLog.isInfoEnabled()) { mLog.info("Processing 'getTime' request from '" + lUser + "' user..."); } lJWSEndPoint.respondPayload(aToken, 0, // return code "OK", // return message new MapAppender().append("time", System.currentTimeMillis()).getMap(), null); } } catch (JMSEndpointException lEx) { mLog.error("Unexpected error during service request processing", lEx); } } }); // on response of the login... lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "echo", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { String lPayload = aToken.getString("payload"); if (mLog.isInfoEnabled()) { mLog.info("Processing 'demo1 with Payload '" + lPayload + "'"); } Map<String, Object> lAdditionalResults = new FastMap<String, Object>(); lAdditionalResults.putAll(aToken.getMap()); // lAdditionalResults.remove("sourceId"); lAdditionalResults.remove("payload"); lJWSEndPoint.respondPayload(aToken, 0, // return code "Ok", // return message lAdditionalResults, aToken.getString("payload")); } }); // on response of the login... lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "testProgress", new JWSMessageListener(lJWSEndPoint) { @Override @SuppressWarnings("SleepWhileInLoop") public void processToken(String aSourceId, Token aToken) { int lMax = 10; for (int lIdx = 0; lIdx < lMax; lIdx++) { mLog.debug("Progress iteration " + lIdx + "..."); try { Thread.sleep(333); } catch (InterruptedException lEx) { } lJWSEndPoint.sendProgress(aToken, ((lIdx + 1.0) / lMax) * 100, 0, "Iteration #" + lIdx, null); } lJWSEndPoint.respondPayload(aToken, 0, // return code "Ok", // return message null, aToken.getString("payload")); } }); // start the endpoint all all listener have been assigned lJWSEndPoint.start(); return lJWSEndPoint; }
From source file:tld.yourname.jms.server.DemoService3.java
/** * * @param aArgs/* ww w .j a v a 2s . c o m*/ * @return */ public JWSEndPoint start(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", "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); // setting the endpoint service authenticator, clients commonly require // to authenticate againts endpoint services final JWSAutoSelectAuthenticator lAuthenticator = new JWSAutoSelectAuthenticator(); final JWSOAuthAuthenticator lOAuthAuthenticator = new JWSOAuthAuthenticator(); final JWSLDAPAuthenticator lLDAPAuthenticator = new JWSLDAPAuthenticator(); // hardcoding memory authenticator for example JWSMemoryAuthenticator lMemoryAuth = new JWSMemoryAuthenticator(); lMemoryAuth.addCredentials("admin", "21232f297a57a5a743894a0e4a801fc3"); //admin:admin lAuthenticator.addAuthenticator(lMemoryAuth); mLog.info("jWebSocket JMS Gateway Server Endpoint"); Configuration lConfig = null; boolean lConfigLoaded; try { // try to load properties files from local folder or jar String lPath = "JMSServer.properties"; mLog.debug("Trying 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/DemoService3.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 null; } // 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()); // 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; lOAuthAuthenticator.init(lOAuthHost, lOAuthAppId, lOAuthAppSecret, lOAuthTimeout); lAuthenticator.addAuthenticator(lOAuthAuthenticator); } // 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"); lLDAPAuthenticator.init(lLDAPURL, lBaseDNGroups, lBaseDNUsers); lAuthenticator.addAuthenticator(lLDAPAuthenticator); } // 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); // instantiate a new jWebSocket JMS Gateway Client 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) ); } catch (JMSException lEx) { mLog.fatal("JMSEndpoint could not be instantiated: " + lEx.getMessage()); System.exit(0); } lJWSEndPoint.addRequestListener("org.jwebsocket.jms.gateway", "welcome", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { mLog.info("Received 'welcome', authenticating against jWebSocket..."); Token lToken = TokenFactory.createToken("org.jwebsocket.plugins.system", "login"); lToken.setString("username", lJWSUsername); lToken.setString("password", lJWSPassword); sendToken(aSourceId, lToken); } }); // on response of the login... lJWSEndPoint.addResponseListener("org.jwebsocket.plugins.system", "login", 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("Authentication against jWebSocket successful."); } } else { mLog.error("Authentication against jWebSocket failed!"); } } }); // adding service 'getTime' command implementation ... lJWSEndPoint.addRequestListener("somecompany.service.clock", "getTime", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { try { String lUser = lAuthenticator.authenticate(aToken); if (null == lUser) { lJWSEndPoint.respondPayload(aToken, -1, // return code "access denied", // return message null, null); } else { if (mLog.isInfoEnabled()) { mLog.info("Processing 'getTime' request from '" + lUser + "' user..."); } lJWSEndPoint.respondPayload(aToken, 0, // return code "OK", // return message new MapAppender().append("time", System.currentTimeMillis()).getMap(), null); } } catch (JMSEndpointException lEx) { mLog.error("Unexpected error during service request processing", lEx); } } }); // on response of the login... lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "echo", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { String lPayload = aToken.getString("payload"); if (mLog.isInfoEnabled()) { mLog.info("Processing 'demo1 with Payload '" + lPayload + "'"); } Map<String, Object> lAdditionalResults = new FastMap<String, Object>(); lAdditionalResults.putAll(aToken.getMap()); // lAdditionalResults.remove("sourceId"); lAdditionalResults.remove("payload"); lJWSEndPoint.respondPayload(aToken, 0, // return code "Ok", // return message lAdditionalResults, aToken.getString("payload")); } }); // on response of the login... lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "testProgress", new JWSMessageListener(lJWSEndPoint) { @Override @SuppressWarnings("SleepWhileInLoop") public void processToken(String aSourceId, Token aToken) { int lMax = 10; for (int lIdx = 0; lIdx < lMax; lIdx++) { mLog.debug("Progress iteration " + lIdx + "..."); try { Thread.sleep(333); } catch (InterruptedException lEx) { } lJWSEndPoint.sendProgress(aToken, ((lIdx + 1.0) / lMax) * 100, 0, "Iteration #" + lIdx, null); } lJWSEndPoint.respondPayload(aToken, 0, // return code "Ok", // return message null, aToken.getString("payload")); } }); // start the endpoint all all listener have been assigned lJWSEndPoint.start(); return lJWSEndPoint; }
From source file:tld.yourname.jms.server.JMSServer.java
/** * * @param aArgs//from w w w . j av a 2s . c o m * @return */ public JWSEndPoint start(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", "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); final JWSAutoSelectAuthenticator lAuthenticator = new JWSAutoSelectAuthenticator(); final JWSOAuthAuthenticator lOAuthAuthenticator = new JWSOAuthAuthenticator(); final JWSLDAPAuthenticator lLDAPAuthenticator = new JWSLDAPAuthenticator(); mLog.info("jWebSocket JMS Gateway Server Endpoint"); Configuration lConfig = null; boolean lConfigLoaded; try { // try to load properties files from local folder or jar String lPath = "JMSServer.properties"; mLog.debug("Trying 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("/private/JMSServer.properties"); // String lPath = Tools.expandEnvVarsAndProps("${JWEBSOCKET_HOME}conf/JMSPlugIn/JMSServer.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 null; } // 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()); // 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); 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, lOAuthTimeout); lAuthenticator.addAuthenticator(lOAuthAuthenticator); } // set up LDAP Authenticator boolean lUseLDAP = lConfig.getBoolean("UseLDAP", false); String lLDAPURL = lConfig.getString("LDAPURL"); String lBaseDNGroups = lConfig.getString("BaseDNGroups"); String lBaseDNUsers = lConfig.getString("BaseDNUsers"); if (lUseLDAP) { lLDAPAuthenticator.init(lLDAPURL, lBaseDNGroups, lBaseDNUsers); lAuthenticator.addAuthenticator(lLDAPAuthenticator); } // 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); // instantiate a new jWebSocket JMS Gateway Client 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) ); } catch (JMSException lEx) { mLog.fatal("JMSEndpoint could not be instantiated: " + lEx.getMessage()); System.exit(0); } lJWSEndPoint.addRequestListener("org.jwebsocket.jms.gateway", "welcome", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { mLog.info("Received 'welcome', authenticating against jWebSocket..."); Token lToken = TokenFactory.createToken("org.jwebsocket.plugins.system", "login"); lToken.setString("username", lJWSUsername); lToken.setString("password", lJWSPassword); sendToken(aSourceId, lToken); } }); // on response of the login... lJWSEndPoint.addResponseListener("org.jwebsocket.plugins.system", "login", 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("Authentication against jWebSocket successful."); } } else { mLog.error("Authentication against jWebSocket failed!"); } } }); // on response of the login... lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "getUser", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { String lPayload = aToken.getString("payload"); if (mLog.isInfoEnabled()) { mLog.info("Processing 'getUser'..."); } } }); // on response of the login... lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "echo", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { String lPayload = aToken.getString("payload"); if (mLog.isInfoEnabled()) { mLog.info("Processing 'demo1 with Payload '" + lPayload + "'"); } Map<String, Object> lAdditionalResults = new FastMap<String, Object>(); lAdditionalResults.putAll(aToken.getMap()); // lAdditionalResults.remove("sourceId"); lAdditionalResults.remove("payload"); lJWSEndPoint.respondPayload(aToken, 0, // return code "Ok", // return message lAdditionalResults, aToken.getString("payload")); } }); // on response of the login... lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "testProgress", new JWSMessageListener(lJWSEndPoint) { @Override @SuppressWarnings("SleepWhileInLoop") public void processToken(String aSourceId, Token aToken) { int lMax = 10; for (int lIdx = 0; lIdx < lMax; lIdx++) { mLog.debug("Progress iteration " + lIdx + "..."); try { Thread.sleep(333); } catch (InterruptedException lEx) { } lJWSEndPoint.sendProgress(aToken, ((lIdx + 1.0) / lMax) * 100, 0, "Iteration #" + lIdx, null); } lJWSEndPoint.respondPayload(aToken, 0, // return code "Ok", // return message null, aToken.getString("payload")); } }); // ... lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "testCaughtException", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { mLog.debug("Testing caught exception..."); // provoke null pointer exception and DO catch it for test purposes int a = 1; int b = 0; try { int c = a / b; lJWSEndPoint.respondPayload(aToken, 0, // return code "Ok", // return message null, aToken.getString("payload")); } catch (Exception Ex) { lJWSEndPoint.respondPayload(aToken, -1, // return code Ex.getClass().getSimpleName() + ": " + Ex.getMessage(), // return message null, aToken.getString("payload")); } } }); // ... lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "testUncaughtException", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { mLog.debug("Testing uncaught exception..."); // provoke null pointer exception and do NOT catch it for test purposes int a = 1; int b = 0; int c = a / b; lJWSEndPoint.respondPayload(aToken, 0, // return code "Ok", // return message null, aToken.getString("payload")); } }); // test for the OAuth interface lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "testOAuth", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { Map<String, Object> lArgs = new FastMap<String, Object>(); String lUsername; int lCode = 0; String lMessage = "Ok"; try { lUsername = lOAuthAuthenticator.authToken(aToken); if (null == lUsername) { lCode = -1; lMessage = "User could not be authenticated!"; } else { lArgs.put("username", lUsername); } } catch (JMSEndpointException ex) { lCode = -1; lMessage = ex.getClass().getSimpleName() + " on authentication: " + ex.getMessage(); } lJWSEndPoint.respondPayload(aToken, lCode, // return code lMessage, // return message lArgs, // additional result fields null); // payload } }); // test for the LDAP interface lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "testLDAP", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { Map<String, Object> lArgs = new FastMap<String, Object>(); String lUsername; int lCode = 0; String lMessage = "Ok"; try { lUsername = lLDAPAuthenticator.authToken(aToken); if (null == lUsername) { lCode = -1; lMessage = "User could not be authenticated!"; } else { lArgs.put("username", lUsername); } } catch (JMSEndpointException ex) { lCode = -1; lMessage = ex.getClass().getSimpleName() + " on authentication: " + ex.getMessage(); } lJWSEndPoint.respondPayload(aToken, lCode, // return code lMessage, // return message lArgs, // additional result fields null); // payload } }); // test for the auto authentication interface lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "testAuth", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { mLog.debug("Testing auto authenticator..."); Map<String, Object> lArgs = new FastMap<String, Object>(); String lUsername; int lCode = 0; String lMessage = "Ok"; try { checkADUsername(aToken); lUsername = lAuthenticator.authToken(aToken); if (null == lUsername) { lCode = -1; lMessage = "User could not be authenticated!"; } else { lArgs.put("username", lUsername); } } catch (JMSEndpointException lEx) { lCode = -1; lMessage = lEx.getClass().getSimpleName() + " on auto authentication: " + lEx.getMessage(); } lJWSEndPoint.respondPayload(aToken, lCode, // return code lMessage, // return message lArgs, // additional result fields null); // payload } }); lJWSEndPoint.addRequestListener("tld.yourname.jms", "transferFile", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { // here you can get the additional arguments mLog.info("Received 'transferFile' with additional args" + " (arg1=" + aToken.getString("arg1") + " (arg2=" + aToken.getString("arg2") + ")..."); // here you get the payload from the requester String lPayload = aToken.getString("payload"); // parse the JSON payload into a Token (for simpler processing) Token lToken = JSONProcessor.JSONStringToToken(lPayload); // extract the base64 and compressed file contents into Strings // (it's a text message) // String lBase64Encoded = lToken.getString("fileAsBase64"); String lBase64Zipped = lToken.getString("fileAsZip"); // specify the target file File lFile = new File("Apache License 2.0 (copy).txt"); try { // take the zipped version of the file... byte[] lBA = Tools.unzip(lBase64Zipped.getBytes("UTF-8"), Boolean.TRUE); // and save it to the hard disk FileUtils.writeByteArrayToFile(lFile, lBA); } catch (Exception lEx) { mLog.error("Demo file " + lFile.getAbsolutePath() + " could not be saved!"); } } }); // add a high level listener to listen in coming messages lJWSEndPoint.addRequestListener("org.jwebsocket.jms.demo", "helloWorld", new JWSMessageListener(lJWSEndPoint) { @Override public void processToken(String aSourceId, Token aToken) { mLog.info("Received 'helloWorld'..."); lJWSEndPoint.respondPayload(aToken.getString("sourceId"), aToken, 0, // return code "Ok", // return message null, // here you can add additional results beside the payload "Hello World!"); } }); // start the endpoint all all listener have been assigned lJWSEndPoint.start(); return lJWSEndPoint; }