Trying to trigger JMX Mbean functions from command line - wildfly-8

My application is running on Wildfly-8.0.1. Currently, I am able to trigger MBean methods through JConsole using service:jmx:http-remoting-jmx://localhost:9990.
I want to write some script to trigger those commands but I didn't find a supporting tool to accomplish that.
I tried below tools, but it seems like they are not supporting http-remoting-jmx protocol or may be I am not using in right way
1. JMXTerm
2. Cmdline_JMXClient
3. JManage
4. CJMX
Here is the error from JMXTerm
$>open service:jmx:http-remoting-jmx://localhost:9990
RuntimeIOException: Runtime IO exception: Unsupported protocol: http-remoting-j
mx
any help would greatly be appreciated.

Create custom jar file using below class.
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
public class JMXCli {
//private static List<String> operations;
private static final String SERVICE_URL = "service:jmx:http-remoting-jmx://";
public static void main(String[] args) throws Exception {
JMXServiceURL url = new JMXServiceURL(SERVICE_URL + args[0]);
JMXConnector connector = JMXConnectorFactory.connect(url);
MBeanServerConnection connection = connector.getMBeanServerConnection();
ObjectName objectName = new ObjectName("com.xyz.com:name=<<Your MBean class name>>");
System.out.println(connection.invoke(objectName, args[1], null, null));
}
}

Related

Cannot import package in unit tests for a Jenkins Shared Library

I'm attempting to create unit tests for a JenkinsShared library using Gradle in order to run the test tasks.
I've followed this tutorial which upon conclusion one has a working test suite for a shared library for functions within the vars folder (with the unit tests in src/test/groovy/*Test.groovy).
However, in our internal shared jenkins library we followed a more object oriented style and isolated functionality into a package of classes in the format: src/org/company/*.groovy.
The problem arises when attempting to import said package into a unit test class. In the tutorial, the functions are imported using the loadScript method this method fails when loading a class which is dependent on another file.
Take the class:
package tests
import org.junit.*
import com.lesfurets.jenkins.unit.*
import static groovy.test.GroovyAssert.*
import org.company.UtilFactory
class UtilFactoryTest extends BasePipelineTest {
#Test
void testCall() {
def util = UtilFactory.getUtil("hello")
assertEquals true, true
}
}
src/org/company/UtilFactory.groovy
package org.company
class UtilFactory implements Serializable {
static Util instance
static Util getUtil(script=null) {
if (!(UtilFactory.instance)) {
if (!script) {
// Throws an exception if on the first call to getUtil the
// script parameter is null.
throw new ScriptUndefinedException("script parameter null on initial call to getUtil")
}
UtilFactory.instance = new Util(script)
}
return UtilFactory.instance
}
}
class ScriptUndefinedException extends Exception {
// Parameterless Constructor
public ScriptUndefinedException() {}
// Constructor that accepts a message
public ScriptUndefinedException(String message)
{
super(message);
}
}
Which gives me the exception:
jenkins-utilities/src/test/groovy/UtilFactoryTest.groovy: 7:
unable to resolve class org.company.UtilFactory
# line 7, column 1.
import org.company.UtilFactory
This may be more of a Gradle issue than a JenkinsShared Library. I've just spent a good portion of my day trying to figure out exactly what I'm doing wrong to no avail.
I would really appreciate any help to guide me in the right direction.
This library may be helpful getting your shared libraries to work in the unit test https://github.com/stchar/pipeline-sharedlib-testharness

Context & Dependency Injection : How to inject implementation of an interface?

I am at beginner stage of CDI and trying to inject the implementation of interface using field injection as below:
AutoService.java
package com.interfaces;
public interface AutoService {
void getService();
}
BMWAutoService.java
package com.implementations;
import javax.inject.Named;
import com.interfaces.AutoService;
#Named("bmwAutoService")
public class BMWAutoService implements AutoService {
public BMWAutoService() {
// TODO Auto-generated constructor stub
}
#Override
public void getService() {
System.out.println("You chose BMW auto service");
}
}
AutoServiceCaller.java
package com.interfaces;
public interface AutoServiceCaller {
void callAutoService();
}
AutoServiceCallerImp.java
package com.implementations;
import javax.inject.Inject;
import javax.inject.Named;
import com.interfaces.AutoService;
import com.interfaces.AutoServiceCaller;
public class AutoServiceCallerImp implements AutoServiceCaller {
#Inject
#Named("bmwAutoService")
private AutoService bmwAutoService;
public AutoServiceCallerImp() {
}
#Override
public void callAutoService() {
bmwAutoService.getService();
}
}
TestDisplayMessage.java
package com.tests;
import com.implementations.AutoServiceCallerImp;
import com.interfaces.AutoServiceCaller;
public class TestDisplayMessage {
public TestDisplayMessage() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
AutoServiceCaller caller = new AutoServiceCallerImp();
caller.callAutoService();
}
}
When I run TestDisplayMessage.java , the expected result would be "You chose BMW auto service" but I get NullPointerException as below :
Exception in thread "main" java.lang.NullPointerException
at com.implementations.AutoServiceCallerImp.callAutoService(AutoServiceCallerImp.java:21)
at com.tests.TestDisplayMessage.main(TestDisplayMessage.java:16)
Couldn't figure out exactly what I am missing here. Please help.Thanks in advance.
Ok, it seems you misunderstood the concept of CDI a bit - the idea is that you leave the bean lifecycle to CDI container. That means CDI will create a dispose beans for you. In other words, you are not supposed to create beans by calling new. If you do that, CDI does not know about it and will not inject anything into it.
If you are in SE environment, which I think you are since you use main method to test, you want to use Weld (CDI implementation) SE artifact (I guess you do that).
There, you will need to start the CDI container. Note that if you were developing a classical EE application on a server, you don't do this, because the server will handle it for you. Now, the very basic way to boot Weld SE container is:
Weld weld = new Weld();
try (WeldContainer container = weld.initialize()) {
// inside this try-with-resources block you have CDI container booted
//now, ask it to give you an instance of AutoServiceCallerImpl
AutoServiceCallerImpl as = container.select(AutoService.class).get();
as.callAutoService();
}
Now, second issue with your code. The usage of #Named is intended for EL resolution. E.g. in JFS pages, so you can access the bean directly. What you probably want is to differentiate between several AutoService implementations and choose a given one. For that CDI has qualifiers. Check this documentation section for more information on how to use them.

Override property in application.groovy with external config in grails 3

There is no grails.config.locations property in grails 3 anymore, now Grails 3 uses Spring's property source concept instead, but how can I achieve the same behavior in grails 3 as it was in previous versions? Suppose I want to override some property property.to.be.overridden in application.grovy file with my external configuration file. How can I do it?
The equivalent of grails.config.locations is spring.config.location
http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-application-property-files
Here is an example specifying configuration locations while launching a jar from the command line(These same arguments can be used inside of your ide)
java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
Also since you mention wanting to override properties it's useful to learn the way Spring Boot handles profile specific property files(Multiple profiles may also be specified)
http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties
I solved this a slightly different way, so I could load an external YAML file.
Application.groovy
package com.mycompany.myapp
import grails.boot.GrailsApp
import grails.boot.config.GrailsAutoConfiguration
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean
import org.springframework.context.EnvironmentAware
import org.springframework.core.env.Environment
import org.springframework.core.env.PropertiesPropertySource
import org.springframework.core.io.FileSystemResource
import org.springframework.core.io.Resource;
class Application extends GrailsAutoConfiguration implements EnvironmentAware {
static void main(String[] args) {
GrailsApp.run(Application)
}
#Override
void setEnvironment(Environment environment) {
String configPath = System.properties["myapp.config.location"]
if (configPath) {
Resource resourceConfig = new FileSystemResource(configPath);
YamlPropertiesFactoryBean propertyFactoryBean = new YamlPropertiesFactoryBean();
propertyFactoryBean.setResources(resourceConfig);
propertyFactoryBean.afterPropertiesSet();
Properties properties = propertyFactoryBean.getObject();
environment.propertySources.addFirst(new PropertiesPropertySource("myapp.config.location", properties))
}
}
}
Then I specify the YAML file when I run it
command line
java -jar -Dmyapp.config.location=/etc/myapp/application.yml build/libs/myapp-0.1.war

Exception in thread "main" java.lang.Error: Unresolved compilation problems: JNI4net

I am working with JNI4net and although the libraries and installed in the build path and eclipse recognizes them, it still gives me run time error. Why could that be in your opinion? Here is the code.
import net.sf.jni4net.*;
import java.io.IOException;
import java.lang.String;
import system.*;
import system.Object;
import system.io.TextWriter;
import system.collections.IDictionary;
import system.collections.IEnumerator;
/**
* #author Pavel Savara (original)
*/
public class Program {
public static void main(String[] args) throws IOException {
// create bridge, with default setup
// it will lookup jni4net.n.dll next to jni4net.j.jar
//Bridge.setVerbose(true);
Bridge.setVerbose(true);
Bridge.init();
// here you go!
Console.WriteLine("Hello .NET world!\n");
// OK, simple hello is boring, let's play with System.Environment
// they are Hashtable realy
final IDictionary variables = system.Environment.GetEnvironmentVariables();
// let's enumerate all keys
final IEnumerator keys = variables.getKeys().GetEnumerator();
while (keys.MoveNext()) {
// there hash table is not generic and returns system.Object
// but we know is should be system.String, so we could cast
final system.String key = (system.String) keys.getCurrent();
Console.Write(key);
// this is automatic conversion of JVM string to system.String
Console.Write(" : ");
// we use the hashtable
Object value = variables.getItem(key);
// and this is JVM toString() redirected to CLR ToString() method
String valueToString = value.toString();
Console.WriteLine(valueToString);
}
// Console output is really TextWriter on stream
final TextWriter writer = Console.getOut();
writer.Flush();
}
}
AND here is the message I get!
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Bridge cannot be resolved
Bridge cannot be resolved
Console cannot be resolved
IDictionary cannot be resolved to a type
system cannot be resolved
IEnumerator cannot be resolved to a type
system cannot be resolved to a type
system cannot be resolved to a type
Console cannot be resolved
Console cannot be resolved
Console cannot be resolved
TextWriter cannot be resolved to a type
Console cannot be resolved
at Program.main(Program.java:37)
To make your life easier, I am going to share my findings here. Read Martin Serrano's answer to my question. It will help you understand what needs to be done. Then go to jni4net's website and download their example zip folder. Extract that. There is an example there called myCSharpDemoCalc. Replace your dll with myCSharpDemoCalc.dll (inside work folder) and then run generateProxies.cmd (be sure to edit this file to your dll name) and run.cmd. Then go to the work folder and run build.cmd (edit name) to create your JAR file. It might not spit out the j4n.dll you probably need to twik the path yourself. Use this JAR file. This was the easiest way to create a JAR file from a third party dll for me.

Groovy can't compile the code from a solution given on StackOverflow

Answer 1 to this StackOverflow post provides some Groovy code, but it doesn't compile (for me, Groovy Console Version 2.1.3, or in my Grails 2.2.3 app).
Can you please assist in letting me know what I need to change to make this code work? The error I get is:
unexpected token: public at line 14, column: 52 (... which is the "public X509 Certificate[]")
For quick reference the code solution provided in Answer 1 is:
import javax.net.ssl.X509TrustManager
import javax.net.ssl.SSLContext
import java.security.cert.X509Certificate
import javax.net.ssl.TrustManager
import java.security.SecureRandom
import org.apache.http.conn.ssl.SSLSocketFactory
import org.apache.http.conn.scheme.Scheme
import org.apache.http.conn.scheme.SchemeRegistry
def http = new HTTPBuilder( "https://your_unsecure_certificate_host" )
//=== SSL UNSECURE CERTIFICATE ===
def sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, [ new X509TrustManager() {public X509Certificate[]
getAcceptedIssuers() {null }
public void checkClientTrusted(X509Certificate[] certs, String authType) { }
public void checkServerTrusted(X509Certificate[] certs, String authType) { }
} ] as TrustManager[], new SecureRandom())
def sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
def httpsScheme = new Scheme("https", sf, 443)
http.client.connectionManager.schemeRegistry.register( httpsScheme )
//================================
You probably have a newline between the public X509Certificate[] and getAcceptedIssuers() {null} as a result of pasting the code in.
Try removing the newline (and formatting the code to something moderately readable while you're at it) and the error should disappear.

Resources