javax.management.Query Java Examples

The following examples show how to use javax.management.Query. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RelationServiceExample.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void endExample()
{
   try
   {
      System.out.println("Cleaning up......");
      // this query will return the set of mbeans which have a class attribute of "management*" which is our MBeans
      Set mbeanSet = m_server.queryMBeans(null, Query.initialSubString(Query.classattr(), Query.value("management*")));
      for (Iterator i = mbeanSet.iterator(); i.hasNext();)
      {
         m_server.unregisterMBean(((ObjectInstance)i.next()).getObjectName());
      }
      // release the relationService
      m_server.unregisterMBean(m_relationObjectName);
      // release the MBeanServer
      MBeanServerFactory.releaseMBeanServer(m_server);
      System.exit(0);
   }
   catch (Exception ex)
   {
      ex.printStackTrace();
      System.exit(1);
   }
}
 
Example #2
Source File: TestClusterAggregateMetrics.java    From helix with Apache License 2.0 6 votes vote down vote up
/**
 * Queries for all MBeans from the MBean Server and only looks at the relevant MBean and gets its
 * metric numbers.
 */
private void updateMetrics() {
  try {
    QueryExp exp = Query.match(Query.attr("SensorName"), Query.value("*" + CLUSTER_NAME + "*"));
    Set<ObjectInstance> mbeans = new HashSet<>(ManagementFactory.getPlatformMBeanServer()
        .queryMBeans(new ObjectName("ClusterStatus:*"), exp));
    for (ObjectInstance instance : mbeans) {
      ObjectName beanName = instance.getObjectName();
      if (beanName.toString().equals("ClusterStatus:cluster=" + CLUSTER_NAME)) {
        MBeanInfo info = _server.getMBeanInfo(beanName);
        MBeanAttributeInfo[] infos = info.getAttributes();
        for (MBeanAttributeInfo infoItem : infos) {
          Object val = _server.getAttribute(beanName, infoItem.getName());
          _beanValueMap.put(infoItem.getName(), val);
        }
      }
    }
  } catch (Exception e) {
    // update failed
  }
}
 
Example #3
Source File: TestTaskPerformanceMetrics.java    From helix with Apache License 2.0 6 votes vote down vote up
/**
 * Queries for all MBeans from the MBean Server and only looks at the relevant MBean and gets its
 * metric numbers.
 */
private void extractMetrics() {
  try {
    QueryExp exp = Query.match(Query.attr("SensorName"), Query.value(CLUSTER_NAME + ".Job.*"));
    Set<ObjectInstance> mbeans = new HashSet<>(
        ManagementFactory.getPlatformMBeanServer().queryMBeans(new ObjectName("ClusterStatus:*"), exp));
    for (ObjectInstance instance : mbeans) {
      ObjectName beanName = instance.getObjectName();
      if (instance.getClassName().endsWith("JobMonitor")) {
        MBeanInfo info = _server.getMBeanInfo(beanName);
        MBeanAttributeInfo[] infos = info.getAttributes();
        for (MBeanAttributeInfo infoItem : infos) {
          Object val = _server.getAttribute(beanName, infoItem.getName());
          _beanValueMap.put(infoItem.getName(), val);
        }
      }
    }
  } catch (Exception e) {
    // update failed
  }
}
 
Example #4
Source File: RelationServiceAdaptor.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void endTests()
{
   try
   {
      m_adaptor.stop();
      Set mbeanSet = m_server.queryMBeans(null, Query.initialSubString(Query.classattr(), Query.value("test*")));
      for (Iterator i = mbeanSet.iterator(); i.hasNext();)
      {
         m_server.unregisterMBean(((ObjectInstance)i.next()).getObjectName());
      }
      // release the relationService
      m_server.unregisterMBean(m_relationServiceObjectName);
      m_server.unregisterMBean(processorName);
      m_server.unregisterMBean(httpAdaptorObjectName);
      // release the MBeanServer
      MBeanServerFactory.releaseMBeanServer(m_server);
      System.exit(0);
   }
   catch (Exception ex)
   {
      ex.printStackTrace();
      System.exit(1);
   }
}
 
Example #5
Source File: ServerManager.java    From bistoury with GNU General Public License v3.0 6 votes vote down vote up
private static String getTomcatPortByMxBean() {
    String tomcatPort = "-1";
    try {
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();
        if (server != null) {
            Set<ObjectName> objectNames = server.queryNames(new ObjectName("*:type=Connector,*"),
                    Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
            tomcatPort = objectNames.iterator().next().getKeyProperty("port");
        }

    } catch (Exception e) {
        logger.error("get tomcat port error", e);
        throw Throwables.propagate(e);
    }
    return tomcatPort;
}
 
Example #6
Source File: BaseTool.java    From zooadmin with MIT License 6 votes vote down vote up
public static String getServer() {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ArrayList<String> endPoints = new ArrayList<String>();
    try {
        Set<ObjectName> objs = mbs.queryNames(new ObjectName("*:type=Connector,*"), Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
        String hostname = InetAddress.getLocalHost().getHostName();
        InetAddress[] addresses = InetAddress.getAllByName(hostname);
        for (Iterator<ObjectName> i = objs.iterator(); i.hasNext(); ) {
            ObjectName obj = i.next();
            String scheme = mbs.getAttribute(obj, "scheme").toString();
            String port = obj.getKeyProperty("port");
            for (InetAddress addr : addresses) {
                String host = addr.getHostAddress();
                String ep = scheme + "://" + host + ":" + port;
                endPoints.add(ep);
            }
        }
    } catch (Exception e) {
        return "";
    }
    if (endPoints.size() > 0) {
        return endPoints.get(0);
    } else {
        return "";
    }
}
 
Example #7
Source File: Solr4X509ServletFilter.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
Optional<ObjectName> connectorMBeanName()
{
    try
    {
        final QueryExp query = Query.eq(Query.attr("Scheme"), Query.value("https"));
        final Set<ObjectName> connectors = mxServer().queryNames(null, query);
        return connectors
                .stream()
                .findFirst();
    }
    catch (final Exception exception)
    {
        logger.error("Error getting the Connector MBean.", exception);
        return Optional.empty();
    }
}
 
Example #8
Source File: BaseTool.java    From zooadmin with MIT License 6 votes vote down vote up
public static String getServer() {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ArrayList<String> endPoints = new ArrayList<String>();
    try {
        Set<ObjectName> objs = mbs.queryNames(new ObjectName("*:type=Connector,*"), Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
        String hostname = InetAddress.getLocalHost().getHostName();
        InetAddress[] addresses = InetAddress.getAllByName(hostname);
        for (Iterator<ObjectName> i = objs.iterator(); i.hasNext(); ) {
            ObjectName obj = i.next();
            String scheme = mbs.getAttribute(obj, "scheme").toString();
            String port = obj.getKeyProperty("port");
            for (InetAddress addr : addresses) {
                String host = addr.getHostAddress();
                String ep = scheme + "://" + host + ":" + port;
                endPoints.add(ep);
            }
        }
    } catch (Exception e) {
        return "";
    }
    if (endPoints.size() > 0) {
        return endPoints.get(0);
    } else {
        return "";
    }
}
 
Example #9
Source File: SessionExpireTestRun.java    From twill with Apache License 2.0 5 votes vote down vote up
private boolean expireAppMasterZKSession(TwillController controller, long timeout, TimeUnit timeoutUnit) {
  MBeanServer mbeanServer = MBeanRegistry.getInstance().getPlatformMBeanServer();
  QueryExp query = Query.isInstanceOf(new StringValueExp(ConnectionMXBean.class.getName()));

  Stopwatch stopwatch = new Stopwatch();
  stopwatch.start();
  do {
    // Find the AM session and expire it
    Set<ObjectName> connectionBeans = mbeanServer.queryNames(ObjectName.WILDCARD, query);
    for (ObjectName objectName : connectionBeans) {

      ConnectionMXBean connectionBean = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, objectName,
                                                                                      ConnectionMXBean.class, false);
      for (String node : connectionBean.getEphemeralNodes()) {
        if (node.endsWith("/instances/" + controller.getRunId().getId())) {
          // This is the AM, expire the session.
          LOG.info("Kill AM session {}", connectionBean.getSessionId());
          connectionBean.terminateSession();
          return true;
        }
      }
    }
    Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
  } while (stopwatch.elapsedTime(timeoutUnit) < timeout);

  return false;
}
 
Example #10
Source File: QueryMatchTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static int query(MBeanServer mbs,
                         String pattern,
                         String[][] data) throws Exception {

    int error = 0;

    System.out.println("\nAttribute Value Pattern = " + pattern + "\n");
    for (int i = 0; i < data.length; i++) {
        ObjectName on = new ObjectName("domain:type=Simple,pattern=" +
                                       ObjectName.quote(pattern) +
                                       ",name=" + i);
        Simple s = new Simple(data[i][0]);
        mbs.registerMBean(s, on);
        QueryExp q =
            Query.match(Query.attr("StringNumber"), Query.value(pattern));
        q.setMBeanServer(mbs);
        boolean r = q.apply(on);
        System.out.print("Attribute Value = " +
            mbs.getAttribute(on, "StringNumber"));
        if (r && "OK".equals(data[i][1])) {
            System.out.println(" OK");
        } else if (!r && "KO".equals(data[i][1])) {
            System.out.println(" KO");
        } else {
            System.out.println(" Error");
            error++;
        }
    }

    return error;
}
 
Example #11
Source File: QueryMatchTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private static int query(MBeanServer mbs,
                         String pattern,
                         String[][] data) throws Exception {

    int error = 0;

    System.out.println("\nAttribute Value Pattern = " + pattern + "\n");
    for (int i = 0; i < data.length; i++) {
        ObjectName on = new ObjectName("domain:type=Simple,pattern=" +
                                       ObjectName.quote(pattern) +
                                       ",name=" + i);
        Simple s = new Simple(data[i][0]);
        mbs.registerMBean(s, on);
        QueryExp q =
            Query.match(Query.attr("StringNumber"), Query.value(pattern));
        q.setMBeanServer(mbs);
        boolean r = q.apply(on);
        System.out.print("Attribute Value = " +
            mbs.getAttribute(on, "StringNumber"));
        if (r && "OK".equals(data[i][1])) {
            System.out.println(" OK");
        } else if (!r && "KO".equals(data[i][1])) {
            System.out.println(" KO");
        } else {
            System.out.println(" Error");
            error++;
        }
    }

    return error;
}
 
Example #12
Source File: JmxMetricsReporter.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private JmxListener(MBeanServer mBeanServer, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit,
                    ObjectNameFactory objectNameFactory, String tag) {
  this.mBeanServer = mBeanServer;
  this.name = name;
  this.filter = filter;
  this.rateUnit = rateUnit;
  this.durationUnit = durationUnit;
  this.registered = new ConcurrentHashMap<>();
  this.objectNameFactory = objectNameFactory;
  this.tag = tag;
  this.exp = Query.eq(Query.attr(INSTANCE_TAG), Query.value(tag));
}
 
Example #13
Source File: AbstractCommandsController.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the MemberMXBean from the JVM Platform MBeanServer for the specified member, identified by name or ID,
 * in the GemFire cluster.
 * <p/>
 * @param memberNameId a String indicating the name or ID of the GemFire member.
 * @return a proxy to the GemFire member's MemberMXBean.
 * @throws IllegalStateException if no MemberMXBean could be found for GemFire member with ID or name.
 * @throws RuntimeException wrapping the MalformedObjectNameException if the ObjectName pattern is malformed.
 * @see #getMBeanServer()
 * @see javax.management.JMX
 * @see com.gemstone.gemfire.management.MemberMXBean
 * @see com.gemstone.gemfire.management.internal.ManagementConstants
 */
protected MemberMXBean getMemberMXBean(final String memberNameId) {
  try {
    final MBeanServer connection = getMBeanServer();

    final String objectNamePattern = ManagementConstants.OBJECTNAME__PREFIX.concat("type=Member,*");

    // NOTE possibly throws a MalformedObjectNameException, but this should not happen
    final ObjectName objectName = ObjectName.getInstance(objectNamePattern);

    final QueryExp query = Query.or(
      Query.eq(Query.attr("Name"), Query.value(memberNameId)),
      Query.eq(Query.attr("Id"), Query.value(memberNameId))
    );

    final Set<ObjectName> objectNames = connection.queryNames(objectName, query);

    assertState(isMemberMXBeanFound(objectNames),
      "No MemberMXBean with ObjectName (%1$s) was found in the Platform MBeanServer for member (%2$s)!",
        objectName, memberNameId);

    return JMX.newMXBeanProxy(connection, objectNames.iterator().next(), MemberMXBean.class);
  }
  catch (MalformedObjectNameException e) {
    throw new RuntimeException(e);
  }
}
 
Example #14
Source File: LauncherLifecycleCommandsDUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
protected static String getMemberId(final String jmxManagerHost, final int jmxManagerPort, final String memberName)
  throws Exception
{
  JMXConnector connector = null;

  try {
    connector = JMXConnectorFactory.connect(new JMXServiceURL(String.format(
      "service:jmx:rmi://%1$s/jndi/rmi://%1$s:%2$d/jmxrmi", jmxManagerHost, jmxManagerPort)));

    final MBeanServerConnection connection = connector.getMBeanServerConnection();

    final ObjectName objectNamePattern = ObjectName.getInstance("GemFire:type=Member,*");

    final QueryExp query = Query.eq(Query.attr("Name"), Query.value(memberName));

    final Set<ObjectName> objectNames = connection.queryNames(objectNamePattern, query);

    assertNotNull(objectNames);
    assertEquals(1, objectNames.size());

    //final ObjectName objectName = ObjectName.getInstance("GemFire:type=Member,Name=" + memberName);
    final ObjectName objectName = objectNames.iterator().next();

    //System.err.printf("ObjectName for Member with Name (%1$s) is %2$s%n", memberName, objectName);

    return ObjectUtils.toString(connection.getAttribute(objectName, "Id"));
  }
  finally {
    IOUtils.close(connector);
  }
}
 
Example #15
Source File: QueryParameterSourceJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@Test
public void testSerialization() throws ClassNotFoundException, IOException, MalformedObjectNameException {
  final ObjectName expectedObjectName = ObjectName.getInstance("GemFire:type=Member,*");
  
  final QueryExp expectedQueryExpression = Query.or(
    Query.eq(Query.attr("name"), Query.value("myName")),
    Query.eq(Query.attr("id"), Query.value("myId"))
  );

  final QueryParameterSource expectedQuery = new QueryParameterSource(expectedObjectName, expectedQueryExpression);

  assertNotNull(expectedQuery);
  assertSame(expectedObjectName, expectedQuery.getObjectName());
  assertSame(expectedQueryExpression, expectedQuery.getQueryExpression());

  final byte[] queryBytes = IOUtils.serializeObject(expectedQuery);

  assertNotNull(queryBytes);
  assertTrue(queryBytes.length != 0);

  final Object queryObj = IOUtils.deserializeObject(queryBytes);

  assertTrue(queryObj instanceof QueryParameterSource);

  final QueryParameterSource actualQuery = (QueryParameterSource) queryObj;

  assertNotSame(expectedQuery, actualQuery);
  assertNotNull(actualQuery.getObjectName());
  assertEquals(expectedQuery.getObjectName().toString(), actualQuery.getObjectName().toString());
  assertNotNull(actualQuery.getQueryExpression());
  assertEquals(expectedQuery.getQueryExpression().toString(), actualQuery.getQueryExpression().toString());
}
 
Example #16
Source File: QueryParameterSourceJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateQueryParameterSource() throws MalformedObjectNameException {
  final ObjectName expectedObjectName = ObjectName.getInstance("GemFire:type=Member,*");
  
  final QueryExp expectedQueryExpression = Query.eq(Query.attr("id"), Query.value("12345"));

  final QueryParameterSource query = new QueryParameterSource(expectedObjectName, expectedQueryExpression);

  assertNotNull(query);
  assertSame(expectedObjectName, query.getObjectName());
  assertSame(expectedQueryExpression, query.getQueryExpression());
}
 
Example #17
Source File: MBeanProcessController.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the QueryExp used to identify the target MBean.
 * 
 * @param pidAttribute the name of the MBean attribute with the process id to compare against
 * @param attributes the names of additional MBean attributes to compare with expected values
 * @param values the expected values of the specified MBean attributes
 *
 * @return the main QueryExp for matching the target MBean
 */
private QueryExp buildQueryExp(final String pidAttribute, final String[] attributes, final Object[] values) {
  final QueryExp optionalAttributes = buildOptionalQueryExp(attributes, values);
  QueryExp constraint;
  if (optionalAttributes != null) {
    constraint = Query.and(optionalAttributes, Query.eq(
      Query.attr(pidAttribute),
      Query.value(this.pid)));
  } else {
    constraint = Query.eq(
        Query.attr(pidAttribute),
        Query.value(this.pid));
  }
  return constraint;
}
 
Example #18
Source File: ContextLoaderListener.java    From oneplatform with Apache License 2.0 5 votes vote down vote up
private static  int getServerPort(){
    int port = 0;
    try {
        MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
        Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"),
                Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));

        port = Integer.valueOf(objectNames.iterator().next().getKeyProperty("port"));
    }catch (Exception e){
    	if(StringUtils.isNotBlank(System.getProperty("jetty.port"))){
    		port = Integer.parseInt(System.getProperty("jetty.port"));
    	}
    }
    return port;
}
 
Example #19
Source File: MBeanProcessController.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Builds an optional QueryExp to aid in matching the correct MBean using 
 * additional attributes with the specified values. Returns null if no
 * attributes and values were specified during construction.
 * 
 * @param attributes the names of additional MBean attributes to compare with expected values
 * @param values the expected values of the specified MBean attributes
 *
 * @return optional QueryExp to aid in matching the correct MBean 
 */
private QueryExp buildOptionalQueryExp(final String[] attributes, final Object[] values) {
  QueryExp queryExp = null;
  for (int i = 0; i < attributes.length; i++) {
    if (values[i] instanceof Boolean) {
      if (queryExp == null) { 
        queryExp = Query.eq(
            Query.attr(attributes[i]), 
            Query.value(((Boolean) values[i])));
      } else {
        queryExp = Query.and(queryExp, 
            Query.eq(Query.attr(attributes[i]), 
            Query.value(((Boolean) values[i]))));
      }
    } else if (values[i] instanceof Number) {
      if (queryExp == null) { 
        queryExp = Query.eq(
            Query.attr(attributes[i]), 
            Query.value((Number)values[i]));
      } else {
        queryExp = Query.and(queryExp, 
            Query.eq(Query.attr(attributes[i]), 
            Query.value((Number)values[i])));
      }
    } else if (values[i] instanceof String) {
      if (queryExp == null) { 
        queryExp = Query.eq(
            Query.attr(attributes[i]), 
            Query.value((String)values[i]));
      } else {
        queryExp = Query.and(queryExp, 
            Query.eq(Query.attr(attributes[i]), 
            Query.value((String)values[i])));
      }
    }
  }
  return queryExp;
}
 
Example #20
Source File: LauncherLifecycleCommands.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
protected MemberMXBean getMemberMXBean(final String serviceName, final String member) throws IOException {
  assertState(isConnectedAndReady(), "Gfsh must be connected in order to get proxy to a GemFire Member MBean.");

  MemberMXBean memberBean = null;

  try {
    String objectNamePattern = ManagementConstants.OBJECTNAME__PREFIX;

    objectNamePattern += (StringUtils.isBlank(serviceName) ? StringUtils.EMPTY_STRING
      : "service=" + serviceName + StringUtils.COMMA_DELIMITER);
    objectNamePattern += "type=Member,*";

    // NOTE throws a MalformedObjectNameException, however, this should not happen since the ObjectName is constructed
    // here in a conforming pattern
    final ObjectName objectName = ObjectName.getInstance(objectNamePattern);

    final QueryExp query = Query.or(
      Query.eq(Query.attr("Name"), Query.value(member)),
      Query.eq(Query.attr("Id"), Query.value(member))
    );

    final Set<ObjectName> memberObjectNames = getGfsh().getOperationInvoker().queryNames(objectName, query);

    if (!memberObjectNames.isEmpty()) {
      memberBean = getGfsh().getOperationInvoker().getMBeanProxy(memberObjectNames.iterator().next(), MemberMXBean.class);
    }
  }
  catch (MalformedObjectNameException e) {
    getGfsh().logSevere(e.getMessage(), e);
  }

  return memberBean;
}
 
Example #21
Source File: LocalProcessController.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the QueryExp used to identify the target MBean.
 * 
 * @param pidAttribute the name of the MBean attribute with the process id to compare against
 * @param attributes the names of additional MBean attributes to compare with expected values
 * @param values the expected values of the specified MBean attributes
 *
 * @return the main QueryExp for matching the target MBean
 */
private QueryExp buildQueryExp(final String pidAttribute, final String[] attributes, final Object[] values) {
  final QueryExp optionalAttributes = buildOptionalQueryExp(attributes, values);
  QueryExp constraint;
  if (optionalAttributes != null) {
    constraint = Query.and(optionalAttributes, Query.eq(
      Query.attr(pidAttribute),
      Query.value(this.pid)));
  } else {
    constraint = Query.eq(
        Query.attr(pidAttribute),
        Query.value(this.pid));
  }
  return constraint;
}
 
Example #22
Source File: LocalProcessController.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Builds an optional QueryExp to aid in matching the correct MBean using 
 * additional attributes with the specified values. Returns null if no
 * attributes and values were specified during construction.
 * 
 * @param attributes the names of additional MBean attributes to compare with expected values
 * @param values the expected values of the specified MBean attributes
 *
 * @return optional QueryExp to aid in matching the correct MBean 
 */
private QueryExp buildOptionalQueryExp(final String[] attributes, final Object[] values) {
  QueryExp queryExp = null;
  for (int i = 0; i < attributes.length; i++) {
    if (values[i] instanceof Boolean) {
      if (queryExp == null) { 
        queryExp = Query.eq(
            Query.attr(attributes[i]), 
            Query.value(((Boolean) values[i])));
      } else {
        queryExp = Query.and(queryExp, 
            Query.eq(Query.attr(attributes[i]), 
            Query.value(((Boolean) values[i]))));
      }
    } else if (values[i] instanceof Number) {
      if (queryExp == null) { 
        queryExp = Query.eq(
            Query.attr(attributes[i]), 
            Query.value((Number)values[i]));
      } else {
        queryExp = Query.and(queryExp, 
            Query.eq(Query.attr(attributes[i]), 
            Query.value((Number)values[i])));
      }
    } else if (values[i] instanceof String) {
      if (queryExp == null) { 
        queryExp = Query.eq(
            Query.attr(attributes[i]), 
            Query.value((String)values[i]));
      } else {
        queryExp = Query.and(queryExp, 
            Query.eq(Query.attr(attributes[i]), 
            Query.value((String)values[i])));
      }
    }
  }
  return queryExp;
}
 
Example #23
Source File: MBeanProcessController.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the QueryExp used to identify the target MBean.
 * 
 * @param pidAttribute the name of the MBean attribute with the process id to compare against
 * @param attributes the names of additional MBean attributes to compare with expected values
 * @param values the expected values of the specified MBean attributes
 *
 * @return the main QueryExp for matching the target MBean
 */
private QueryExp buildQueryExp(final String pidAttribute, final String[] attributes, final Object[] values) {
  final QueryExp optionalAttributes = buildOptionalQueryExp(attributes, values);
  QueryExp constraint;
  if (optionalAttributes != null) {
    constraint = Query.and(optionalAttributes, Query.eq(
      Query.attr(pidAttribute),
      Query.value(this.pid)));
  } else {
    constraint = Query.eq(
        Query.attr(pidAttribute),
        Query.value(this.pid));
  }
  return constraint;
}
 
Example #24
Source File: MBeanProcessController.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Builds an optional QueryExp to aid in matching the correct MBean using 
 * additional attributes with the specified values. Returns null if no
 * attributes and values were specified during construction.
 * 
 * @param attributes the names of additional MBean attributes to compare with expected values
 * @param values the expected values of the specified MBean attributes
 *
 * @return optional QueryExp to aid in matching the correct MBean 
 */
private QueryExp buildOptionalQueryExp(final String[] attributes, final Object[] values) {
  QueryExp queryExp = null;
  for (int i = 0; i < attributes.length; i++) {
    if (values[i] instanceof Boolean) {
      if (queryExp == null) { 
        queryExp = Query.eq(
            Query.attr(attributes[i]), 
            Query.value(((Boolean) values[i])));
      } else {
        queryExp = Query.and(queryExp, 
            Query.eq(Query.attr(attributes[i]), 
            Query.value(((Boolean) values[i]))));
      }
    } else if (values[i] instanceof Number) {
      if (queryExp == null) { 
        queryExp = Query.eq(
            Query.attr(attributes[i]), 
            Query.value((Number)values[i]));
      } else {
        queryExp = Query.and(queryExp, 
            Query.eq(Query.attr(attributes[i]), 
            Query.value((Number)values[i])));
      }
    } else if (values[i] instanceof String) {
      if (queryExp == null) { 
        queryExp = Query.eq(
            Query.attr(attributes[i]), 
            Query.value((String)values[i]));
      } else {
        queryExp = Query.and(queryExp, 
            Query.eq(Query.attr(attributes[i]), 
            Query.value((String)values[i])));
      }
    }
  }
  return queryExp;
}
 
Example #25
Source File: QueryParameterSourceJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateQueryParameterSource() throws MalformedObjectNameException {
  final ObjectName expectedObjectName = ObjectName.getInstance("GemFire:type=Member,*");
  
  final QueryExp expectedQueryExpression = Query.eq(Query.attr("id"), Query.value("12345"));

  final QueryParameterSource query = new QueryParameterSource(expectedObjectName, expectedQueryExpression);

  assertNotNull(query);
  assertSame(expectedObjectName, query.getObjectName());
  assertSame(expectedQueryExpression, query.getQueryExpression());
}
 
Example #26
Source File: QueryParameterSourceJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@Test
public void testSerialization() throws ClassNotFoundException, IOException, MalformedObjectNameException {
  final ObjectName expectedObjectName = ObjectName.getInstance("GemFire:type=Member,*");
  
  final QueryExp expectedQueryExpression = Query.or(
    Query.eq(Query.attr("name"), Query.value("myName")),
    Query.eq(Query.attr("id"), Query.value("myId"))
  );

  final QueryParameterSource expectedQuery = new QueryParameterSource(expectedObjectName, expectedQueryExpression);

  assertNotNull(expectedQuery);
  assertSame(expectedObjectName, expectedQuery.getObjectName());
  assertSame(expectedQueryExpression, expectedQuery.getQueryExpression());

  final byte[] queryBytes = IOUtils.serializeObject(expectedQuery);

  assertNotNull(queryBytes);
  assertTrue(queryBytes.length != 0);

  final Object queryObj = IOUtils.deserializeObject(queryBytes);

  assertTrue(queryObj instanceof QueryParameterSource);

  final QueryParameterSource actualQuery = (QueryParameterSource) queryObj;

  assertNotSame(expectedQuery, actualQuery);
  assertNotNull(actualQuery.getObjectName());
  assertEquals(expectedQuery.getObjectName().toString(), actualQuery.getObjectName().toString());
  assertNotNull(actualQuery.getQueryExpression());
  assertEquals(expectedQuery.getQueryExpression().toString(), actualQuery.getQueryExpression().toString());
}
 
Example #27
Source File: LauncherLifecycleCommandsDUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
protected static String getMemberId(final String jmxManagerHost, final int jmxManagerPort, final String memberName)
  throws Exception
{
  JMXConnector connector = null;

  try {
    connector = JMXConnectorFactory.connect(new JMXServiceURL(String.format(
      "service:jmx:rmi://%1$s/jndi/rmi://%1$s:%2$d/jmxrmi", jmxManagerHost, jmxManagerPort)));

    final MBeanServerConnection connection = connector.getMBeanServerConnection();

    final ObjectName objectNamePattern = ObjectName.getInstance("GemFire:type=Member,*");

    final QueryExp query = Query.eq(Query.attr("Name"), Query.value(memberName));

    final Set<ObjectName> objectNames = connection.queryNames(objectNamePattern, query);

    assertNotNull(objectNames);
    assertEquals(1, objectNames.size());

    //final ObjectName objectName = ObjectName.getInstance("GemFire:type=Member,Name=" + memberName);
    final ObjectName objectName = objectNames.iterator().next();

    //System.err.printf("ObjectName for Member with Name (%1$s) is %2$s%n", memberName, objectName);

    return ObjectUtils.toString(connection.getAttribute(objectName, "Id"));
  }
  finally {
    IOUtils.close(connector);
  }
}
 
Example #28
Source File: QueryMatchTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static int query(MBeanServer mbs,
                         String pattern,
                         String[][] data) throws Exception {

    int error = 0;

    System.out.println("\nAttribute Value Pattern = " + pattern + "\n");
    for (int i = 0; i < data.length; i++) {
        ObjectName on = new ObjectName("domain:type=Simple,pattern=" +
                                       ObjectName.quote(pattern) +
                                       ",name=" + i);
        Simple s = new Simple(data[i][0]);
        mbs.registerMBean(s, on);
        QueryExp q =
            Query.match(Query.attr("StringNumber"), Query.value(pattern));
        q.setMBeanServer(mbs);
        boolean r = q.apply(on);
        System.out.print("Attribute Value = " +
            mbs.getAttribute(on, "StringNumber"));
        if (r && "OK".equals(data[i][1])) {
            System.out.println(" OK");
        } else if (!r && "KO".equals(data[i][1])) {
            System.out.println(" KO");
        } else {
            System.out.println(" Error");
            error++;
        }
    }

    return error;
}
 
Example #29
Source File: QueryMatchTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static int query(MBeanServer mbs,
                         String pattern,
                         String[][] data) throws Exception {

    int error = 0;

    System.out.println("\nAttribute Value Pattern = " + pattern + "\n");
    for (int i = 0; i < data.length; i++) {
        ObjectName on = new ObjectName("domain:type=Simple,pattern=" +
                                       ObjectName.quote(pattern) +
                                       ",name=" + i);
        Simple s = new Simple(data[i][0]);
        mbs.registerMBean(s, on);
        QueryExp q =
            Query.match(Query.attr("StringNumber"), Query.value(pattern));
        q.setMBeanServer(mbs);
        boolean r = q.apply(on);
        System.out.print("Attribute Value = " +
            mbs.getAttribute(on, "StringNumber"));
        if (r && "OK".equals(data[i][1])) {
            System.out.println(" OK");
        } else if (!r && "KO".equals(data[i][1])) {
            System.out.println(" KO");
        } else {
            System.out.println(" Error");
            error++;
        }
    }

    return error;
}
 
Example #30
Source File: ApiRestletApplication.java    From geowave with Apache License 2.0 5 votes vote down vote up
private static String getHTTPEndPoint() throws Exception {
  final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
  final QueryExp subQuery1 = Query.match(Query.attr("protocol"), Query.value("HTTP/1.1"));
  final QueryExp subQuery2 = Query.anySubString(Query.attr("protocol"), Query.value("Http11"));
  final QueryExp query = Query.or(subQuery1, subQuery2);
  final Set<ObjectName> objs = mbs.queryNames(new ObjectName("*:type=Connector,*"), query);
  // HP Fortify "DNS Lookups" false positive
  // The DNS lookups referenced here are not used for Security purposes
  final String hostname = InetAddress.getLocalHost().getHostName();
  // HP Fortify "DNS Lookups" false positive
  // The DNS lookups referenced here are not used for Security purposes
  final InetAddress[] addresses = InetAddress.getAllByName(hostname);
  for (final Iterator<ObjectName> i = objs.iterator(); i.hasNext();) {
    final ObjectName obj = i.next();
    // final String scheme = mbs.getAttribute(
    // obj,
    // "scheme").toString();
    final String port = obj.getKeyProperty("port");
    // HP Fortify "DNS Lookups" false positive
    // The DNS lookups referenced here are not used for Security
    // purposes
    for (final InetAddress addr : addresses) {
      if (addr.isAnyLocalAddress() || addr.isLoopbackAddress() || addr.isMulticastAddress()) {
        continue;
      }
      final String host = addr.getHostAddress();
      // just return the first one
      return host + ":" + port;
    }
    return hostname + ":" + port;
  }
  return "localhost:8080";
}