Example usage for javax.management MBeanInfo getAttributes

List of usage examples for javax.management MBeanInfo getAttributes

Introduction

In this page you can find the example usage for javax.management MBeanInfo getAttributes.

Prototype

public MBeanAttributeInfo[] getAttributes() 

Source Link

Document

Returns the list of attributes exposed for management.

Usage

From source file:com.tesora.dve.tools.DVEConfigCLI.java

public void cmd_jmx_mbean(Scanner scanner) throws PEException {
    checkJMXConnected();//from  w w  w .  j  a  v a2  s  . c  o m
    checkJMXDomain();

    final String mbean = scan(scanner, "mbean");

    final ObjectName on = jmxConnector.makeObjectName(jmxDomain, mbean);

    final MBeanInfo info = jmxConnector.getBeanInfo(on);

    jmxMBean = on;
    jmxMBeanInfo = info;

    printlnDots("MBean '" + jmxMBean + "' selected");

    println("Attributes = " + (info.getAttributes() == null ? "N/A" : info.getAttributes().length));
    println("Operations = " + (info.getOperations() == null ? "N/A" : info.getOperations().length));
}

From source file:de.acosix.alfresco.mtsupport.repo.sync.TenantAwareChainingUserRegistrySynchronizer.java

protected void logPluginConfig(final String id) {
    try {//from  w w  w.j a  v a 2  s .  co  m
        final StringBuilder nameBuff = new StringBuilder(200)
                .append("Alfresco:Type=Configuration,Category=Authentication,id1=managed,id2=")
                .append(URLDecoder.decode(id, "UTF-8"));
        final ObjectName name = new ObjectName(nameBuff.toString());
        if (this.mbeanServer != null && this.mbeanServer.isRegistered(name)) {
            final MBeanInfo info = this.mbeanServer.getMBeanInfo(name);
            final MBeanAttributeInfo[] attributes = info.getAttributes();
            LOGGER.debug("{} attributes:", id);
            for (final MBeanAttributeInfo attribute : attributes) {
                final Object value = this.mbeanServer.getAttribute(name, attribute.getName());
                LOGGER.debug("{} = {}", attribute.getName(), value);
            }
        }
    } catch (final MalformedObjectNameException | InstanceNotFoundException | IntrospectionException
            | AttributeNotFoundException | ReflectionException | MBeanException | IOException e) {
        LOGGER.warn("Exception during logging", e);
    }
}

From source file:org.opennms.tools.jmxconfiggenerator.jmxconfig.JmxDatacollectionConfiggenerator.java

public JmxDatacollectionConfig generateJmxConfigModel(MBeanServerConnection mBeanServerConnection,
        String serviceName, Boolean runStandardVmBeans, Boolean runWritableMBeans) {

    logger.debug("Startup values: \n serviceName: " + serviceName + "\n runStandardVmBeans: "
            + runStandardVmBeans + "\n runWritableMBeans: " + runWritableMBeans);
    JmxDatacollectionConfig xmlJmxDatacollectionConfig = xmlObjectFactory.createJmxDatacollectionConfig();
    JmxCollection xmlJmxCollection = xmlObjectFactory.createJmxCollection();

    xmlJmxCollection.setName("JSR160-" + serviceName);
    xmlJmxCollection.setRrd(rrd);//from w  w w.  j  av a  2s  .  c  o  m
    xmlJmxDatacollectionConfig.getJmxCollection().add(xmlJmxCollection);
    xmlJmxCollection.setMbeans(xmlObjectFactory.createMbeans());

    if (runStandardVmBeans) {
        ignores.clear();
    } else {
        ignores.addAll(standardVmBeans);
    }

    try {
        for (String domainName : mBeanServerConnection.getDomains()) {

            // just domains that are relevant for the service
            if (!ignores.contains(domainName)) {
                logger.debug("domain: " + domainName);

                // for all mBeans of the actual domain
                for (ObjectInstance jmxObjectInstance : mBeanServerConnection
                        .queryMBeans(new ObjectName(domainName + ":*"), null)) {
                    Mbean xmlMbean = xmlObjectFactory.createMbean();
                    xmlMbean.setObjectname(jmxObjectInstance.getObjectName().toString());
                    String typeAndOthers = StringUtils
                            .substringAfterLast(jmxObjectInstance.getObjectName().getCanonicalName(), "=");
                    xmlMbean.setName(domainName + "." + typeAndOthers);

                    logger.debug("\t" + jmxObjectInstance.getObjectName());

                    MBeanInfo jmxMbeanInfo;
                    try {
                        jmxMbeanInfo = mBeanServerConnection.getMBeanInfo(jmxObjectInstance.getObjectName());
                    } catch (InstanceNotFoundException e) {
                        logger.error("InstanceNotFoundException skipping MBean '{}' message: '{}'",
                                jmxObjectInstance.getObjectName(), e.getMessage());
                        continue;
                    } catch (IntrospectionException e) {
                        logger.error("IntrospectionException skipping MBean '{}' message: '{}'",
                                jmxObjectInstance.getObjectName(), e.getMessage());
                        continue;
                    } catch (ReflectionException e) {
                        logger.error("ReflectionException skipping MBean '{}' message: '{}'",
                                jmxObjectInstance.getObjectName(), e.getMessage());
                        continue;
                    } catch (Throwable e) {
                        logger.error(
                                "problem during remote call to get MBeanInfo for '{}' skipping this MBean. Message '{}'",
                                jmxObjectInstance.getObjectName(), e.getMessage());
                        continue;
                    }

                    logger.debug("--- Attributes for " + jmxObjectInstance.getObjectName());

                    for (MBeanAttributeInfo jmxBeanAttributeInfo : jmxMbeanInfo.getAttributes()) {

                        // process just readable mbeans
                        if (jmxBeanAttributeInfo.isReadable()) {
                            // precess writable mbeans if run writable mbeans is set
                            if (!jmxBeanAttributeInfo.isWritable() || runWritableMBeans) {

                                logger.debug("Check mBean: '{}', attribute: '{}'",
                                        jmxObjectInstance.getObjectName().toString(),
                                        jmxBeanAttributeInfo.getName());
                                logger.debug("isWritable: '{}', type: '{}'", jmxBeanAttributeInfo.isWritable(),
                                        jmxBeanAttributeInfo.getType());

                                // check for CompositeData
                                if ("javax.management.openmbean.CompositeData"
                                        .equals(jmxBeanAttributeInfo.getType())) {
                                    logger.error("actual mBean: '{}'", jmxObjectInstance.getObjectName());
                                    CompAttrib compAttrib = createCompAttrib(mBeanServerConnection,
                                            jmxObjectInstance, jmxBeanAttributeInfo);
                                    if (compAttrib != null) {
                                        logger.debug("xmlMbean got CompAttrib");
                                        xmlMbean.getCompAttrib().add(compAttrib);
                                    }
                                }

                                if (numbers.contains(jmxBeanAttributeInfo.getType())) {
                                    Attrib xmlJmxAttribute = createAttr(jmxBeanAttributeInfo);
                                    logger.debug("Added MBean: '{}' Added attribute: '{}'",
                                            xmlMbean.getObjectname(),
                                            xmlJmxAttribute.getName() + " as " + xmlJmxAttribute.getAlias());
                                    xmlMbean.getAttrib().add(xmlJmxAttribute);
                                }
                            }
                        }
                    }

                    if (xmlMbean.getAttrib().size() > 0 || xmlMbean.getCompAttrib().size() > 0) {
                        xmlJmxCollection.getMbeans().getMbean().add(xmlMbean);
                    } else {
                        logger.debug("mbean: " + xmlMbean.getName() + " has no relavant attributes.");
                    }
                }
            } else {
                logger.debug("ignored: " + domainName);
            }
        }

    } catch (MalformedObjectNameException e) {
        logger.error("MalformedObjectNameException '{}'", e.getMessage());
    } catch (IOException e) {
        logger.error("IOException '{}'", e.getMessage());
    }

    return xmlJmxDatacollectionConfig;
}

From source file:org.opennms.jmxconfiggenerator.jmxconfig.JmxDatacollectionConfiggenerator.java

public JmxDatacollectionConfig generateJmxConfigModel(MBeanServerConnection mBeanServerConnection,
        String serviceName, Boolean runStandardVmBeans, Boolean runWritableMBeans,
        Map<String, String> dictionary) {

    logger.debug("Startup values: \n serviceName: " + serviceName + "\n runStandardVmBeans: "
            + runStandardVmBeans + "\n runWritableMBeans: " + runWritableMBeans + "\n dictionary" + dictionary);
    nameCutter.setDictionary(dictionary);
    JmxDatacollectionConfig xmlJmxDatacollectionConfig = xmlObjectFactory.createJmxDatacollectionConfig();
    JmxCollection xmlJmxCollection = xmlObjectFactory.createJmxCollection();

    xmlJmxCollection.setName("JSR160-" + serviceName);
    xmlJmxCollection.setRrd(rrd);/*from  w ww  . j  ava2 s  .  co m*/
    xmlJmxDatacollectionConfig.getJmxCollection().add(xmlJmxCollection);
    xmlJmxCollection.setMbeans(xmlObjectFactory.createMbeans());

    if (runStandardVmBeans) {
        ignores.clear();
    } else {
        ignores.addAll(standardVmBeans);
    }

    try {
        for (String domainName : mBeanServerConnection.getDomains()) {

            // just domains that are relevant for the service
            if (!ignores.contains(domainName)) {
                logger.debug("domain: " + domainName);

                // for all mBeans of the actual domain
                for (ObjectInstance jmxObjectInstance : mBeanServerConnection
                        .queryMBeans(new ObjectName(domainName + ":*"), null)) {
                    Mbean xmlMbean = xmlObjectFactory.createMbean();
                    xmlMbean.setObjectname(jmxObjectInstance.getObjectName().toString());
                    String typeAndOthers = StringUtils
                            .substringAfterLast(jmxObjectInstance.getObjectName().getCanonicalName(), "=");
                    xmlMbean.setName(domainName + "." + typeAndOthers);

                    logger.debug("\t" + jmxObjectInstance.getObjectName());

                    MBeanInfo jmxMbeanInfo;
                    try {
                        jmxMbeanInfo = mBeanServerConnection.getMBeanInfo(jmxObjectInstance.getObjectName());
                    } catch (InstanceNotFoundException e) {
                        logger.error("InstanceNotFoundException skipping MBean '{}' message: '{}'",
                                jmxObjectInstance.getObjectName(), e.getMessage());
                        continue;
                    } catch (IntrospectionException e) {
                        logger.error("IntrospectionException skipping MBean '{}' message: '{}'",
                                jmxObjectInstance.getObjectName(), e.getMessage());
                        continue;
                    } catch (ReflectionException e) {
                        logger.error("ReflectionException skipping MBean '{}' message: '{}'",
                                jmxObjectInstance.getObjectName(), e.getMessage());
                        continue;
                    } catch (Throwable e) {
                        logger.error(
                                "problem during remote call to get MBeanInfo for '{}' skipping this MBean. Message '{}'",
                                jmxObjectInstance.getObjectName(), e.getMessage());
                        continue;
                    }

                    logger.debug("--- Attributes for " + jmxObjectInstance.getObjectName());

                    for (MBeanAttributeInfo jmxBeanAttributeInfo : jmxMbeanInfo.getAttributes()) {

                        // process just readable mbeans
                        if (jmxBeanAttributeInfo.isReadable()) {
                            // precess writable mbeans if run writable mbeans is set
                            if (!jmxBeanAttributeInfo.isWritable() || runWritableMBeans) {

                                logger.debug("Check mBean: '{}', attribute: '{}'",
                                        jmxObjectInstance.getObjectName().toString(),
                                        jmxBeanAttributeInfo.getName());
                                logger.debug("isWritable: '{}', type: '{}'", jmxBeanAttributeInfo.isWritable(),
                                        jmxBeanAttributeInfo.getType());

                                // check for CompositeData
                                if ("javax.management.openmbean.CompositeData"
                                        .equals(jmxBeanAttributeInfo.getType())) {
                                    logger.error("actual mBean: '{}'", jmxObjectInstance.getObjectName());
                                    CompAttrib compAttrib = createCompAttrib(mBeanServerConnection,
                                            jmxObjectInstance, jmxBeanAttributeInfo);
                                    if (compAttrib != null) {
                                        logger.debug("xmlMbean got CompAttrib");
                                        xmlMbean.getCompAttrib().add(compAttrib);
                                    }
                                }

                                if (numbers.contains(jmxBeanAttributeInfo.getType())) {
                                    Attrib xmlJmxAttribute = createAttr(jmxBeanAttributeInfo);
                                    logger.debug("Added MBean: '{}' Added attribute: '{}'",
                                            xmlMbean.getObjectname(),
                                            xmlJmxAttribute.getName() + " as " + xmlJmxAttribute.getAlias());
                                    xmlMbean.getAttrib().add(xmlJmxAttribute);
                                }
                            }
                        }
                    }

                    if (xmlMbean.getAttrib().size() > 0 || xmlMbean.getCompAttrib().size() > 0) {
                        xmlJmxCollection.getMbeans().getMbean().add(xmlMbean);
                    } else {
                        logger.debug("mbean: " + xmlMbean.getName() + " has no relavant attributes.");
                    }
                }
            } else {
                logger.debug("ignored: " + domainName);
            }
        }

    } catch (MalformedObjectNameException e) {
        logger.error("MalformedObjectNameException '{}'", e.getMessage());
    } catch (IOException e) {
        logger.error("IOException '{}'", e.getMessage());
    }

    return xmlJmxDatacollectionConfig;
}

From source file:org.opennms.features.jmxconfiggenerator.jmxconfig.JmxDatacollectionConfiggenerator.java

public JmxDatacollectionConfig generateJmxConfigModel(MBeanServerConnection mBeanServerConnection,
        String serviceName, Boolean runStandardVmBeans, Boolean runWritableMBeans,
        Map<String, String> dictionary) {

    logger.debug("Startup values: \n serviceName: " + serviceName + "\n runStandardVmBeans: "
            + runStandardVmBeans + "\n runWritableMBeans: " + runWritableMBeans + "\n dictionary" + dictionary);
    nameCutter.setDictionary(dictionary);
    JmxDatacollectionConfig xmlJmxDatacollectionConfig = xmlObjectFactory.createJmxDatacollectionConfig();
    JmxCollection xmlJmxCollection = xmlObjectFactory.createJmxCollection();

    xmlJmxCollection.setName("JSR160-" + serviceName);
    xmlJmxCollection.setRrd(rrd);/*w w  w. j  av  a 2s . co m*/
    xmlJmxDatacollectionConfig.getJmxCollection().add(xmlJmxCollection);
    xmlJmxCollection.setMbeans(xmlObjectFactory.createMbeans());

    if (runStandardVmBeans) {
        ignores.clear();
    } else {
        ignores.addAll(standardVmBeans);
    }

    try {
        String[] domains = mBeanServerConnection.getDomains();
        logger.info("Found " + domains.length + " domains");
        logger.info("domains: " + Arrays.toString(domains));
        for (String domainName : domains) {

            // just domains that are relevant for the service
            if (!ignores.contains(domainName)) {
                logger.info("domain: " + domainName);

                // for all mBeans of the actual domain
                for (ObjectInstance jmxObjectInstance : mBeanServerConnection
                        .queryMBeans(new ObjectName(domainName + ":*"), null)) {
                    Mbean xmlMbean = xmlObjectFactory.createMbean();
                    xmlMbean.setObjectname(jmxObjectInstance.getObjectName().toString());
                    String typeAndOthers = StringUtils
                            .substringAfterLast(jmxObjectInstance.getObjectName().getCanonicalName(), "=");
                    xmlMbean.setName(domainName + "." + typeAndOthers);

                    logger.debug("\t" + jmxObjectInstance.getObjectName());

                    MBeanInfo jmxMbeanInfo;
                    try {
                        jmxMbeanInfo = mBeanServerConnection.getMBeanInfo(jmxObjectInstance.getObjectName());
                    } catch (InstanceNotFoundException e) {
                        logger.error("InstanceNotFoundException skipping MBean '{}' message: '{}'",
                                jmxObjectInstance.getObjectName(), e.getMessage());
                        continue;
                    } catch (IntrospectionException e) {
                        logger.error("IntrospectionException skipping MBean '{}' message: '{}'",
                                jmxObjectInstance.getObjectName(), e.getMessage());
                        continue;
                    } catch (ReflectionException e) {
                        logger.error("ReflectionException skipping MBean '{}' message: '{}'",
                                jmxObjectInstance.getObjectName(), e.getMessage());
                        continue;
                    } catch (Throwable e) {
                        logger.error(
                                "problem during remote call to get MBeanInfo for '{}' skipping this MBean. Message '{}'",
                                jmxObjectInstance.getObjectName(), e.getMessage());
                        continue;
                    }

                    logger.debug("--- Attributes for " + jmxObjectInstance.getObjectName());

                    for (MBeanAttributeInfo jmxBeanAttributeInfo : jmxMbeanInfo.getAttributes()) {

                        // process just readable mbeans
                        if (jmxBeanAttributeInfo.isReadable()) {
                            // precess writable mbeans if run writable
                            // mbeans is set
                            if (!jmxBeanAttributeInfo.isWritable() || runWritableMBeans) {

                                logger.debug("Check mBean: '{}', attribute: '{}'",
                                        jmxObjectInstance.getObjectName().toString(),
                                        jmxBeanAttributeInfo.getName());
                                logger.debug("isWritable: '{}', type: '{}'", jmxBeanAttributeInfo.isWritable(),
                                        jmxBeanAttributeInfo.getType());

                                // check for CompositeData
                                if ("javax.management.openmbean.CompositeData"
                                        .equals(jmxBeanAttributeInfo.getType())) {
                                    logger.error("actual mBean: '{}'", jmxObjectInstance.getObjectName());
                                    CompAttrib compAttrib = createCompAttrib(mBeanServerConnection,
                                            jmxObjectInstance, jmxBeanAttributeInfo);
                                    if (compAttrib != null) {
                                        logger.debug("xmlMbean got CompAttrib");
                                        xmlMbean.getCompAttrib().add(compAttrib);
                                    }
                                }

                                if (numbers.contains(jmxBeanAttributeInfo.getType())) {
                                    Attrib xmlJmxAttribute = createAttr(jmxBeanAttributeInfo);
                                    logger.debug("Added MBean: '{}' Added attribute: '{}'",
                                            xmlMbean.getObjectname(),
                                            xmlJmxAttribute.getName() + " as " + xmlJmxAttribute.getAlias());
                                    xmlMbean.getAttrib().add(xmlJmxAttribute);
                                }
                            }
                        }
                    }

                    if (xmlMbean.getAttrib().size() > 0 || xmlMbean.getCompAttrib().size() > 0) {
                        xmlJmxCollection.getMbeans().getMbean().add(xmlMbean);
                    } else {
                        logger.debug("mbean: " + xmlMbean.getName() + " has no relavant attributes.");
                    }
                }
            } else {
                logger.debug("ignored: " + domainName);
            }
        }

    } catch (MalformedObjectNameException e) {
        logger.error("MalformedObjectNameException '{}'", e.getMessage());
    } catch (IOException e) {
        logger.error("IOException '{}'", e.getMessage());
    }
    logger.debug("finish collection!");
    return xmlJmxDatacollectionConfig;
}

From source file:org.alfresco.repo.security.sync.TenantChainingUserRegistrySynchronizer.java

private void synchronizeInternal(boolean forceUpdate, boolean isFullSync, final boolean splitTxns) {
    TenantChainingUserRegistrySynchronizer.logger
            .debug("Running a sync for domain: " + SEIPTenantIntegration.getTenantId());
    if (TenantChainingUserRegistrySynchronizer.logger.isDebugEnabled()) {

        if (forceUpdate) {
            TenantChainingUserRegistrySynchronizer.logger.debug("Running a full sync.");
        } else {/*  www .ja v a 2  s.c  o m*/
            TenantChainingUserRegistrySynchronizer.logger.debug("Running a differential sync.");
        }
        if (allowDeletions) {
            TenantChainingUserRegistrySynchronizer.logger.debug("deletions are allowed");
        } else {
            TenantChainingUserRegistrySynchronizer.logger.debug("deletions are not allowed");
        }
        // Don't proceed with the sync if the repository is read only
        if (this.transactionService.isReadOnly()) {
            TenantChainingUserRegistrySynchronizer.logger
                    .warn("Unable to proceed with user registry synchronization. Repository is read only.");
            return;
        }
    }

    // Don't proceed with the sync if the repository is read only
    if (this.transactionService.isReadOnly()) {
        TenantChainingUserRegistrySynchronizer.logger
                .warn("Unable to proceed with user registry synchronization. Repository is read only.");
        return;
    }

    // Create a background executor that will refresh our lock. This means
    // we can request a lock with a relatively
    // small persistence time and not worry about it lasting after server
    // restarts. Note we use an independent
    // executor because this is a compound operation that spans accross
    // multiple batch processors.
    String lockToken = null;
    TraceableThreadFactory threadFactory = new TraceableThreadFactory();
    threadFactory.setNamePrefix("TenantChainingUserRegistrySynchronizer lock refresh");
    threadFactory.setThreadDaemon(true);
    ScheduledExecutorService lockRefresher = new ScheduledThreadPoolExecutor(1, threadFactory);

    // Let's ensure all exceptions get logged
    try {
        // First, try to obtain a lock to ensure we are the only node trying
        // to run this job
        try {
            if (splitTxns) {
                // If this is an automated sync on startup or scheduled
                // sync, don't even wait around for the lock.
                // Assume the sync will be completed on another node.
                lockToken = this.transactionService.getRetryingTransactionHelper()
                        .doInTransaction(new RetryingTransactionCallback<String>() {
                            public String execute() throws Throwable {
                                return TenantChainingUserRegistrySynchronizer.this.jobLockService.getLock(
                                        TenantChainingUserRegistrySynchronizer.LOCK_QNAME,
                                        TenantChainingUserRegistrySynchronizer.LOCK_TTL, 0, 1);
                            }
                        }, false, splitTxns);
            } else {
                // If this is a login-triggered sync, give it a few retries
                // before giving up
                lockToken = this.jobLockService.getLock(TenantChainingUserRegistrySynchronizer.LOCK_QNAME,
                        TenantChainingUserRegistrySynchronizer.LOCK_TTL, 3000, 10);
            }
        } catch (LockAcquisitionException e) {
            // Don't proceed with the sync if it is running on another node
            TenantChainingUserRegistrySynchronizer.logger.warn(
                    "User registry synchronization already running in another thread. Synchronize aborted");
            return;
        }

        // Schedule the lock refresh to run at regular intervals
        final String token = lockToken;
        lockRefresher.scheduleAtFixedRate(new Runnable() {
            public void run() {
                TenantChainingUserRegistrySynchronizer.this.transactionService.getRetryingTransactionHelper()
                        .doInTransaction(new RetryingTransactionCallback<Object>() {
                            public Object execute() throws Throwable {
                                TenantChainingUserRegistrySynchronizer.this.jobLockService.refreshLock(token,
                                        TenantChainingUserRegistrySynchronizer.LOCK_QNAME,
                                        TenantChainingUserRegistrySynchronizer.LOCK_TTL);
                                return null;
                            }
                        }, false, splitTxns);
            }
        }, TenantChainingUserRegistrySynchronizer.LOCK_TTL / 2,
                TenantChainingUserRegistrySynchronizer.LOCK_TTL / 2, TimeUnit.MILLISECONDS);

        Set<String> visitedZoneIds = new TreeSet<String>();
        Collection<String> instanceIds = this.applicationContextManager.getInstanceIds();

        // Work out the set of all zone IDs in the authentication chain so
        // that we can decide which users / groups
        // need 're-zoning'
        Set<String> allZoneIds = new TreeSet<String>();
        for (String id : instanceIds) {
            allZoneIds.add(AuthorityService.ZONE_AUTH_EXT_PREFIX + id);
        }
        for (String id : instanceIds) {
            ApplicationContext context = this.applicationContextManager.getApplicationContext(id);
            try {
                UserRegistry plugin = (UserRegistry) context.getBean(this.sourceBeanName);
                if (!(plugin instanceof ActivateableBean) || ((ActivateableBean) plugin).isActive()) {
                    if (TenantChainingUserRegistrySynchronizer.logger.isDebugEnabled()) {
                        mbeanServer = (MBeanServerConnection) getApplicationContext()
                                .getBean("alfrescoMBeanServer");
                        try {
                            StringBuilder nameBuff = new StringBuilder(200).append(
                                    "Alfresco:Type=Configuration,Category=Authentication,id1=managed,id2=")
                                    .append(URLDecoder.decode(id, "UTF-8"));
                            ObjectName name = new ObjectName(nameBuff.toString());
                            if (mbeanServer != null && mbeanServer.isRegistered(name)) {
                                MBeanInfo info = mbeanServer.getMBeanInfo(name);
                                MBeanAttributeInfo[] attributes = info.getAttributes();
                                TenantChainingUserRegistrySynchronizer.logger.debug(id + " attributes:");
                                for (MBeanAttributeInfo attribute : attributes) {
                                    Object value = mbeanServer.getAttribute(name, attribute.getName());
                                    TenantChainingUserRegistrySynchronizer.logger
                                            .debug(attribute.getName() + " = " + value);
                                }
                            }
                        } catch (UnsupportedEncodingException e) {
                            if (TenantChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                                TenantChainingUserRegistrySynchronizer.logger.warn("Exception during logging",
                                        e);
                            }
                        } catch (MalformedObjectNameException e) {
                            if (TenantChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                                TenantChainingUserRegistrySynchronizer.logger.warn("Exception during logging",
                                        e);
                            }
                        } catch (InstanceNotFoundException e) {
                            if (TenantChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                                TenantChainingUserRegistrySynchronizer.logger.warn("Exception during logging",
                                        e);
                            }
                        } catch (IntrospectionException e) {
                            if (TenantChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                                TenantChainingUserRegistrySynchronizer.logger.warn("Exception during logging",
                                        e);
                            }
                        } catch (AttributeNotFoundException e) {
                            if (TenantChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                                TenantChainingUserRegistrySynchronizer.logger.warn("Exception during logging",
                                        e);
                            }
                        } catch (ReflectionException e) {
                            if (TenantChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                                TenantChainingUserRegistrySynchronizer.logger.warn("Exception during logging",
                                        e);
                            }
                        } catch (MBeanException e) {
                            if (TenantChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                                TenantChainingUserRegistrySynchronizer.logger.warn("Exception during logging",
                                        e);
                            }
                        } catch (IOException e) {
                            if (TenantChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                                TenantChainingUserRegistrySynchronizer.logger.warn("Exception during logging",
                                        e);
                            }
                        }

                    }
                    if (TenantChainingUserRegistrySynchronizer.logger.isInfoEnabled()) {
                        TenantChainingUserRegistrySynchronizer.logger
                                .info("Synchronizing users and groups with user registry '" + id + "'");
                    }
                    if (isFullSync && TenantChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                        TenantChainingUserRegistrySynchronizer.logger
                                .warn("Full synchronization with user registry '" + id + "'");
                        if (allowDeletions) {
                            TenantChainingUserRegistrySynchronizer.logger.warn(
                                    "Some users and groups previously created by synchronization with this user registry may be removed.");
                        } else {
                            TenantChainingUserRegistrySynchronizer.logger.warn(
                                    "Deletions are disabled. Users and groups removed from this registry will be logged only and will remain in the repository. Users previously found in a different registry will be moved in the repository rather than recreated.");
                        }
                    }
                    // Work out whether we should do the work in a separate
                    // transaction (it's most performant if we
                    // bunch it into small transactions, but if we are doing
                    // a sync on login, it has to be the same
                    // transaction)
                    boolean requiresNew = splitTxns || AlfrescoTransactionSupport
                            .getTransactionReadState() == TxnReadState.TXN_READ_ONLY;

                    syncWithPlugin(id, plugin, forceUpdate, isFullSync, requiresNew, visitedZoneIds,
                            allZoneIds);
                }
            } catch (NoSuchBeanDefinitionException e) {
                // Ignore and continue
            }

        }
    } catch (RuntimeException e) {
        TenantChainingUserRegistrySynchronizer.logger.error("Synchronization aborted due to error", e);
        throw e;
    }
    // Release the lock if necessary
    finally {
        if (lockToken != null) {
            // Cancel the lock refresher
            // Because we may hit a perfect storm when trying to interrupt
            // workers in their unsynchronized getTask()
            // method we can't wait indefinitely and may have to retry the
            // shutdown
            int trys = 0;
            do {
                lockRefresher.shutdown();
                try {
                    lockRefresher.awaitTermination(TenantChainingUserRegistrySynchronizer.LOCK_TTL,
                            TimeUnit.MILLISECONDS);
                } catch (InterruptedException e) {
                }
            } while (!lockRefresher.isTerminated() && trys++ < 3);
            if (!lockRefresher.isTerminated()) {
                lockRefresher.shutdownNow();
                TenantChainingUserRegistrySynchronizer.logger.error("Failed to shut down lock refresher");
            }

            final String token = lockToken;
            this.transactionService.getRetryingTransactionHelper()
                    .doInTransaction(new RetryingTransactionCallback<Object>() {
                        public Object execute() throws Throwable {
                            TenantChainingUserRegistrySynchronizer.this.jobLockService.releaseLock(token,
                                    TenantChainingUserRegistrySynchronizer.LOCK_QNAME);
                            return null;
                        }
                    }, false, splitTxns);
        }
    }
}

From source file:org.alfresco.repo.security.sync.ChainingUserRegistrySynchronizer.java

private void synchronizeInternal(boolean forceUpdate, boolean isFullSync, final boolean splitTxns) {
    if (ChainingUserRegistrySynchronizer.logger.isDebugEnabled()) {

        if (forceUpdate) {
            ChainingUserRegistrySynchronizer.logger.debug("Running a full sync.");
        } else {/*  w ww . j  av a  2  s . co m*/
            ChainingUserRegistrySynchronizer.logger.debug("Running a differential sync.");
        }
        if (allowDeletions) {
            ChainingUserRegistrySynchronizer.logger.debug("deletions are allowed");
        } else {
            ChainingUserRegistrySynchronizer.logger.debug("deletions are not allowed");
        }
        // Don't proceed with the sync if the repository is read only
        if (this.transactionService.isReadOnly()) {
            ChainingUserRegistrySynchronizer.logger
                    .warn("Unable to proceed with user registry synchronization. Repository is read only.");
            return;
        }
    }

    // Don't proceed with the sync if the repository is read only
    if (this.transactionService.isReadOnly()) {
        ChainingUserRegistrySynchronizer.logger
                .warn("Unable to proceed with user registry synchronization. Repository is read only.");
        return;
    }

    // Create a background executor that will refresh our lock. This means we can request a lock with a relatively
    // small persistence time and not worry about it lasting after server restarts. Note we use an independent
    // executor because this is a compound operation that spans accross multiple batch processors.
    String lockToken = null;
    TraceableThreadFactory threadFactory = new TraceableThreadFactory();
    threadFactory.setNamePrefix("ChainingUserRegistrySynchronizer lock refresh");
    threadFactory.setThreadDaemon(true);
    ScheduledExecutorService lockRefresher = new ScheduledThreadPoolExecutor(1, threadFactory);

    // Let's ensure all exceptions get logged
    try {
        // First, try to obtain a lock to ensure we are the only node trying to run this job
        try {
            if (splitTxns) {
                // If this is an automated sync on startup or scheduled sync, don't even wait around for the lock.
                // Assume the sync will be completed on another node.
                lockToken = this.transactionService.getRetryingTransactionHelper()
                        .doInTransaction(new RetryingTransactionCallback<String>() {
                            public String execute() throws Throwable {
                                return ChainingUserRegistrySynchronizer.this.jobLockService.getLock(
                                        ChainingUserRegistrySynchronizer.LOCK_QNAME,
                                        ChainingUserRegistrySynchronizer.LOCK_TTL, 0, 1);
                            }
                        }, false, splitTxns);
            } else {
                // If this is a login-triggered sync, give it a few retries before giving up
                lockToken = this.jobLockService.getLock(ChainingUserRegistrySynchronizer.LOCK_QNAME,
                        ChainingUserRegistrySynchronizer.LOCK_TTL, 3000, 10);
            }
        } catch (LockAcquisitionException e) {
            // Don't proceed with the sync if it is running on another node
            ChainingUserRegistrySynchronizer.logger.warn(
                    "User registry synchronization already running in another thread. Synchronize aborted");
            return;
        }

        // Schedule the lock refresh to run at regular intervals
        final String token = lockToken;
        lockRefresher.scheduleAtFixedRate(new Runnable() {
            public void run() {
                ChainingUserRegistrySynchronizer.this.transactionService.getRetryingTransactionHelper()
                        .doInTransaction(new RetryingTransactionCallback<Object>() {
                            public Object execute() throws Throwable {
                                ChainingUserRegistrySynchronizer.this.jobLockService.refreshLock(token,
                                        ChainingUserRegistrySynchronizer.LOCK_QNAME,
                                        ChainingUserRegistrySynchronizer.LOCK_TTL);
                                return null;
                            }
                        }, false, splitTxns);
            }
        }, ChainingUserRegistrySynchronizer.LOCK_TTL / 2, ChainingUserRegistrySynchronizer.LOCK_TTL / 2,
                TimeUnit.MILLISECONDS);

        Set<String> visitedZoneIds = new TreeSet<String>();
        Collection<String> instanceIds = this.applicationContextManager.getInstanceIds();

        // Work out the set of all zone IDs in the authentication chain so that we can decide which users / groups
        // need 're-zoning'
        Set<String> allZoneIds = new TreeSet<String>();
        for (String id : instanceIds) {
            allZoneIds.add(AuthorityService.ZONE_AUTH_EXT_PREFIX + id);
        }

        // Collect the plugins that we can sync : zoneId, plugin
        Map<String, UserRegistry> plugins = new HashMap<String, UserRegistry>();

        for (String id : instanceIds) {
            UserRegistry plugin;
            try {
                ApplicationContext context = this.applicationContextManager.getApplicationContext(id);
                plugin = (UserRegistry) context.getBean(this.sourceBeanName);
            } catch (RuntimeException e) {
                // The bean doesn't exist or this subsystem won't start. The reason would have been logged. Ignore and continue.
                continue;
            }

            if (!(plugin instanceof ActivateableBean) || ((ActivateableBean) plugin).isActive()) {
                // yes this plugin needs to be synced
                plugins.put(id, plugin);
            }
        }

        /**
         *  Sync starts here
         */
        notifySyncStart(plugins.keySet());

        for (String id : instanceIds) {
            UserRegistry plugin = plugins.get(id);

            if (plugin != null) {
                // If debug is enabled then dump out the contents of the authentication JMX bean
                if (ChainingUserRegistrySynchronizer.logger.isDebugEnabled()) {
                    mbeanServer = (MBeanServerConnection) getApplicationContext()
                            .getBean("alfrescoMBeanServer");
                    try {
                        StringBuilder nameBuff = new StringBuilder(200)
                                .append("Alfresco:Type=Configuration,Category=Authentication,id1=managed,id2=")
                                .append(URLDecoder.decode(id, "UTF-8"));
                        ObjectName name = new ObjectName(nameBuff.toString());
                        if (mbeanServer != null && mbeanServer.isRegistered(name)) {
                            MBeanInfo info = mbeanServer.getMBeanInfo(name);
                            MBeanAttributeInfo[] attributes = info.getAttributes();
                            ChainingUserRegistrySynchronizer.logger.debug(id + " attributes:");
                            for (MBeanAttributeInfo attribute : attributes) {
                                Object value = mbeanServer.getAttribute(name, attribute.getName());
                                ChainingUserRegistrySynchronizer.logger
                                        .debug(attribute.getName() + " = " + value);
                            }
                        }
                    } catch (UnsupportedEncodingException e) {
                        if (ChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                            ChainingUserRegistrySynchronizer.logger.warn("Exception during logging", e);
                        }
                    } catch (MalformedObjectNameException e) {
                        if (ChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                            ChainingUserRegistrySynchronizer.logger.warn("Exception during logging", e);
                        }
                    } catch (InstanceNotFoundException e) {
                        if (ChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                            ChainingUserRegistrySynchronizer.logger.warn("Exception during logging", e);
                        }
                    } catch (IntrospectionException e) {
                        if (ChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                            ChainingUserRegistrySynchronizer.logger.warn("Exception during logging", e);
                        }
                    } catch (AttributeNotFoundException e) {
                        if (ChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                            ChainingUserRegistrySynchronizer.logger.warn("Exception during logging", e);
                        }
                    } catch (ReflectionException e) {
                        if (ChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                            ChainingUserRegistrySynchronizer.logger.warn("Exception during logging", e);
                        }
                    } catch (MBeanException e) {
                        if (ChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                            ChainingUserRegistrySynchronizer.logger.warn("Exception during logging", e);
                        }
                    } catch (IOException e) {
                        if (ChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                            ChainingUserRegistrySynchronizer.logger.warn("Exception during logging", e);
                        }
                    }
                } // end of debug dump of active JMX bean
                if (ChainingUserRegistrySynchronizer.logger.isInfoEnabled()) {
                    ChainingUserRegistrySynchronizer.logger
                            .info("Synchronizing users and groups with user registry '" + id + "'");
                }
                if (isFullSync && ChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                    ChainingUserRegistrySynchronizer.logger
                            .warn("Full synchronization with user registry '" + id + "'");
                    if (allowDeletions) {
                        ChainingUserRegistrySynchronizer.logger.warn(
                                "Some users and groups previously created by synchronization with this user registry may be removed.");
                    } else {
                        ChainingUserRegistrySynchronizer.logger.warn(
                                "Deletions are disabled. Users and groups removed from this registry will be logged only and will remain in the repository. Users previously found in a different registry will be moved in the repository rather than recreated.");
                    }
                }
                // Work out whether we should do the work in a separate transaction (it's most performant if we
                // bunch it into small transactions, but if we are doing a sync on login, it has to be the same
                // transaction)
                boolean requiresNew = splitTxns
                        || AlfrescoTransactionSupport.getTransactionReadState() == TxnReadState.TXN_READ_ONLY;

                try {
                    /**
                     * Do the sync with the specified plugin
                     */
                    syncWithPlugin(id, plugin, forceUpdate, isFullSync, requiresNew, visitedZoneIds,
                            allZoneIds);

                    this.applicationEventPublisher.publishEvent(new SynchronizeDirectoryEndEvent(this, id));
                } catch (final RuntimeException e) {
                    notifySyncDirectoryEnd(id, e);
                    throw e;
                }
            } // if plugin exists
        } // for each instanceId

        //End of successful synchronization here
        notifySyncEnd();
    } catch (final RuntimeException e) {
        notifySyncEnd(e);
        ChainingUserRegistrySynchronizer.logger.error("Synchronization aborted due to error", e);
        throw e;
    } finally {
        // Release the lock if necessary
        if (lockToken != null) {
            // Cancel the lock refresher
            // Because we may hit a perfect storm when trying to interrupt workers in their unsynchronized getTask()
            // method we can't wait indefinitely and may have to retry the shutdown
            int trys = 0;
            do {
                lockRefresher.shutdown();
                try {
                    lockRefresher.awaitTermination(ChainingUserRegistrySynchronizer.LOCK_TTL,
                            TimeUnit.MILLISECONDS);
                } catch (InterruptedException e) {
                }
            } while (!lockRefresher.isTerminated() && trys++ < 3);
            if (!lockRefresher.isTerminated()) {
                lockRefresher.shutdownNow();
                ChainingUserRegistrySynchronizer.logger.error("Failed to shut down lock refresher");
            }

            final String token = lockToken;
            this.transactionService.getRetryingTransactionHelper()
                    .doInTransaction(new RetryingTransactionCallback<Object>() {
                        public Object execute() throws Throwable {
                            ChainingUserRegistrySynchronizer.this.jobLockService.releaseLock(token,
                                    ChainingUserRegistrySynchronizer.LOCK_QNAME);
                            return null;
                        }
                    }, false, splitTxns);
        }
    }
}

From source file:org.cggh.repo.security.sync.CustomChainingUserRegistrySynchronizer.java

private void synchronizeInternal(boolean forceUpdate, boolean isFullSync, final boolean splitTxns) {
    if (CustomChainingUserRegistrySynchronizer.logger.isDebugEnabled()) {

        if (forceUpdate) {
            CustomChainingUserRegistrySynchronizer.logger.debug("Running a full sync.");
        } else {//from w w w  .  java2 s  .  c  o m
            CustomChainingUserRegistrySynchronizer.logger.debug("Running a differential sync.");
        }
        if (allowDeletions) {
            CustomChainingUserRegistrySynchronizer.logger.debug("deletions are allowed");
        } else {
            CustomChainingUserRegistrySynchronizer.logger.debug("deletions are not allowed");
        }
        // Don't proceed with the sync if the repository is read only
        if (this.transactionService.isReadOnly()) {
            CustomChainingUserRegistrySynchronizer.logger
                    .warn("Unable to proceed with user registry synchronization. Repository is read only.");
            return;
        }
    }

    // Don't proceed with the sync if the repository is read only
    if (this.transactionService.isReadOnly()) {
        CustomChainingUserRegistrySynchronizer.logger
                .warn("Unable to proceed with user registry synchronization. Repository is read only.");
        return;
    }

    // Create a background executor that will refresh our lock. This means we can request a lock with a relatively
    // small persistence time and not worry about it lasting after server restarts. Note we use an independent
    // executor because this is a compound operation that spans accross multiple batch processors.
    String lockToken = null;
    TraceableThreadFactory threadFactory = new TraceableThreadFactory();
    threadFactory.setNamePrefix("ChainingUserRegistrySynchronizer lock refresh");
    threadFactory.setThreadDaemon(true);
    ScheduledExecutorService lockRefresher = new ScheduledThreadPoolExecutor(1, threadFactory);

    // Let's ensure all exceptions get logged
    try {
        // First, try to obtain a lock to ensure we are the only node trying to run this job
        try {
            if (splitTxns) {
                // If this is an automated sync on startup or scheduled sync, don't even wait around for the lock.
                // Assume the sync will be completed on another node.
                lockToken = this.transactionService.getRetryingTransactionHelper()
                        .doInTransaction(new RetryingTransactionCallback<String>() {
                            public String execute() throws Throwable {
                                return CustomChainingUserRegistrySynchronizer.this.jobLockService.getLock(
                                        CustomChainingUserRegistrySynchronizer.LOCK_QNAME,
                                        CustomChainingUserRegistrySynchronizer.LOCK_TTL, 0, 1);
                            }
                        }, false, splitTxns);
            } else {
                // If this is a login-triggered sync, give it a few retries before giving up
                lockToken = this.jobLockService.getLock(CustomChainingUserRegistrySynchronizer.LOCK_QNAME,
                        CustomChainingUserRegistrySynchronizer.LOCK_TTL, 3000, 10);
            }
        } catch (LockAcquisitionException e) {
            // Don't proceed with the sync if it is running on another node
            CustomChainingUserRegistrySynchronizer.logger.warn(
                    "User registry synchronization already running in another thread. Synchronize aborted");
            return;
        }

        // Schedule the lock refresh to run at regular intervals
        final String token = lockToken;
        lockRefresher.scheduleAtFixedRate(new Runnable() {
            public void run() {
                CustomChainingUserRegistrySynchronizer.this.transactionService.getRetryingTransactionHelper()
                        .doInTransaction(new RetryingTransactionCallback<Object>() {
                            public Object execute() throws Throwable {
                                CustomChainingUserRegistrySynchronizer.this.jobLockService.refreshLock(token,
                                        CustomChainingUserRegistrySynchronizer.LOCK_QNAME,
                                        CustomChainingUserRegistrySynchronizer.LOCK_TTL);
                                return null;
                            }
                        }, false, splitTxns);
            }
        }, CustomChainingUserRegistrySynchronizer.LOCK_TTL / 2,
                CustomChainingUserRegistrySynchronizer.LOCK_TTL / 2, TimeUnit.MILLISECONDS);

        Set<String> visitedZoneIds = new TreeSet<String>();
        Collection<String> instanceIds = this.applicationContextManager.getInstanceIds();

        // Work out the set of all zone IDs in the authentication chain so that we can decide which users / groups
        // need 're-zoning'
        Set<String> allZoneIds = new TreeSet<String>();
        for (String id : instanceIds) {
            allZoneIds.add(AuthorityService.ZONE_AUTH_EXT_PREFIX + id);
        }

        // Collect the plugins that we can sync : zoneId, plugin
        Map<String, UserRegistry> plugins = new HashMap<String, UserRegistry>();

        for (String id : instanceIds) {
            UserRegistry plugin;
            try {
                ApplicationContext context = this.applicationContextManager.getApplicationContext(id);
                plugin = (UserRegistry) context.getBean(this.sourceBeanName);
            } catch (RuntimeException e) {
                // The bean doesn't exist or this subsystem won't start. The reason would have been logged. Ignore and continue.
                continue;
            }

            if (!(plugin instanceof ActivateableBean) || ((ActivateableBean) plugin).isActive()) {
                // yes this plugin needs to be synced
                plugins.put(id, plugin);
            }
        }

        /**
         *  Sync starts here
         */
        notifySyncStart(plugins.keySet());

        for (String id : instanceIds) {
            UserRegistry plugin = plugins.get(id);

            if (plugin != null) {
                // If debug is enabled then dump out the contents of the authentication JMX bean
                if (CustomChainingUserRegistrySynchronizer.logger.isDebugEnabled()) {
                    mbeanServer = (MBeanServerConnection) getApplicationContext()
                            .getBean("alfrescoMBeanServer");
                    try {
                        StringBuilder nameBuff = new StringBuilder(200)
                                .append("Alfresco:Type=Configuration,Category=Authentication,id1=managed,id2=")
                                .append(URLDecoder.decode(id, "UTF-8"));
                        ObjectName name = new ObjectName(nameBuff.toString());
                        if (mbeanServer != null && mbeanServer.isRegistered(name)) {
                            MBeanInfo info = mbeanServer.getMBeanInfo(name);
                            MBeanAttributeInfo[] attributes = info.getAttributes();
                            CustomChainingUserRegistrySynchronizer.logger.debug(id + " attributes:");
                            for (MBeanAttributeInfo attribute : attributes) {
                                Object value = mbeanServer.getAttribute(name, attribute.getName());
                                CustomChainingUserRegistrySynchronizer.logger
                                        .debug(attribute.getName() + " = " + value);
                            }
                        }
                    } catch (UnsupportedEncodingException e) {
                        if (CustomChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                            CustomChainingUserRegistrySynchronizer.logger.warn("Exception during logging", e);
                        }
                    } catch (MalformedObjectNameException e) {
                        if (CustomChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                            CustomChainingUserRegistrySynchronizer.logger.warn("Exception during logging", e);
                        }
                    } catch (InstanceNotFoundException e) {
                        if (CustomChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                            CustomChainingUserRegistrySynchronizer.logger.warn("Exception during logging", e);
                        }
                    } catch (IntrospectionException e) {
                        if (CustomChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                            CustomChainingUserRegistrySynchronizer.logger.warn("Exception during logging", e);
                        }
                    } catch (AttributeNotFoundException e) {
                        if (CustomChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                            CustomChainingUserRegistrySynchronizer.logger.warn("Exception during logging", e);
                        }
                    } catch (ReflectionException e) {
                        if (CustomChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                            CustomChainingUserRegistrySynchronizer.logger.warn("Exception during logging", e);
                        }
                    } catch (MBeanException e) {
                        if (CustomChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                            CustomChainingUserRegistrySynchronizer.logger.warn("Exception during logging", e);
                        }
                    } catch (IOException e) {
                        if (CustomChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                            CustomChainingUserRegistrySynchronizer.logger.warn("Exception during logging", e);
                        }
                    }
                } // end of debug dump of active JMX bean
                if (CustomChainingUserRegistrySynchronizer.logger.isInfoEnabled()) {
                    CustomChainingUserRegistrySynchronizer.logger
                            .info("Synchronizing users and groups with user registry '" + id + "'");
                }
                if (isFullSync && CustomChainingUserRegistrySynchronizer.logger.isWarnEnabled()) {
                    CustomChainingUserRegistrySynchronizer.logger
                            .warn("Full synchronization with user registry '" + id + "'");
                    if (allowDeletions) {
                        CustomChainingUserRegistrySynchronizer.logger.warn(
                                "Some users and groups previously created by synchronization with this user registry may be removed.");
                    } else {
                        CustomChainingUserRegistrySynchronizer.logger.warn(
                                "Deletions are disabled. Users and groups removed from this registry will be logged only and will remain in the repository. Users previously found in a different registry will be moved in the repository rather than recreated.");
                    }
                }
                // Work out whether we should do the work in a separate transaction (it's most performant if we
                // bunch it into small transactions, but if we are doing a sync on login, it has to be the same
                // transaction)
                boolean requiresNew = splitTxns
                        || AlfrescoTransactionSupport.getTransactionReadState() == TxnReadState.TXN_READ_ONLY;

                try {
                    /**
                     * Do the sync with the specified plugin
                     */
                    syncWithPlugin(id, plugin, forceUpdate, isFullSync, requiresNew, visitedZoneIds,
                            allZoneIds);

                    this.applicationEventPublisher.publishEvent(new SynchronizeDirectoryEndEvent(this, id));
                } catch (final RuntimeException e) {
                    notifySyncDirectoryEnd(id, e);
                    throw e;
                }
            } // if plugin exists
        } // for each instanceId

        //End of successful synchronization here
        notifySyncEnd();
    } catch (final RuntimeException e) {
        notifySyncEnd(e);
        CustomChainingUserRegistrySynchronizer.logger.error("Synchronization aborted due to error", e);
        throw e;
    } finally {
        // Release the lock if necessary
        if (lockToken != null) {
            // Cancel the lock refresher
            // Because we may hit a perfect storm when trying to interrupt workers in their unsynchronized getTask()
            // method we can't wait indefinitely and may have to retry the shutdown
            int trys = 0;
            do {
                lockRefresher.shutdown();
                try {
                    lockRefresher.awaitTermination(CustomChainingUserRegistrySynchronizer.LOCK_TTL,
                            TimeUnit.MILLISECONDS);
                } catch (InterruptedException e) {
                }
            } while (!lockRefresher.isTerminated() && trys++ < 3);
            if (!lockRefresher.isTerminated()) {
                lockRefresher.shutdownNow();
                CustomChainingUserRegistrySynchronizer.logger.error("Failed to shut down lock refresher");
            }

            final String token = lockToken;
            this.transactionService.getRetryingTransactionHelper()
                    .doInTransaction(new RetryingTransactionCallback<Object>() {
                        public Object execute() throws Throwable {
                            CustomChainingUserRegistrySynchronizer.this.jobLockService.releaseLock(token,
                                    CustomChainingUserRegistrySynchronizer.LOCK_QNAME);
                            return null;
                        }
                    }, false, splitTxns);
        }
    }
}

From source file:org.apache.hadoop.jmx.JMXJsonServlet.java

private void listBeans(JsonGenerator jg, ObjectName qry) throws IOException {
    LOG.debug("Listing beans for " + qry);
    Set<ObjectName> names = null;
    names = mBeanServer.queryNames(qry, null);

    jg.writeArrayFieldStart("beans");
    Iterator<ObjectName> it = names.iterator();
    while (it.hasNext()) {
        ObjectName oname = it.next();
        MBeanInfo minfo;
        String code;// w w w. j  av a 2 s  .  c o  m
        try {
            minfo = mBeanServer.getMBeanInfo(oname);
            code = minfo.getClassName();
            try {
                if ("org.apache.commons.modeler.BaseModelMBean".equals(code)) {
                    code = (String) mBeanServer.getAttribute(oname, "modelerType");
                }
            } catch (AttributeNotFoundException e) {
                //Ignored the modelerType attribute was not found, so use the class name instead.
            } catch (MBeanException e) {
                //The code inside the attribute getter threw an exception so log it, and
                // fall back on the class name
                LOG.error("getting attribute modelerType of " + oname + " threw an exception", e);
            } catch (RuntimeException e) {
                //For some reason even with an MBeanException available to them Runtime exceptions
                //can still find their way through, so treat them the same as MBeanException
                LOG.error("getting attribute modelerType of " + oname + " threw an exception", e);
            } catch (ReflectionException e) {
                //This happens when the code inside the JMX bean (setter?? from the java docs)
                //threw an exception, so log it and fall back on the class name
                LOG.error("getting attribute modelerType of " + oname + " threw an exception", e);
            }
        } catch (InstanceNotFoundException e) {
            //Ignored for some reason the bean was not found so don't output it
            continue;
        } catch (IntrospectionException e) {
            //This is an internal error, something odd happened with reflection so log it and
            //don't output the bean.
            LOG.error("Problem while trying to process JMX query: " + qry + " with MBean " + oname, e);
            continue;
        } catch (ReflectionException e) {
            //This happens when the code inside the JMX bean threw an exception, so log it and
            //don't output the bean.
            LOG.error("Problem while trying to process JMX query: " + qry + " with MBean " + oname, e);
            continue;
        }

        jg.writeStartObject();
        jg.writeStringField("name", oname.toString());
        // can't be null - I think

        jg.writeStringField("modelerType", code);

        MBeanAttributeInfo attrs[] = minfo.getAttributes();
        for (int i = 0; i < attrs.length; i++) {
            writeAttribute(jg, oname, attrs[i]);
        }
        //  LOG.error("Caught Error writing value ",t);
        //  ExceptionUtils.handleThrowable(t);
        //}
        jg.writeEndObject();
    }
    jg.writeEndArray();
}

From source file:com.streamsets.datacollector.http.JMXJsonServlet.java

private void listBeans(JsonGenerator jg, ObjectName qry, String attribute, HttpServletResponse response)
        throws IOException {

    Set<ObjectName> names = null;
    names = mBeanServer.queryNames(qry, null);

    jg.writeArrayFieldStart("beans");
    Iterator<ObjectName> it = names.iterator();
    while (it.hasNext()) {
        ObjectName oname = it.next();
        MBeanInfo minfo;
        String code = "";
        Object attributeinfo = null;
        try {// w  ww  .  j a  va 2s  .c om
            minfo = mBeanServer.getMBeanInfo(oname);
            code = minfo.getClassName();
            String prs = "";
            try {
                if ("org.apache.commons.modeler.BaseModelMBean".equals(code)) {
                    prs = "modelerType";
                    code = (String) mBeanServer.getAttribute(oname, prs);
                }
                if (attribute != null) {
                    prs = attribute;
                    attributeinfo = mBeanServer.getAttribute(oname, prs);
                }
            } catch (AttributeNotFoundException e) {
                // If the modelerType attribute was not found, the class name is used
                // instead.

            } catch (MBeanException e) {
                // The code inside the attribute getter threw an exception so 
                // and fall back on the class name

            } catch (RuntimeException e) {
                // For some reason even with an MBeanException available to them
                // Runtime exceptionscan still find their way through, so treat them
                // the same as MBeanException

            } catch (ReflectionException e) {
                // This happens when the code inside the JMX bean (setter?? from the
                // java docs) threw an exception, so 
                // class name

            }
        } catch (InstanceNotFoundException e) {
            //Ignored for some reason the bean was not found so don't output it
            continue;
        } catch (IntrospectionException e) {
            // This is an internal error, something odd happened with reflection so
            // 

            continue;
        } catch (ReflectionException e) {
            // This happens when the code inside the JMX bean threw an exception, so
            // 

            continue;
        }

        jg.writeStartObject();
        jg.writeStringField("name", oname.toString());

        jg.writeStringField("modelerType", code);
        if ((attribute != null) && (attributeinfo == null)) {
            jg.writeStringField("result", "ERROR");
            jg.writeStringField("message", "No attribute with name " + attribute + " was found.");
            jg.writeEndObject();
            jg.writeEndArray();
            jg.close();
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        if (attribute != null) {
            writeAttribute(jg, attribute, attributeinfo);
        } else {
            MBeanAttributeInfo attrs[] = minfo.getAttributes();
            for (int i = 0; i < attrs.length; i++) {
                writeAttribute(jg, oname, attrs[i]);
            }
        }
        jg.writeEndObject();
    }
    jg.writeEndArray();
}