How to get the SSLHostConfig? - java

I am able to get the parent Connector with
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
QueryExp qe = Query.match(Query.attr("port"), Query.value("443"));
ObjectName on = new ObjectName("*:type=Connector,*");
Set<ObjectName> objectNames = mbs.queryNames(on, qe);
and I don't want to read server.xml in case it is out of sync.
How is one to get the SSLHostConfig ?

The Connector MBean does not contain information on the TLS configuration. You need to call the method findSslHostConfigs on a bean of type=ThreadPool. ThreadPool is actually a misnomer, since this MBean is exported by each ProtocolHandler.
final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
final QueryExp qe = Query.eq(Query.attr("port"), Query.value(443));
final ObjectName on = new ObjectName("*:type=ThreadPool,*");
final Set<ObjectName> protocols = mbs.queryNames(on, qe);
for (final ObjectName protocol : protocols) {
SSLHostConfig[] configs = (SSLHostConfig[]) mbs.invoke(protocol, "findSslHostConfigs", null, null);
// do something with the SSLHostConfig
}
Alternatively the SSLHostConfigs are available as MBeans too: they have the property type=SSLHostConfig.

Related

Can't send a message to queue on WIldfly 11

I am having this small message producer:
public static void main(String[] args) throws Exception {
BasicConfigurator.configure();
Properties env = new Properties();
InputStream is = Producer.class.getResourceAsStream("/jms.properties");
env.load(is);
Context context = new InitialContext(env);
ConnectionFactory factory = (ConnectionFactory) context.lookup("jms/RemoteConnectionFactory");
Destination queue = (Destination) context.lookup("jms/demoQueue");
JMSContext jmsContext = factory.createContext();
jmsContext.createProducer().send(queue, "Message");
}
Using the following properties:
java.naming.factory.initial = org.wildfly.naming.client.WildFlyInitialContextFactory
java.naming.provider.url = http-remoting://localhost:8080
java.naming.security.principal = alex
java.naming.security.credentials = password
messagingProvider = demo
connectionFactoryNames = QueueFactory
queue.queueReq = jms.queueReq
queue.queueResp = jms.queueResp
But I get an exception:
"Caused by: javax.jms.JMSSecurityException: AMQ119031: Unable to
validate user"
I believe I have misconfigured something on the server. But what exactly? Security settings have pattern: # with role guest and admin. I don't see anything else related to security
Call the overloaded createContext() method with 2 arguments:
JMSContext context = factory.createContext("alex", "password");
Then it should work if the "alex" user has correct role assigned.
I remember I had a discussion with developers about how the createContext() should work (it was in relation with Elytron - the new securtity subsystem), and the decission for now was like: It works as designed, but it can be enhanced in the future.
See comments in JBEAP-10527 for details.

List all deployments from Jboss using either JMX or JNDI

Is there a way to get a list of all deployments on a Jboss 6.0
implemented in Java either using JMX (ServerMBean) or JNDI?
On Wildfly 9.0.1.Final the code looks like this:
String host = "localhost";
int port = 9990;
String urlString = System.getProperty("jmx.service.url","service:jmx:http-remoting-jmx://" + host + ":" + port);
JMXServiceURL serviceURL = new JMXServiceURL(urlString);
JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceURL, null);
MBeanServerConnection connection = jmxConnector.getMBeanServerConnection();
ObjectName name = new ObjectName("jboss.modules:type=ModuleLoader,name=*");
Set<ObjectInstance> objectInstances = connection.queryMBeans(name, null);
for (ObjectInstance objectInstance : objectInstances) {
if (objectInstance.getObjectName().getCanonicalName().contains("ServiceModuleLoader")) {
System.out.println("invoking method on " + objectInstance.getObjectName());
Object dumpAllModuleInformation = connection.invoke(objectInstance.getObjectName(), "dumpAllModuleInformation", new Object[]{}, new String[]{});
System.out.println(dumpAllModuleInformation);
}
}
jmxConnector.close();
Maybe you can adapt this to JBoss 6. On Wildfly 9.0.1.Finale this outputs:
Module deployment.stackoverflow-jboss-1.0-SNAPSHOT.war:main
Class loader: ModuleClassLoader for Module "deployment.stackoverflow-jboss-1.0-SNAPSHOT.war:main" from Service Module Loader
Resource Loaders:
Loader Type: org.jboss.as.server.deployment.module.VFSResourceLoader
Paths:
META-INF
META-INF/maven
META-INF/maven/stackoverflow-jboss

How to connect and send data to MQ with java

I've run ActiveMQ in my machine (imqbrokerd.exe) and got below details. I've hidden my machine name with
[#|2015-10-01T19:16:06.788+0530|WARNING|5.1|imq.log.Logger|_ThreadID=1;_ThreadNa
me=main;|[S2004]: Log output channel com.sun.messaging.jmq.util.log.SysLogHandle
r is disabled: no imqutil in java.library.path|#]
[#|2015-10-01T19:16:06.804+0530|FORCE|5.1|imq.log.Logger|_ThreadID=1;_ThreadName
=main;|
================================================================================
Message Queue 5.1
Oracle
Version: 5.1 (Build 9-b)
Compile: July 29 2014 1229
Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
================================================================================
Java Runtime: 1.7.0_40 Oracle Corporation C:\Program Files (x86)\Java\jre7
|#]
[#|2015-10-01T19:16:06.819+0530|FORCE|5.1|imq.log.Logger|_ThreadID=1;_ThreadName
=main;| IMQ_HOME=C:\MessageQueue5.1\mq
|#]
[#|2015-10-01T19:16:06.819+0530|FORCE|5.1|imq.log.Logger|_ThreadID=1;_ThreadName
=main;|IMQ_VARHOME=C:\MessageQueue5.1\var\mq
|#]
[#|2015-10-01T19:16:06.819+0530|FORCE|5.1|imq.log.Logger|_ThreadID=1;_ThreadName
=main;|Windows 7 6.1 x86 <MachineName> (4 cpu)
|#]
[#|2015-10-01T19:16:06.835+0530|FORCE|5.1|imq.log.Logger|_ThreadID=1;_ThreadName
=main;|Java Heap Size: max=190080k, current=15872k
|#]
[#|2015-10-01T19:16:06.835+0530|FORCE|5.1|imq.log.Logger|_ThreadID=1;_ThreadName
=main;|Arguments:
|#]
[#|2015-10-01T19:16:06.850+0530|FORCE|5.1|imq.log.Logger|_ThreadID=1;_ThreadName
=main;|[B1060]: Loading persistent data...
|#]
[#|2015-10-01T19:16:06.866+0530|FORCE|5.1|imq.log.Logger|_ThreadID=1;_ThreadName
=main;|Using built-in file-based persistent store: C:\MessageQueue5.1\var\mq\ins
tances\imqbroker\
|#]
[#|2015-10-01T19:16:07.194+0530|FORCE|5.1|imq.log.Logger|_ThreadID=1;_ThreadName
=main;|[B1270]: Processing messages from transaction log file...
|#]
[#|2015-10-01T19:16:07.396+0530|FORCE|5.1|imq.log.Logger|_ThreadID=1;_ThreadName
=main;|[B1039]: Broker "imqbroker#<MachineName>:7676"
ready.
|#]
And I'm using below java program to connect to this queue.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Hashtable;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class QueueSendLinear {
public static void main(String args[]) throws JMSException, NamingException {
// Defines the JNDI context factory.
final String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";
// Defines the JMS context factory.
final String JMS_FACTORY="jms/TestConnectionFactory";
// Defines the queue.
final String QUEUE="jms/TestJMSQueue";
QueueConnectionFactory qconFactory;
QueueConnection qcon;
QueueSession qsession;
QueueSender qsender;
Queue queue;
TextMessage msg;
String xml = "Sample XML comes here!! ";
String url = "t3://<MachineName>:7676";
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
env.put(Context.PROVIDER_URL, url);
InitialContext ic = new InitialContext(env);
qconFactory = (QueueConnectionFactory) ic.lookup(JMS_FACTORY);
qcon = qconFactory.createQueueConnection();
qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
queue = (Queue) ic.lookup(QUEUE);
qsender = qsession.createSender(queue);
msg = qsession.createTextMessage();
qcon.start();
msg.setText(xml);
qsender.send(msg);
qsender.close();
qsession.close();
qcon.close();
}
}
question here...
a. What should be the values in JNDI_FACTORY, JMS_FACTORY, QUEUE, url and what do they signify?
b. What does 't3://' in url means? Is this a protocol ? if so, what should be given for active MQ?
FYI, i'm getting below error
Oct 01, 2015 7:20:58 PM com.sun.corba.se.impl.naming.namingutil.CorbalocURL badAddress
WARNING: "IOP00110603: (BAD_PARAM) Bad host address in -ORBInitDef"
org.omg.CORBA.BAD_PARAM: vmcid: SUN minor code: 603 completed: No
[UPDATE #1]:
When I use below code, I get below error. I've attached images of my activeMQ queue details. I know that the URL that i'm using is wrong. Can you please help me out with the right one?
Exception in thread "main" javax.naming.NamingException: Couldn't connect to the specified host : [Root exception is org.omg.CORBA.COMM_FAILURE: vmcid: SUN minor code: 208 completed: Maybe]
at weblogic.corba.j2ee.naming.Utils.wrapNamingException(Utils.java:83)
at weblogic.corba.j2ee.naming.ORBHelper.getORBReferenceWithRetry(ORBHelper.java:656)
final String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";
final String JMS_FACTORY="jms/?";
final String QUEUE = "mq.sys.dmq";
QueueConnectionFactory qconFactory;
QueueConnection qcon;
QueueSession qsession;
QueueSender qsender;
Queue queue;
TextMessage msg;
String xml = "Sample XML comes here!! ";
String url = "t3://localhost:51010";
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
env.put(Context.PROVIDER_URL, url);
InitialContext ic = new InitialContext(env);
qconFactory = (QueueConnectionFactory) ic.lookup(JMS_FACTORY);
qcon = qconFactory.createQueueConnection();
qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
queue = (Queue) ic.lookup(QUEUE);
qsender = qsession.createSender(queue);
msg = qsession.createTextMessage();
qcon.start();
Hope this Helps..
I have passed the JMS server name as an argument. And WLS library jar should be imported
private static final String CONNECTION_FACTORY_NAME ="connection factory name goes here";
private static final String TOPIC_NAME = "Topic Name goes here";
private static final String SERVER_URL_PREFIX = "t3://";
private static final String SERVER_URL_SUFFIX = ".url.com:port";
private static final String USER = "";
private static final String PASSWORD = "";
private static final String LOCAL_DIRECTORY = "C:\\tmp\\poslog\\";
public static void main(String args[]) throws JMSException,
NamingException, IOException, InterruptedException {
System.out.println("start" + new Date());
// INITIALIZE
System.out.println("creating context for " + args[0]);
Hashtable<String, String> properties = new Hashtable<String, String>();
properties.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
properties.put(Context.PROVIDER_URL, SERVER_URL_PREFIX + args[0] + SERVER_URL_SUFFIX);
//properties.put(Context.SECURITY_PRINCIPAL, USER);
//properties.put(Context.SECURITY_CREDENTIALS, PASSWORD);
InitialContext ctx = new InitialContext(properties);
TopicConnectionFactory connectionFactory = (TopicConnectionFactory) ctx
.lookup(CONNECTION_FACTORY_NAME);
TopicConnection connection = connectionFactory.createTopicConnection();
TopicSession session = connection.createTopicSession(false, 0);
Topic topic = (Topic) ctx.lookup(TOPIC_NAME);
TopicPublisher sender = session.createPublisher(topic);
JNDI_FACTORY is more like a driver that you want to use to connect, they are usually specific to the vendor in your case is weblogic and is pre-defined.
JMS_FACTORY is the connection factory that you have already predefined in web logic for this type of integration. it is responsible for managing the connections to the queue.
QUEUE also is something that you need to predefine / setup on weblogic admin console. It is the reference to the queues that reside on weblogic which you have setup before hand.
t3 is the connection type you are using, the other alternative could be iiop. t3 it is a more lightweight type of connection.

Embedded Jetty application

I a newbie in Jetty. I have created an application in which I embed the jetty web container. When I run the the application from eclipse it runs perfectly without any issues. However when I export the project with all the required libraries and run it from command line I cannot access the index.jsp web page like I used to in eclispe. This is the file that run the jetty web container.
public class JettyServer {
// The folder containing all the .jsp files
private final static String WEB_ROOT = "src/WebContent";
// Instance of the Jetty server
private final static Server SRV = new Server();
// Context Path
private final static String CONTEXT_PATH = "/smpp";
// Logging
private final static org.slf4j.Logger logger = LoggerFactory.getLogger(JettyServer.class);
/**
* #param args
* #throws ConfigurationException
*/
public static void main(String[] args) throws ConfigurationException {
logger.info("Initializing Web Server......");
// Servlet Context
final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
// Set the security constraints
context.setContextPath(CONTEXT_PATH);
context.setResourceBase(WEB_ROOT);
context.setClassLoader(Thread.currentThread().getContextClassLoader());
context.addServlet(DefaultServlet.class, "/");
context.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
String [] welcomeFiles = {"index.jsp"};
context.setWelcomeFiles(welcomeFiles);
// Set the .jsp servlet handlers
final ServletHolder jsp = context.addServlet(JspServlet.class, "*.jsp");
jsp.setInitParameter("classpath", context.getClassPath());
// Session Manager
SessionHandler sh = new SessionHandler();
context.setSessionHandler(sh);
/* Http Request Handlers */
context.addServlet(HttpRequestProcessor.class, "/HttpHandler");
// Server configuration setup
// Connector setup
// We explicitly use the SocketConnector because the SelectChannelConnector locks files
Connector connector = new SocketConnector();
connector.setHost("localhost");
connector.setPort(Integer.parseInt(System.getProperty("jetty.port", new PropertiesConfiguration("smpp-config.properties").getString("http_port").trim())));
connector.setMaxIdleTime(60000);
JettyServer.SRV.setConnectors(new Connector[] { connector });
JettyServer.SRV.setHandler(context);
JettyServer.SRV.setAttribute("org.mortbay.jetty.Request.maxFormContentSize", 0);
JettyServer.SRV.setGracefulShutdown(5000);
JettyServer.SRV.setStopAtShutdown(true);
logger.info("Starting Jetty Web Container....");
try{
JettyServer.SRV.start();
}
catch(Exception ex){
logger.error("Jetty Web Container failed to start [CAUSE : " + ex.getMessage() + "]");
return;
}
logger.info("Jetty Web Container running....");
while(true){
try{
JettyServer.SRV.join();
}
catch(InterruptedException iex){
logger.error("Jetty Web Container interrupted [CAUSE : " + iex.getMessage() + "]");
}
}
}
}
code formatted properly
Your use of relative paths in the context.setResourceBase("src/WebContent"); will cause you problems.
Use a full, and absolute, URI reference with context.setResourceBase(String).
Note that you can use the following URI schemes: file, ftp, jar, and even http
Instead of this
final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
Can you use this ?
WebAppContext root = new WebAppContext();
and rest of the code as example :
String webappDirLocation = "src/Webcontent/";
Server server = new Server(8080);
root.setContextPath(CONTEXT_PATH);
root.setDescriptor(webappDirLocation + "/WEB-INF/web.xml");
root.setResourceBase(webappDirLocation);
root.setParentLoaderPriority(true);
server.setHandler(root);

Can an EJB be called from a desktop application?

I am new in Java EJB 3.0. It is possible to call a (session) bean—deployed on JBoss—from a desktop application client?
Thanks in advance.
Yes you can. Some specifics are here (references EJB2 but it the same for EJB3 when it comes to remote clients): http://www.theserverside.com/discussions/thread.tss?thread_id=9197
Paraphrased:
Hashtable env = new Hashtable();
env.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
env.put("java.naming.provider.url", "jnp://localhost:1099");
env.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
Context ctx = new InitialContext(env);
// name is whatever JNDI name you gave it
Object o = ctx.lookup("home name");
EJBHome ejbHome = (EJBHome) PortableRemoteObject.narrow(o,EJBHome.class);
// This is userID should be the one passed.
EJB ejb = ejbHome.create(..);
Yes.
public static void main(String args[]) throws Exception {
InitialContext ctx = new InitialContext();
YourService yourService = (YourService) ctx.lookup("com.example.session.YourService");
String time = yourService.getTime();
System.out.println("Time is: " + time);
}
For client configuration you must provide jndi.properties file with contents
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost
If you are looking for working examples on JBoss try download source code of Enterprise JavaBeans 3.0, Fifth Edition
Let's assume you have the following remote interface:
#Remote
public interface HelloBeanRemote {
public String sayHello();
}
And a session bean implementing it:
#Stateless
public class HelloBean implements HelloBeanRemote {
...
}
And that this EJB is correctly packaged and deployed on JBoss.
On the client side, create a jndi.properties with the following content and put it on the classpath:
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost:1099
Then use the following code to call your EJB:
Context context;
try {
context = new InitialContext();
HelloBeanRemote beanRemote = (HelloBeanRemote)context.lookup("HelloBean/remote");
beanRemote.test();
} catch (NamingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
Alternatively, if you don't want to provide a jndi.properties file, you can explicitly setup the JNDI environment in the code and create the context like this:
Properties properties = new Properties();
properties.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
properties.put("java.naming.factory.url.pkgs","=org.jboss.naming:org.jnp.interfaces");
properties.put("java.naming.provider.url","localhost:1099");
Context context = new InitialContext(properties);
But I'd recommend using the jndi.properties for the sake of portability.
You can also expose the bean as a web service. I believe this is available as of EJB 3. It is quite nice considering you can do it with annotations. You may wish to consider using this option to decrease coupling. Here is a link to a tutorial.

Categories

Resources