Search in sources :

Example 6 with J4pExecRequest

use of org.jolokia.client.request.J4pExecRequest in project camel by apache.

the class DefaultJolokiaCamelController method listComponents.

@Override
public List<Map<String, String>> listComponents(String camelContextName) throws Exception {
    if (jolokia == null) {
        throw new IllegalStateException("Need to connect to remote jolokia first");
    }
    List<Map<String, String>> answer = new ArrayList<Map<String, String>>();
    ObjectName found = lookupCamelContext(camelContextName);
    if (found != null) {
        J4pExecResponse response = jolokia.execute(new J4pExecRequest(found, "listComponents()"));
        if (response != null) {
            JSONObject data = response.getValue();
            for (Object obj : data.values()) {
                JSONObject component = (JSONObject) obj;
                Map<String, String> row = new LinkedHashMap<String, String>();
                row.put("artifactId", asString(component.get("artifactId")));
                row.put("title", asString(component.get("title")));
                row.put("description", asString(component.get("description")));
                row.put("groupId", asString(component.get("groupId")));
                row.put("label", asString(component.get("label")));
                row.put("name", asString(component.get("name")));
                row.put("status", asString(component.get("status")));
                row.put("type", asString(component.get("type")));
                row.put("version", asString(component.get("version")));
                answer.add(row);
            }
        }
        // sort the list
        Collections.sort(answer, new Comparator<Map<String, String>>() {

            @Override
            public int compare(Map<String, String> component1, Map<String, String> component2) {
                String name1 = component1.get("name");
                String name2 = component2.get("name");
                return name1.compareTo(name2);
            }
        });
    }
    return answer;
}
Also used : J4pExecRequest(org.jolokia.client.request.J4pExecRequest) ArrayList(java.util.ArrayList) ObjectName(javax.management.ObjectName) LinkedHashMap(java.util.LinkedHashMap) JSONObject(org.json.simple.JSONObject) JSONObject(org.json.simple.JSONObject) J4pExecResponse(org.jolokia.client.request.J4pExecResponse) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 7 with J4pExecRequest

use of org.jolokia.client.request.J4pExecRequest in project camel by apache.

the class DefaultJolokiaCamelController method getRestServices.

@Override
public List<Map<String, String>> getRestServices(String camelContextName) throws Exception {
    if (jolokia == null) {
        throw new IllegalStateException("Need to connect to remote jolokia first");
    }
    List<Map<String, String>> answer = new ArrayList<Map<String, String>>();
    ObjectName found = lookupCamelContext(camelContextName);
    if (found != null) {
        String pattern = String.format("%s:context=%s,type=services,name=DefaultRestRegistry", found.getDomain(), found.getKeyProperty("context"));
        ObjectName on = ObjectName.getInstance(pattern);
        J4pExecResponse response = jolokia.execute(new J4pExecRequest(on, "listRestServices()"));
        if (response != null) {
            JSONObject data = response.getValue();
            if (data != null) {
                for (Object obj : data.values()) {
                    JSONObject data2 = (JSONObject) obj;
                    JSONObject service = (JSONObject) data2.values().iterator().next();
                    Map<String, String> row = new LinkedHashMap<String, String>();
                    row.put("basePath", asString(service.get("basePath")));
                    row.put("baseUrl", asString(service.get("baseUrl")));
                    row.put("consumes", asString(service.get("consumes")));
                    row.put("description", asString(service.get("description")));
                    row.put("inType", asString(service.get("inType")));
                    row.put("method", asString(service.get("method")));
                    row.put("outType", asString(service.get("outType")));
                    row.put("produces", asString(service.get("produces")));
                    row.put("routeId", asString(service.get("routeId")));
                    row.put("state", asString(service.get("state")));
                    row.put("uriTemplate", asString(service.get("uriTemplate")));
                    row.put("url", asString(service.get("url")));
                    answer.add(row);
                }
            }
        }
        // sort the list
        Collections.sort(answer, new Comparator<Map<String, String>>() {

            @Override
            public int compare(Map<String, String> service1, Map<String, String> service2) {
                String url1 = service1.get("url");
                String url2 = service2.get("url");
                return url1.compareTo(url2);
            }
        });
    }
    return answer;
}
Also used : J4pExecRequest(org.jolokia.client.request.J4pExecRequest) ArrayList(java.util.ArrayList) ObjectName(javax.management.ObjectName) LinkedHashMap(java.util.LinkedHashMap) JSONObject(org.json.simple.JSONObject) JSONObject(org.json.simple.JSONObject) J4pExecResponse(org.jolokia.client.request.J4pExecResponse) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 8 with J4pExecRequest

use of org.jolokia.client.request.J4pExecRequest in project opennms by OpenNMS.

the class JolokiaBeanMonitor method poll.

/**
 * {@inheritDoc}
 *
 * Poll the specified address for service availability.
 *
 * During the poll an attempt is made to execute the named method (with
 * optional input) connect on the specified port. If the exec on request is
 * successful, the banner line generated by the interface is parsed and if
 * the banner text indicates that we are talking to Provided that the
 * interface's response is valid we set the service status to
 * SERVICE_AVAILABLE and return.
 */
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    // 
    // Process parameters
    // 
    // 
    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    // Port
    int port = ParameterMap.getKeyedInteger(parameters, PARAMETER_PORT, DEFAULT_PORT);
    // URL
    String strURL = ParameterMap.getKeyedString(parameters, PARAMETER_URL, DEFAULT_URL);
    // Username
    String strUser = ParameterMap.getKeyedString(parameters, PARAMETER_USERNAME, null);
    // Password
    String strPasswd = ParameterMap.getKeyedString(parameters, PARAMETER_PASSWORD, null);
    // AttrName
    String strAttrName = ParameterMap.getKeyedString(parameters, PARAMETER_ATTRNAME, null);
    // AttrPath
    String strAttrPath = ParameterMap.getKeyedString(parameters, PARAMETER_ATTRPATH, null);
    // BeanName
    String strBeanName = ParameterMap.getKeyedString(parameters, PARAMETER_BEANNAME, null);
    // MethodName
    String strMethodName = ParameterMap.getKeyedString(parameters, PARAMETER_METHODNAME, null);
    // Optional Inputs
    String strInput1 = ParameterMap.getKeyedString(parameters, PARAMETER_METHODINPUT1, null);
    String strInput2 = ParameterMap.getKeyedString(parameters, PARAMETER_METHODINPUT2, null);
    // BannerMatch
    String strBannerMatch = ParameterMap.getKeyedString(parameters, PARAMETER_BANNER, null);
    // Get the address instance.
    InetAddress ipAddr = svc.getAddress();
    final String hostAddress = InetAddressUtils.str(ipAddr);
    LOGGER.debug("poll: address = " + hostAddress + ", port = " + port + ", " + tracker);
    strURL = strURL.replace("${ipaddr}", hostAddress);
    strURL = strURL.replace("${port}", ((Integer) port).toString());
    LOGGER.debug("poll: final URL address = " + strURL);
    // Give it a whirl
    PollStatus serviceStatus = PollStatus.unknown("Initialized");
    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        try {
            tracker.startAttempt();
            J4pClientBuilder j4pClientBuilder = new J4pClientBuilder();
            j4pClientBuilder.url(strURL).connectionTimeout(tracker.getConnectionTimeout()).socketTimeout(tracker.getSoTimeout());
            if (strUser != null && strPasswd != null) {
                j4pClientBuilder.user(strUser).password(strPasswd);
            }
            J4pClient j4pClient = j4pClientBuilder.build();
            LOGGER.debug("JolokiaBeanMonitor: connected to URLhost: " + strURL);
            // We're connected, so upgrade status to unresponsive
            serviceStatus = PollStatus.unresponsive();
            if (strBannerMatch == null || strBannerMatch.length() == 0 || strBannerMatch.equals("*")) {
                serviceStatus = PollStatus.available(tracker.elapsedTimeInMillis());
                break;
            }
            // Exec a method or poll an attribute?
            String response;
            if (strAttrName != null) {
                J4pReadRequest readReq = new J4pReadRequest(strBeanName, strAttrName);
                readReq.setPreferredHttpMethod("POST");
                if (strAttrPath != null) {
                    readReq.setPath(strAttrPath);
                }
                J4pReadResponse resp = j4pClient.execute(readReq);
                response = resp.getValue().toString();
            } else {
                J4pExecRequest execReq;
                // Default Inputs
                if (strInput1 == null && strInput2 == null) {
                    LOGGER.debug("JolokiaBeanMonitor - execute bean: " + strBeanName + " method: " + strMethodName);
                    execReq = new J4pExecRequest(strBeanName, strMethodName);
                } else if (strInput1 != null && strInput2 == null) {
                    // Single Input
                    LOGGER.debug("JolokiaBeanMonitor - execute bean: " + strBeanName + " method: " + strMethodName + " args: " + strInput1);
                    execReq = new J4pExecRequest(strBeanName, strMethodName, strInput1);
                } else {
                    // Double Input
                    LOGGER.debug("JolokiaBeanMonitor - execute bean: " + strBeanName + " method: " + strMethodName + " args: " + strInput1 + " " + strInput2);
                    execReq = new J4pExecRequest(strBeanName, strMethodName, strInput1, strInput2);
                }
                execReq.setPreferredHttpMethod("POST");
                J4pExecResponse resp = j4pClient.execute(execReq);
                response = resp.getValue().toString();
            }
            double responseTime = tracker.elapsedTimeInMillis();
            if (response == null) {
                continue;
            }
            LOGGER.debug("poll: banner = " + response);
            LOGGER.debug("poll: responseTime = " + responseTime + "ms");
            // Could it be a regex?
            if (strBannerMatch.charAt(0) == '~') {
                if (!response.matches(strBannerMatch.substring(1))) {
                    serviceStatus = PollStatus.unavailable("Banner does not match Regex '" + strBannerMatch + "'");
                } else {
                    serviceStatus = PollStatus.available(responseTime);
                }
            } else {
                if (response.contains(strBannerMatch)) {
                    serviceStatus = PollStatus.available(responseTime);
                } else {
                    serviceStatus = PollStatus.unavailable("Did not find expected Text '" + strBannerMatch + "'");
                }
            }
        } catch (J4pConnectException e) {
            String reason = "Connection exception for address: " + ipAddr + ":" + port + " " + e.getMessage();
            LOGGER.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
            break;
        } catch (J4pRemoteException e) {
            String reason = "Remote exception from J4pRemote: " + e.getMessage();
            LOGGER.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (MalformedObjectNameException e) {
            String reason = "Parameters for Jolokia are malformed: " + e.getMessage();
            LOGGER.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (J4pException e) {
            String reason = J4pException.class.getSimpleName() + " during Jolokia monitor call: " + e.getMessage();
            LOGGER.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        }
    }
    return serviceStatus;
}
Also used : MalformedObjectNameException(javax.management.MalformedObjectNameException) PollStatus(org.opennms.netmgt.poller.PollStatus) J4pReadRequest(org.jolokia.client.request.J4pReadRequest) J4pExecRequest(org.jolokia.client.request.J4pExecRequest) J4pConnectException(org.jolokia.client.exception.J4pConnectException) J4pClient(org.jolokia.client.J4pClient) J4pRemoteException(org.jolokia.client.exception.J4pRemoteException) J4pReadResponse(org.jolokia.client.request.J4pReadResponse) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) J4pException(org.jolokia.client.exception.J4pException) J4pClientBuilder(org.jolokia.client.J4pClientBuilder) J4pExecResponse(org.jolokia.client.request.J4pExecResponse) InetAddress(java.net.InetAddress)

Example 9 with J4pExecRequest

use of org.jolokia.client.request.J4pExecRequest in project fabric8 by jboss-fuse.

the class FabricServiceFacade method getContainers.

@Override
public Container[] getContainers() {
    List<Container> containers = new ArrayList<Container>();
    try {
        J4pExecRequest request = Helpers.createExecRequest("containers(java.util.List)", toList("id"));
        J4pExecResponse response = getJolokiaClient().execute(request);
        List<Map<String, Object>> values = response.getValue();
        for (Map<String, Object> value : values) {
            containers.add(new ContainerFacade(this, getJolokiaClient(), (String) value.get("id")));
        }
    } catch (Exception e) {
        throw new RuntimeException("Failed to fetch container list", e);
    }
    return containers.toArray(new Container[containers.size()]);
}
Also used : J4pExecRequest(org.jolokia.client.request.J4pExecRequest) ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) JSONObject(org.json.simple.JSONObject) J4pExecResponse(org.jolokia.client.request.J4pExecResponse) Map(java.util.Map) Override(java.lang.Override)

Example 10 with J4pExecRequest

use of org.jolokia.client.request.J4pExecRequest in project fabric8 by jboss-fuse.

the class DeployToProfileMojo method uploadRequirements.

protected DeployResults uploadRequirements(J4pClient client, ProjectRequirements requirements) throws Exception {
    String json = DtoHelper.getMapper().writeValueAsString(requirements);
    ObjectName mbeanName = ProjectDeployerImpl.OBJECT_NAME;
    getLog().info("Updating " + (requirements.isAbstractProfile() ? "abstract " : "") + "profile: " + requirements.getProfileId() + " with parent profile(s): " + requirements.getParentProfiles() + (requirements.isUseResolver() ? " using OSGi resolver" : "") + (requirements.isLocked() ? " locked" : ""));
    getLog().info("About to invoke mbean " + mbeanName + " on jolokia URL: " + jolokiaUrl + " with user: " + fabricServer.getUsername());
    getLog().debug("JSON: " + json);
    try {
        // Append bundles to existing profile bundles if we're not running the plugin at project root
        Boolean appendBundles = !mavenSession.getExecutionRootDirectory().equalsIgnoreCase(project.getBasedir().toString());
        J4pExecRequest request = new J4pExecRequest(mbeanName, "deployProjectJsonMergeOption(java.lang.String,boolean)", json, appendBundles);
        J4pResponse<J4pExecRequest> response = client.execute(request, "POST");
        Object value = response.getValue();
        if (value == null) {
            return null;
        } else {
            DeployResults answer = DtoHelper.getMapper().reader(DeployResults.class).readValue(value.toString());
            if (answer != null) {
                String profileUrl = answer.getProfileUrl();
                if (profileUrl != null) {
                    getLog().info("");
                    getLog().info("Profile page: " + profileUrl);
                    getLog().info("");
                } else {
                    getLog().info("Result: " + answer);
                }
            } else {
                getLog().info("Result: " + value);
            }
            return answer;
        }
    } catch (J4pRemoteException e) {
        if (e.getMessage().contains(".InstanceNotFoundException")) {
            throw new MojoExecutionException("Could not find the mbean " + mbeanName + " in the JVM for " + jolokiaUrl + ". Are you sure this JVM is running the Fabric8 console?");
        } else {
            getLog().error("Failed to invoke mbean " + mbeanName + " on jolokia URL: " + jolokiaUrl + " with user: " + fabricServer.getUsername() + ". Error: " + e.getErrorType());
            getLog().error("Stack: " + e.getRemoteStackTrace());
            throw e;
        }
    }
}
Also used : J4pRemoteException(org.jolokia.client.exception.J4pRemoteException) DeployResults(io.fabric8.deployer.dto.DeployResults) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) J4pExecRequest(org.jolokia.client.request.J4pExecRequest) ObjectName(javax.management.ObjectName)

Aggregations

J4pExecRequest (org.jolokia.client.request.J4pExecRequest)24 ObjectName (javax.management.ObjectName)17 J4pExecResponse (org.jolokia.client.request.J4pExecResponse)12 ArrayList (java.util.ArrayList)8 Map (java.util.Map)7 JSONObject (org.json.simple.JSONObject)7 HashMap (java.util.HashMap)6 LinkedHashMap (java.util.LinkedHashMap)6 J4pException (org.jolokia.client.exception.J4pException)5 J4pRemoteException (org.jolokia.client.exception.J4pRemoteException)3 J4pReadRequest (org.jolokia.client.request.J4pReadRequest)3 List (java.util.List)2 MalformedObjectNameException (javax.management.MalformedObjectNameException)2 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)2 AbtractJ4pMBeanRequest (org.jolokia.client.request.AbtractJ4pMBeanRequest)2 J4pResponse (org.jolokia.client.request.J4pResponse)2 J4pWriteRequest (org.jolokia.client.request.J4pWriteRequest)2 DeployResults (io.fabric8.deployer.dto.DeployResults)1 IOException (java.io.IOException)1 Override (java.lang.Override)1