Java 类javax.management.Query 实例源码

项目:zooadmin    文件:BaseTool.java   
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 "";
    }
}
项目:monarch    文件:AbstractCommandsController.java   
/**
 * Gets the MemberMXBean from the JVM Platform MBeanServer for the specified member, identified by
 * name or ID in the GemFire cluster.
 * 
 * @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 #isMemberMXBeanFound(java.util.Collection)
 * @see javax.management.ObjectName
 * @see javax.management.QueryExp
 * @see javax.management.MBeanServer#queryNames(javax.management.ObjectName,
 *      javax.management.QueryExp)
 * @see javax.management.JMX#newMXBeanProxy(javax.management.MBeanServerConnection,
 *      javax.management.ObjectName, Class)
 * @see org.apache.geode.management.MemberMXBean
 */
protected MemberMXBean getMemberMXBean(final String memberNameId) {
  try {
    final MBeanServer connection = getMBeanServer();

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

    // NOTE throws a MalformedObjectNameException, but this should not happen since we constructed
    // the ObjectName above
    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) based on Query (%2$s) was found in the Platform MBeanServer for member (%3$s)!",
        objectName, query, memberNameId);

    return JMX.newMXBeanProxy(connection, objectNames.iterator().next(), MemberMXBean.class);
  } catch (MalformedObjectNameException e) {
    throw new RuntimeException(e);
  }
}
项目:monarch    文件:MBeanServerConnectionRule.java   
/**
 * Retrieve a new proxy MBean
 *
 * @return A new proxy MBean of the same type with which the class was constructed
 */
public <T> T getProxyMBean(Class<T> proxyClass, String beanQueryName)
    throws MalformedObjectNameException, IOException {
  ObjectName name = null;
  QueryExp query = null;

  if (proxyClass != null) {
    query = Query.isInstanceOf(Query.value(proxyClass.getName()));
  }

  if (beanQueryName != null) {
    name = ObjectName.getInstance(beanQueryName);
  }

  Set<ObjectInstance> beans = con.queryMBeans(name, query);
  assertEquals("failed to find only one instance of type " + proxyClass.getName() + " with name "
      + beanQueryName, 1, beans.size());

  return JMX.newMXBeanProxy(con, ((ObjectInstance) beans.toArray()[0]).getObjectName(),
      proxyClass);
}
项目:zooadmin    文件:BaseTool.java   
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 "";
    }
}
项目:Camel    文件:ManagedRoute.java   
public void reset(boolean includeProcessors) throws Exception {
    reset();

    // and now reset all processors for this route
    if (includeProcessors) {
        MBeanServer server = getContext().getManagementStrategy().getManagementAgent().getMBeanServer();
        if (server != null) {
            // get all the processor mbeans and sort them accordingly to their index
            String prefix = getContext().getManagementStrategy().getManagementAgent().getIncludeHostName() ? "*/" : "";
            ObjectName query = ObjectName.getInstance(jmxDomain + ":context=" + prefix + getContext().getManagementName() + ",type=processors,*");
            QueryExp queryExp = Query.match(new AttributeValueExp("RouteId"), new StringValueExp(getRouteId()));
            Set<ObjectName> names = server.queryNames(query, queryExp);
            for (ObjectName name : names) {
                server.invoke(name, "reset", null, null);
            }
        }
    }
}
项目:cacheonix-core    文件:RelationServiceExample.java   
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);
   }
}
项目:cacheonix-core    文件:RelationServiceAdaptor.java   
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);
   }
}
项目:windup-rulesets    文件:RelationServiceExample.java   
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);
   }
}
项目:incubator-twill    文件:SessionExpireTestRun.java   
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();

  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;
        }
      }
    }
  } while (stopwatch.elapsedTime(timeoutUnit) < timeout);

  return false;
}
项目:freeVM    文件:QueryTest.java   
/**
 * Test for the method attr(java.lang.String)
 * 
 * @see javax.management.Query#attr(java.lang.String)
 */
public final void testAttrString() throws Exception {
    for (instances[2].point = 0; instances[2].point < 8; instances[2].point++) {
        try {
            Query.attr("NumberSubcl").apply(names[2]);
        } catch (Exception e) {
            fail("Attribute type: "
                + instances[2].getNumberSubcl().getClass().getName(), e);
        }
    }

    assertTrue(Query.match(Query.attr("Attribute1"),
        Query.value("attribute1")).apply(names[0]));
    assertFalse(Query.match(Query.attr("Attribute2"),
        Query.value("attribute1")).apply(names[0]));
}
项目:freeVM    文件:QueryTest.java   
/**
 * Test for the method attr(java.lang.String, java.lang.String)
 * 
 * @see javax.management.Query#attr(java.lang.String, java.lang.String)
 */
public final void testAttrStringString() throws Exception {
    for (instances[2].point = 0; instances[2].point < 8; instances[2].point++) {
        try {
            Query.attr(Hello.class.getName(), "NumberSubcl")
                .apply(names[2]);
        } catch (Exception e) {
            fail("Attribute type: "
                + instances[2].getNumberSubcl().getClass().getName(), e);
        }
    }

    assertTrue(Query.eq(
        Query.attr(Hello.class.getName(), "Number").apply(names[1]),
        Query.value(123)).apply(names[1]));
    assertTrue(Query.eq(
        Query.attr(Hello.class.getName(), "Number1").apply(names[1]),
        Query.value(123123123)).apply(names[1]));
    assertTrue(Query.eq(
        Query.attr(Hello.class.getName(), "Number1").apply(names[1]),
        Query.value(new BigDecimal((double) 123123123))).apply(names[1]));
    assertFalse(Query.eq(
        Query.attr(Hello.class.getName(), "Number1").apply(names[1]),
        Query.value(new BigDecimal((double) 123))).apply(names[1]));
}
项目:freeVM    文件:QueryTest.java   
/**
 * Test for the method in(javax.management.ValueExp,
 * javax.management.ValueExp[])
 * 
 * @see javax.management.Query#in(javax.management.ValueExp,
 *      javax.management.ValueExp[])
 */
public final void testIn() throws Exception {
    String[] attrs = new String[] { "IntNumber1", "IntNumber2",
        "LongNumber1", "LongNumber2", "DoubleNumber1", "DoubleNumber2",
        "FloatNumber1", "FloatNumber2", "Number1", "Number2" };

    ValueExp[] v1 = new ValueExp[] { Query.value(10), Query.value(20),
        Query.value(30) };
    ValueExp[] v2 = new ValueExp[] { Query.value(20), Query.value(30),
        Query.value(40) };

    for (int i = 0; i < attrs.length; i += 2) {
        assertTrue(attrs[i] + " in [10, 20, 30]", Query.in(
            Query.attr(attrs[i]), v1).apply(names[2]));
        assertFalse(attrs[i] + " in [20, 30, 40]", Query.in(
            Query.attr(attrs[i]), v2).apply(names[2]));
    }
}
项目:freeVM    文件:QueryTest.java   
/**
 * Test for the Query.match() method.
 * 
 * @param expr The array, containing reqular expressions.
 * @param invert if true - the match() method should return false.
 * @throws Exception
 */
private void testMatch(String[] expr, boolean invert) throws Exception {
    for (int i = 0; i < expr.length; i++) {
        try {
            if (invert) {
                assertFalse("Query.match(\"" + instances[0].getAttribute1()
                    + "\", \"" + expr[i] + "\")", Query.match(
                    Query.attr("Attribute1"), Query.value(expr[i])).apply(
                    names[0]));
            } else {
                assertTrue("Query.match(\"" + instances[0].getAttribute1()
                    + "\", \"" + expr[i] + "\")", Query.match(
                    Query.attr("Attribute1"), Query.value(expr[i])).apply(
                    names[0]));
            }
        } catch (Throwable ex) {
            fail("Query.match(\"" + instances[0].getAttribute1() + "\", \""
                + expr[i] + "\")", ex);
        }
    }
}
项目:freeVM    文件:QueryTest.java   
/**
 * Test for the method or(javax.management.QueryExp,
 * javax.management.QueryExp)
 * 
 * @see javax.management.Query#or(javax.management.QueryExp,
 *      javax.management.QueryExp)
 */
public final void testOr() throws Exception {
    String[] attrs = new String[] { "IntNumber1", "IntNumber2",
        "LongNumber1", "LongNumber2", "DoubleNumber1", "DoubleNumber2",
        "FloatNumber1", "FloatNumber2", "Number1", "Number2" };

    for (int i = 0; i < attrs.length; i += 2) {
        assertTrue(Query.or(
            Query.eq(Query.attr(attrs[i]), Query.attr(attrs[i])),
            Query.eq(Query.attr(attrs[i]), Query.attr(attrs[i]))).apply(
            names[2]));
        assertTrue(Query.or(
            Query.lt(Query.attr(attrs[i]), Query.attr(attrs[i + 1])),
            Query.lt(Query.attr(attrs[i]), Query.attr(attrs[i + 1])))
            .apply(names[2]));
        assertFalse(Query.or(
            Query.eq(Query.attr(attrs[i]), Query.attr(attrs[i + 1])),
            Query.eq(Query.attr(attrs[i]), Query.attr(attrs[i + 1])))
            .apply(names[2]));
    }
}
项目:freeVM    文件:QueryTest.java   
/**
 * Test for the method plus(javax.management.ValueExp,
 * javax.management.ValueExp)
 * 
 * @see javax.management.Query#plus(javax.management.ValueExp,
 *      javax.management.ValueExp)
 */
public final void testPlus() throws Exception {
    String[] attrs = new String[] { "IntNumber1", "IntNumber2",
        "LongNumber1", "LongNumber2", "DoubleNumber1", "DoubleNumber2",
        "FloatNumber1", "FloatNumber2", "Number1", "Number2" };

    for (int i = 0; i < attrs.length; i += 2) {
        ValueExp v1 = Query.attr(attrs[i]).apply(names[2]);
        ValueExp v2 = Query.attr(attrs[i + 1]).apply(names[2]);
        ValueExp res = Query.plus(v1, v2).apply(names[2]);
        assertTrue(v1 + " + " + v2 + " = " + res, Query.eq(
            Query.plus(Query.attr(attrs[i + 1]), Query.attr(attrs[i])),
            Query.value(110)).apply(names[2]));
        assertFalse(v1 + " + " + v2 + " = " + res, Query.eq(
            Query.plus(Query.attr(attrs[i + 1]), Query.attr(attrs[i])),
            Query.value(111)).apply(names[2]));
    }
}
项目:freeVM    文件:QueryTest.java   
/**
 * Test for the method times(javax.management.ValueExp,
 * javax.management.ValueExp)
 * 
 * @see javax.management.Query#times(javax.management.ValueExp,
 *      javax.management.ValueExp)
 */
public final void testTimes() throws Exception {
    String[] attrs = new String[] { "IntNumber1", "IntNumber2",
        "LongNumber1", "LongNumber2", "DoubleNumber1", "DoubleNumber2",
        "FloatNumber1", "FloatNumber2", "Number1", "Number2" };

    for (int i = 0; i < attrs.length; i += 2) {
        ValueExp v1 = Query.attr(attrs[i]).apply(names[2]);
        ValueExp v2 = Query.attr(attrs[i + 1]).apply(names[2]);
        ValueExp res = Query.times(v1, v2).apply(names[2]);
        assertTrue(v1 + " * " + v2 + " = " + res, Query.eq(
            Query.times(Query.attr(attrs[i + 1]), Query.attr(attrs[i])),
            Query.value(1000)).apply(names[2]));
        assertFalse(v1 + " * " + v2 + " = " + res, Query.eq(
            Query.times(Query.attr(attrs[i + 1]), Query.attr(attrs[i])),
            Query.value(10001)).apply(names[2]));
    }
}
项目:monarch    文件:LauncherLifecycleCommandsDUnitTest.java   
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)));

    MBeanServerConnection connection = connector.getMBeanServerConnection();

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

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

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

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

    // final ObjectName objectName = ObjectName.getInstance("GemFire:type=Member,Name=" +
    // memberName);
    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);
  }
}
项目:monarch    文件:MBeanServerWrapper.java   
@Override
public Set<ObjectInstance> queryMBeans(ObjectName name, QueryExp query) {
  // We need to filter out the AccessControlMXBean so that the clients wouldn't see it
  if (query != null)
    return mbs.queryMBeans(name, Query.and(query, notAccessControlMBean));
  else
    return mbs.queryMBeans(name, notAccessControlMBean);
}
项目:monarch    文件:MBeanServerWrapper.java   
@Override
public Set<ObjectName> queryNames(ObjectName name, QueryExp query) {
  if (query != null)
    return mbs.queryNames(name, Query.and(query, notAccessControlMBean));
  else
    return mbs.queryNames(name, notAccessControlMBean);
}
项目:monarch    文件:LauncherLifecycleCommands.java   
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;
}
项目:monarch    文件:LocalProcessController.java   
/**
 * 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;
}
项目:monarch    文件:LocalProcessController.java   
/**
 * 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;
}
项目:monarch    文件:MBeanProcessController.java   
/**
 * 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;
}
项目:monarch    文件:MBeanProcessController.java   
/**
 * 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;
}
项目:jdk8u-jdk    文件:QueryMatchTest.java   
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;
}
项目:openjdk-jdk10    文件:QueryMatchTest.java   
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;
}
项目:openjdk9    文件:QueryMatchTest.java   
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;
}
项目:gemfirexd-oss    文件:AbstractCommandsController.java   
/**
 * 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);
  }
}
项目:gemfirexd-oss    文件:LauncherLifecycleCommands.java   
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;
}
项目:gemfirexd-oss    文件:LocalProcessController.java   
/**
 * 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;
}
项目:gemfirexd-oss    文件:LocalProcessController.java   
/**
 * 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;
}
项目:gemfirexd-oss    文件:MBeanProcessController.java   
/**
 * 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;
}
项目:gemfirexd-oss    文件:MBeanProcessController.java   
/**
 * 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;
}
项目:gemfirexd-oss    文件:QueryParameterSourceJUnitTest.java   
@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());
}
项目:gemfirexd-oss    文件:QueryParameterSourceJUnitTest.java   
@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());
}
项目:gemfirexd-oss    文件:LauncherLifecycleCommandsDUnitTest.java   
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);
  }
}
项目:twill    文件:SessionExpireTestRun.java   
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;
}
项目:jdk8u_jdk    文件:QueryMatchTest.java   
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;
}
项目:lookaside_java-1.8.0-openjdk    文件:QueryMatchTest.java   
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;
}
项目:gemfirexd-oss    文件:AbstractCommandsController.java   
/**
 * 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);
  }
}