text:
package org.jasig.cas;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.NotNull;

import com.github.inspektr.audit.annotation.Audit;
import org.apache.commons.lang.StringUtils;
import org.jasig.cas.authentication.AcceptAnyAuthenticationPolicyFactory;
import org.jasig.cas.authentication.Authentication;
import org.jasig.cas.authentication.AuthenticationBuilder;
import org.jasig.cas.authentication.AuthenticationException;
import org.jasig.cas.authentication.AuthenticationManager;
import org.jasig.cas.authentication.ContextualAuthenticationPolicy;
import org.jasig.cas.authentication.ContextualAuthenticationPolicyFactory;
import org.jasig.cas.authentication.MixedPrincipalException;
import org.jasig.cas.authentication.Credential;
import org.jasig.cas.authentication.principal.PersistentIdGenerator;
import org.jasig.cas.authentication.principal.Principal;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.authentication.principal.ShibbolethCompatiblePersistentIdGenerator;
import org.jasig.cas.authentication.principal.SimplePrincipal;
import org.jasig.cas.logout.LogoutManager;
import org.jasig.cas.logout.LogoutRequest;
import org.jasig.cas.services.RegisteredService;
import org.jasig.cas.services.RegisteredServiceAttributeFilter;
import org.jasig.cas.services.ServiceContext;
import org.jasig.cas.services.ServicesManager;
import org.jasig.cas.services.UnauthorizedProxyingException;
import org.jasig.cas.services.UnauthorizedServiceException;
import org.jasig.cas.services.UnauthorizedSsoServiceException;
import org.jasig.cas.services.support.RegisteredServiceDefaultAttributeFilter;
import org.jasig.cas.ticket.ExpirationPolicy;
import org.jasig.cas.ticket.InvalidTicketException;
import org.jasig.cas.ticket.ServiceTicket;
import org.jasig.cas.ticket.TicketException;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.ticket.TicketGrantingTicketImpl;
import org.jasig.cas.ticket.TicketValidationException;
import org.jasig.cas.ticket.UnsatisfiedAuthenticationPolicyException;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.jasig.cas.util.UniqueTicketIdGenerator;
import org.jasig.cas.validation.Assertion;
import org.jasig.cas.validation.ImmutableAssertion;
import org.perf4j.aop.Profiled;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * Concrete implementation of a CentralAuthenticationService, and also the
 * central, organizing component of CAS's internal implementation.
 *

 * This class is threadsafe.
 *

 * This class has the following properties that must be set:
 *

 *
 ticketRegistry - The Ticket Registry to maintain the list
 * of available tickets.

 *
 serviceTicketRegistry - Provides an alternative to configure separate registries for
 * TGTs and ST in order to store them in different locations (i.e. long term memory or short-term)

 *
 authenticationManager - The service that will handle
 * authentication.

 *
 ticketGrantingTicketUniqueTicketIdGenerator - Plug in to
 * generate unique secure ids for TicketGrantingTickets.

 *
 serviceTicketUniqueTicketIdGenerator - Plug in to
 * generate unique secure ids for ServiceTickets.

 *
 ticketGrantingTicketExpirationPolicy - The expiration
 * policy for TicketGrantingTickets.

 *
 serviceTicketExpirationPolicy - The expiration policy for
 * ServiceTickets.

 *

 *
 * @author William G. Thompson, Jr.
 * @author Scott Battaglia
 * @author Dmitry Kopylenko
 * @since 3.0
 */
public final class CentralAuthenticationServiceImpl implements CentralAuthenticationService {

    /** Log instance for logging events, info, warnings, errors, etc. */
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /** TicketRegistry for storing and retrieving tickets as needed. */
    @NotNull
    private final TicketRegistry ticketRegistry;

    /** New Ticket Registry for storing and retrieving services tickets. Can point to the same one as the ticketRegistry variable. */
    @NotNull
    private final TicketRegistry serviceTicketRegistry;

    /**
     * AuthenticationManager for authenticating credentials for purposes of
     * obtaining tickets.
     */
    @NotNull
    private final AuthenticationManager authenticationManager;

    /**
     * UniqueTicketIdGenerator to generate ids for TicketGrantingTickets
     * created.
     */
    @NotNull
    private final UniqueTicketIdGenerator ticketGrantingTicketUniqueTicketIdGenerator;

    /** Map to contain the mappings of service->UniqueTicketIdGenerators. */
    @NotNull
    private final Map<String, UniqueTicketIdGenerator> uniqueTicketIdGeneratorsForService;

    /** Implementation of Service Manager. */
    @NotNull
    private final ServicesManager servicesManager;

    /** The logout manager. **/
    @NotNull
    private final LogoutManager logoutManager;

    /** Expiration policy for ticket granting tickets. */
    @NotNull
    private ExpirationPolicy ticketGrantingTicketExpirationPolicy;

    /** ExpirationPolicy for Service Tickets. */
    @NotNull
    private ExpirationPolicy serviceTicketExpirationPolicy;

    /** Encoder to generate PseudoIds. */
    @NotNull
    private PersistentIdGenerator persistentIdGenerator = new ShibbolethCompatiblePersistentIdGenerator();

    /** The default attribute filter to match principal attributes against that of a registered service. **/
    private RegisteredServiceAttributeFilter defaultAttributeFilter = new RegisteredServiceDefaultAttributeFilter();

    /**
     * Authentication policy that uses a service context to produce stateful security policies to apply when
     * authenticating credentials.
     */
    @NotNull
    private ContextualAuthenticationPolicyFactory<ServiceContext> serviceContextAuthenticationPolicyFactory =
            new AcceptAnyAuthenticationPolicyFactory();

    /**
     * Build the central authentication service implementation.
     *
     * @param ticketRegistry the tickets registry.
     * @param serviceTicketRegistry the service tickets registry.
     * @param authenticationManager the authentication manager.
     * @param ticketGrantingTicketUniqueTicketIdGenerator the TGT id generator.
     * @param uniqueTicketIdGeneratorsForService the map with service and ticket id generators.
     * @param ticketGrantingTicketExpirationPolicy the TGT expiration policy.
     * @param serviceTicketExpirationPolicy the service ticket expiration policy.
     * @param servicesManager the services manager.
     * @param logoutManager the logout manager.
     */
    public CentralAuthenticationServiceImpl(final TicketRegistry ticketRegistry,
                                            final TicketRegistry serviceTicketRegistry,
                                            final AuthenticationManager authenticationManager,
                                            final UniqueTicketIdGenerator ticketGrantingTicketUniqueTicketIdGenerator,
                                            final Map<String, UniqueTicketIdGenerator> uniqueTicketIdGeneratorsForService,
                                            final ExpirationPolicy ticketGrantingTicketExpirationPolicy,
                                            final ExpirationPolicy serviceTicketExpirationPolicy,
                                            final ServicesManager servicesManager,
                                            final LogoutManager logoutManager) {
        this.ticketRegistry = ticketRegistry;
        if (serviceTicketRegistry == null) {
            this.serviceTicketRegistry = ticketRegistry;
        } else {
            this.serviceTicketRegistry = serviceTicketRegistry;
        }
        this.authenticationManager = authenticationManager;
        this.ticketGrantingTicketUniqueTicketIdGenerator = ticketGrantingTicketUniqueTicketIdGenerator;
        this.uniqueTicketIdGeneratorsForService = uniqueTicketIdGeneratorsForService;
        this.ticketGrantingTicketExpirationPolicy = ticketGrantingTicketExpirationPolicy;
        this.serviceTicketExpirationPolicy = serviceTicketExpirationPolicy;
        this.servicesManager = servicesManager;
        this.logoutManager = logoutManager;
    }

    /**
     * {@inheritDoc}
     * Destroy a TicketGrantingTicket and perform back channel logout. This has the effect of invalidating any
     * Ticket that was derived from the TicketGrantingTicket being destroyed. May throw an
     * {@link IllegalArgumentException} if the TicketGrantingTicket ID is null.
     *
     * @param ticketGrantingTicketId the id of the ticket we want to destroy
     * @return the logout requests.
     */
    @Audit(
            action="TICKET_GRANTING_TICKET_DESTROYED",
            actionResolverName="DESTROY_TICKET_GRANTING_TICKET_RESOLVER",
            resourceResolverName="DESTROY_TICKET_GRANTING_TICKET_RESOURCE_RESOLVER")
    @Profiled(tag = "DESTROY_TICKET_GRANTING_TICKET", logFailuresSeparately = false)
    @Transactional(readOnly = false)
    @Override
    public List<LogoutRequest> destroyTicketGrantingTicket(final String ticketGrantingTicketId) {
        Assert.notNull(ticketGrantingTicketId);

        logger.debug("Removing ticket [{}] from registry.", ticketGrantingTicketId);
        final TicketGrantingTicket ticket = this.ticketRegistry.getTicket(ticketGrantingTicketId,
                TicketGrantingTicket.class);

        if (ticket == null) {
            logger.debug("TicketGrantingTicket [{}] cannot be found in the ticket registry.", ticketGrantingTicketId);
            return Collections.emptyList();
        }

        logger.debug("Ticket found. Processing logout requests and then deleting the ticket...");
        final List<LogoutRequest> logoutRequests = logoutManager.performLogout(ticket);
        this.ticketRegistry.deleteTicket(ticketGrantingTicketId);

        return logoutRequests;
    }

    /**
     * @throws IllegalArgumentException if ticketGrantingTicketId or service are null.
     */
    @Audit(
        action="SERVICE_TICKET",
        actionResolverName="GRANT_SERVICE_TICKET_RESOLVER",
        resourceResolverName="GRANT_SERVICE_TICKET_RESOURCE_RESOLVER")
    @Profiled(tag="GRANT_SERVICE_TICKET", logFailuresSeparately = false)
    @Transactional(readOnly = false)
    public String grantServiceTicket(
            final String ticketGrantingTicketId, final Service service, final Credential... credentials)
            throws AuthenticationException, TicketException {
        Assert.notNull(ticketGrantingTicketId, "ticketGrantingticketId cannot be null");
        Assert.notNull(service, "service cannot be null");

        final TicketGrantingTicket ticketGrantingTicket = this.ticketRegistry.getTicket(ticketGrantingTicketId, TicketGrantingTicket.class);

        if (ticketGrantingTicket == null) {
            logger.debug("TicketGrantingTicket [{}] cannot be found in the ticket registry.", ticketGrantingTicketId);
            throw new InvalidTicketException(ticketGrantingTicketId);
        }

        synchronized (ticketGrantingTicket) {
            if (ticketGrantingTicket.isExpired()) {
                this.ticketRegistry.deleteTicket(ticketGrantingTicketId);
                logger.debug("TicketGrantingTicket[{}] has expired and is now deleted from the ticket registry.", ticketGrantingTicketId);
                throw new InvalidTicketException(ticketGrantingTicketId);
            }
        }

        final RegisteredService registeredService = this.servicesManager.findServiceBy(service);

        verifyRegisteredServiceProperties(registeredService, service);

        if (!registeredService.isSsoEnabled() && credentials == null
            && ticketGrantingTicket.getCountOfUses() > 0) {
            logger.warn("ServiceManagement: Service [{}] is not allowed to use SSO.", service.getId());
            throw new UnauthorizedSsoServiceException();
        }

        //CAS-1019
        final List<Authentication> authns = ticketGrantingTicket.getChainedAuthentications();
        if(authns.size() > 1) {
            if (!registeredService.isAllowedToProxy()) {
                final String message = String.
                        format("ServiceManagement: Proxy attempt by service [%s] (registered service [%s]) is not allowed.",
                        service.getId(), registeredService.toString());
                logger.warn(message);
                throw new UnauthorizedProxyingException(message);
            }
        }

        if (credentials != null) {
            final Authentication current = this.authenticationManager.authenticate(credentials);
            final Authentication original = ticketGrantingTicket.getAuthentication();
            if (!current.getPrincipal().equals(original.getPrincipal())) {
                throw new MixedPrincipalException(current, current.getPrincipal(), original.getPrincipal());
            }
            ticketGrantingTicket.getSupplementalAuthentications().add(current);
        }

        // Perform security policy check by getting the authentication that satisfies the configured policy
        // This throws if no suitable policy is found
        getAuthenticationSatisfiedByPolicy(ticketGrantingTicket, new ServiceContext(service, registeredService));

        final String uniqueTicketIdGenKey = service.getClass().getName();
        if (!this.uniqueTicketIdGeneratorsForService.containsKey(uniqueTicketIdGenKey)) {
            logger.warn("Cannot create service ticket because the key [{}] for service [{}] is not linked to a ticket id generator",
                    uniqueTicketIdGenKey, service.getId());
            throw new UnauthorizedSsoServiceException();
        }

        final UniqueTicketIdGenerator serviceTicketUniqueTicketIdGenerator =
                this.uniqueTicketIdGeneratorsForService.get(uniqueTicketIdGenKey);

        final String generatedServiceTicketId = serviceTicketUniqueTicketIdGenerator.getNewTicketId(ServiceTicket.PREFIX);
        logger.debug("Generated service ticket id [{}] for ticket granting ticket [{}]",
                generatedServiceTicketId, ticketGrantingTicket.getId());

        final ServiceTicket serviceTicket = ticketGrantingTicket.grantServiceTicket(generatedServiceTicketId, service,
                this.serviceTicketExpirationPolicy, credentials != null);

        this.serviceTicketRegistry.addTicket(serviceTicket);

        if (logger.isInfoEnabled()) {
            final List<Authentication> authentications = serviceTicket.getGrantingTicket().getChainedAuthentications();
            final String formatString = "Granted %s ticket [%s] for service [%s] for user [%s]";
            final String type;
            final String principalId = authentications.get(authentications.size() - 1).getPrincipal().getId();

            if (authentications.size() == 1) {
                type = "service";
            } else {
                type = "proxy";
            }

            logger.info(String.format(formatString, type, serviceTicket.getId(), service.getId(), principalId));
        }

        return serviceTicket.getId();
    }

    @Audit(
        action="SERVICE_TICKET",
        actionResolverName="GRANT_SERVICE_TICKET_RESOLVER",
        resourceResolverName="GRANT_SERVICE_TICKET_RESOURCE_RESOLVER")
    @Profiled(tag = "GRANT_SERVICE_TICKET", logFailuresSeparately = false)
    @Transactional(readOnly = false)
    public String grantServiceTicket(final String ticketGrantingTicketId,
        final Service service) throws TicketException {
        try {
            return this.grantServiceTicket(ticketGrantingTicketId, service, null);
        } catch (final AuthenticationException e) {
            throw new IllegalStateException("Unexpected authentication exception", e);
        }
    }

    /**
     * @throws IllegalArgumentException if the ServiceTicketId or the
     * Credential are null.
     */
    @Audit(
        action="PROXY_GRANTING_TICKET",
        actionResolverName="GRANT_PROXY_GRANTING_TICKET_RESOLVER",
        resourceResolverName="GRANT_PROXY_GRANTING_TICKET_RESOURCE_RESOLVER")
    @Profiled(tag="GRANT_PROXY_GRANTING_TICKET", logFailuresSeparately = false)
    @Transactional(readOnly = false)
    public String delegateTicketGrantingTicket(final String serviceTicketId, final Credential... credentials)
            throws AuthenticationException, TicketException {

        Assert.notNull(serviceTicketId, "serviceTicketId cannot be null");
        Assert.notNull(credentials, "credentials cannot be null");

        final ServiceTicket serviceTicket =  this.serviceTicketRegistry.getTicket(serviceTicketId, ServiceTicket.class);

        if (serviceTicket == null || serviceTicket.isExpired()) {
            logger.debug("ServiceTicket [{}] has expired or cannot be found in the ticket registry", serviceTicketId);
            throw new InvalidTicketException(serviceTicketId);
        }

        final RegisteredService registeredService = this.servicesManager
                .findServiceBy(serviceTicket.getService());

        verifyRegisteredServiceProperties(registeredService, serviceTicket.getService());

        if (!registeredService.isAllowedToProxy()) {
            logger.warn("ServiceManagement: Service [{}] attempted to proxy, but is not allowed.", serviceTicket.getService().getId());
            throw new UnauthorizedProxyingException();
        }

        final Authentication authentication = this.authenticationManager.authenticate(credentials);

        final TicketGrantingTicket ticketGrantingTicket = serviceTicket
                .grantTicketGrantingTicket(
                        this.ticketGrantingTicketUniqueTicketIdGenerator
                                .getNewTicketId(TicketGrantingTicket.PREFIX),
                        authentication, this.ticketGrantingTicketExpirationPolicy);

        this.ticketRegistry.addTicket(ticketGrantingTicket);

        return ticketGrantingTicket.getId();
    }

    /**
     * @throws IllegalArgumentException if the ServiceTicketId or the Service
     * are null.
     */
    @Audit(
        action="SERVICE_TICKET_VALIDATE",
        actionResolverName="VALIDATE_SERVICE_TICKET_RESOLVER",
        resourceResolverName="VALIDATE_SERVICE_TICKET_RESOURCE_RESOLVER")
    @Profiled(tag="VALIDATE_SERVICE_TICKET", logFailuresSeparately = false)
    @Transactional(readOnly = false)
    public Assertion validateServiceTicket(final String serviceTicketId, final Service service) throws TicketException {
        Assert.notNull(serviceTicketId, "serviceTicketId cannot be null");
        Assert.notNull(service, "service cannot be null");

        final ServiceTicket serviceTicket =  this.serviceTicketRegistry.getTicket(serviceTicketId, ServiceTicket.class);

        if (serviceTicket == null) {
            logger.info("ServiceTicket [{}] does not exist.", serviceTicketId);
            throw new InvalidTicketException(serviceTicketId);
        }

        final RegisteredService registeredService = this.servicesManager.findServiceBy(service);

        verifyRegisteredServiceProperties(registeredService, serviceTicket.getService());

        try {
            synchronized (serviceTicket) {
                if (serviceTicket.isExpired()) {
                    logger.info("ServiceTicket [{}] has expired.", serviceTicketId);
                    throw new InvalidTicketException(serviceTicketId);
                }

                if (!serviceTicket.isValidFor(service)) {
                    logger.error("ServiceTicket [{}] with service [{}] does not match supplied service [{}]",
                            serviceTicketId, serviceTicket.getService().getId(), service);
                    throw new TicketValidationException(serviceTicket.getService());
                }
            }

            final TicketGrantingTicket root = serviceTicket.getGrantingTicket().getRoot();
            final Authentication authentication = getAuthenticationSatisfiedByPolicy(
                    root, new ServiceContext(serviceTicket.getService(), registeredService));
            final Principal principal = authentication.getPrincipal();

            Map<String, Object> attributesToRelease = this.defaultAttributeFilter.filter(principal.getId(),
                    principal.getAttributes(), registeredService);
            if (registeredService.getAttributeFilter() != null) {
                attributesToRelease = registeredService.getAttributeFilter().filter(principal.getId(),
                        attributesToRelease, registeredService);
            }

            final String principalId = determinePrincipalIdForRegisteredService(principal, registeredService, serviceTicket);
            final Principal modifiedPrincipal = new SimplePrincipal(principalId, attributesToRelease);
            final AuthenticationBuilder builder = AuthenticationBuilder.newInstance(authentication);
            builder.setPrincipal(modifiedPrincipal);

            return new ImmutableAssertion(
                    builder.build(),
                    serviceTicket.getGrantingTicket().getChainedAuthentications(),
                    serviceTicket.getService(),
                    serviceTicket.isFromNewLogin());
        } finally {
            if (serviceTicket.isExpired()) {
                this.serviceTicketRegistry.deleteTicket(serviceTicketId);
            }
        }
    }

    /**
     * Determines the principal id to use for a {@link RegisteredService} using the following rules:
     *
     *

     *
 If the service is marked to allow anonymous access, a persistent id is returned.

     *
 If the {@link org.jasig.cas.services.RegisteredService#getUsernameAttribute()} is blank, then the default
     *  principal id is returned.

     *
If the username attribute is available as part of the principal's attributes,
     *  the corresponding attribute value will be returned.
     *

     *
Otherwise, the default principal's id is returned as the username attribute
     *   with an additional warning.

     *

     *
     * @param principal The principal object to be validated and constructed
     * @param registeredService Requesting service for which a principal is being validated.
     * @param serviceTicket An instance of the service ticket used for validation
     *
     * @return The principal id to use for the requesting registered service
     */
    private String determinePrincipalIdForRegisteredService(final Principal principal,
                                                            final RegisteredService registeredService,
                                                            final ServiceTicket serviceTicket) {
        String principalId = null;
        final String serviceUsernameAttribute = registeredService.getUsernameAttribute();

        if (registeredService.isAnonymousAccess()) {
            principalId = this.persistentIdGenerator.generate(principal, serviceTicket.getService());
        } else if (StringUtils.isBlank(serviceUsernameAttribute)) {
            principalId = principal.getId();
        } else {
            if (principal.getAttributes().containsKey(serviceUsernameAttribute)) {
                principalId = principal.getAttributes().get(serviceUsernameAttribute).toString();
            } else {
                principalId = principal.getId();
                final Object[] errorLogParameters = new Object[] {
                        principalId,
                        registeredService.getUsernameAttribute(),
                        principal.getAttributes(),
                        registeredService.getServiceId(),
                        principalId };
                logger.warn("Principal [{}] did not have attribute [{}] among attributes [{}] so CAS cannot "
                        + "provide on the validation response the user attribute the registered service [{}] expects. "
                        + "CAS will instead return the default username attribute [{}]", errorLogParameters);
            }

        }

        logger.debug("Principal id to return for service [{}] is [{}]. The default principal id is [{}].",
                new Object[]{registeredService.getName(), principal.getId(), principalId});
        return principalId;
    }

    /**
     * @throws IllegalArgumentException if the credentials are null.
     */
    @Audit(
        action="TICKET_GRANTING_TICKET",
        actionResolverName="CREATE_TICKET_GRANTING_TICKET_RESOLVER",
        resourceResolverName="CREATE_TICKET_GRANTING_TICKET_RESOURCE_RESOLVER")
    @Profiled(tag = "CREATE_TICKET_GRANTING_TICKET", logFailuresSeparately = false)
    @Transactional(readOnly = false)
    public String createTicketGrantingTicket(final Credential... credentials)
            throws AuthenticationException, TicketException {

        Assert.notNull(credentials, "credentials cannot be null");

        final Authentication authentication = this.authenticationManager.authenticate(credentials);

        final TicketGrantingTicket ticketGrantingTicket = new TicketGrantingTicketImpl(
            this.ticketGrantingTicketUniqueTicketIdGenerator
                .getNewTicketId(TicketGrantingTicket.PREFIX),
            authentication, this.ticketGrantingTicketExpirationPolicy);

        this.ticketRegistry.addTicket(ticketGrantingTicket);
        return ticketGrantingTicket.getId();
    }

    public void setPersistentIdGenerator(
        final PersistentIdGenerator persistentIdGenerator) {
        this.persistentIdGenerator = persistentIdGenerator;
    }

    public void setServiceContextAuthenticationPolicyFactory(final ContextualAuthenticationPolicyFactory<ServiceContext> policy) {
        this.serviceContextAuthenticationPolicyFactory = policy;
    }

    /**
     * @param ticketGrantingTicketExpirationPolicy a TGT expiration policy.
     */
    public void setTicketGrantingTicketExpirationPolicy(final ExpirationPolicy ticketGrantingTicketExpirationPolicy) {
        this.ticketGrantingTicketExpirationPolicy = ticketGrantingTicketExpirationPolicy;
    }

    /**
     * @param serviceTicketExpirationPolicy a ST expiration policy.
     */
    public void setServiceTicketExpirationPolicy(final ExpirationPolicy serviceTicketExpirationPolicy) {
        this.serviceTicketExpirationPolicy = serviceTicketExpirationPolicy;
    }

    private Authentication getAuthenticationSatisfiedByPolicy(
            final TicketGrantingTicket ticket, final ServiceContext context) throws TicketException {

        final ContextualAuthenticationPolicy<ServiceContext> policy =
                serviceContextAuthenticationPolicyFactory.createPolicy(context);
        if (policy.isSatisfiedBy(ticket.getAuthentication())) {
            return ticket.getAuthentication();
        }
        for (final Authentication auth : ticket.getSupplementalAuthentications()) {
            if (policy.isSatisfiedBy(auth)) {
                return auth;
            }
        }
        throw new UnsatisfiedAuthenticationPolicyException(policy);
    }

    /**
     * Ensure that the service is found and enabled in the service registry.
     * @param registeredService the located entry in the registry
     * @param service authenticating service
     * @throws UnauthorizedServiceException
     */
    private void verifyRegisteredServiceProperties(final RegisteredService registeredService, final Service service) {
        if (registeredService == null) {
            final String msg = String.format("ServiceManagement: Unauthorized Service Access. "
                    + "Service [%s] is not found in service registry.", service.getId());
            logger.warn(msg);
            throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, msg);
        }
        if (!registeredService.isEnabled()) {
            final String msg = String.format("ServiceManagement: Unauthorized Service Access. "
                    + "Service %s] is not enabled in service registry.", service.getId());

            logger.warn(msg);
            throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, msg);
        }
    }
}


text:
int main( )
{
//differenece between getch(), getche() and getchar()
char ch ;
printf ("\nPress any key to continue") ;
getch() ; //will not echo the character
printf ("\nType any character") ;
ch = getche( ) ; //will echo the character typed
printf("\nType any character") ;
getchar() ; // will echo character, must be followed by enter key

//difference between scanf() and gets()
char name[10];
printf("\nEnter name ") ;
scanf("%s",name); //will only take one word as input
printf("%s",name);
char footballer[40] ;
puts ("Enter name");
gets(footballer); //will take multi-word comment

//difference between puts() and printf()
puts(footballer); //simpler syntax and have to define the variable type in syntax
printf("%s",name);

}

redpajama_set_name: RedPajamaGithub


text:
package core.discovery;

import java.util.List;

import org.junit.Test;

import core.DBManager;
import core.Endpoint;
import core.Endpoints;
import core.FileManager;
import core.performance.PResult;
import core.performance.PTask;
import core.performance.SpecificPTask;

public class DTaskTEST {

	@Test
	public void test() {
		try {

			Endpoint ep = Endpoints.DBPEDIA;

			DBManager db = new DBManager();
			FileManager fm = new FileManager();

			DTask task = new DTask(ep);
			task.setDBManager(db);
			task.setFileManager(fm);

			task.call();

			List<DResult> r = db.getResults(ep, DResult.class);
			for(DResult rr: r){
				System.out.println(rr);
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}


text:
package ca.corefacility.bioinformatics.irida.config.data;

import java.sql.SQLException;

import javax.sql.DataSource;

import com.github.springtestdbunit.bean.DatabaseConfigBean;
import com.github.springtestdbunit.bean.DatabaseDataSourceConnectionFactoryBean;

import org.dbunit.ext.mysql.MySqlDataTypeFactory;
import org.dbunit.ext.mysql.MySqlMetadataHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Configures dbunit for use with a mariadb/mysql database, for integration testing.
 *
 */
@Configuration
public class IridaDbUnitConfig {

    @Autowired
    private DataSource dataSource;

    @Bean
    public DatabaseDataSourceConnectionFactoryBean dbUnitDatabaseConnection() {
        DatabaseConfigBean bean = new DatabaseConfigBean();
        bean.setDatatypeFactory(new MySqlDataTypeFactory());
        bean.setMetadataHandler(new MySqlMetadataHandler());
        bean.setAllowEmptyFields(true);

        DatabaseDataSourceConnectionFactoryBean dbConnectionFactory = new DatabaseDataSourceConnectionFactoryBean(dataSource);
        dbConnectionFactory.setDatabaseConfig(bean);
        // Need to set schema so that DbUnit does not get ambiguousTableNameException with mysql-connector-java >8
        try {
            String catalog = dataSource.getConnection().getCatalog();
            dbConnectionFactory.setSchema(catalog);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return dbConnectionFactory;
    }

}


text:
<!doctype html>
<html lang="jp">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="background.js"></script>
</head>
<body>
    test
</body>
</html>


text:
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="urn:metadata.tooling.soap.sforce.com" fqn="Einstein_TrainStats">
    <apiVersion>43.0</apiVersion>
    <status>Active</status>
</ApexClass>


text:
package xmlpull

// xgo/xml/xmlpull/minimalDoc_test.go

import (
	"fmt"
	xr "github.com/jddixon/rnglib_go"
	. "gopkg.in/check.v1"
	"io"
	"strings"
)

var _ = fmt.Print

const (
	XML_DECL     = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
	DOCTYPE_DECL = "<!DOCTYPE document PUBLIC \"-//APACHE//DTD Documentation V2.0//EN\" \"http://forrest.apache.org/dtd/document-v20.dtd\">"
	PROLOG_MISC  = "<!-- this is a comment in the prolog -->\n"
	EPILOG_MISC  = "<!-- this is a comment in the epilog -->\n"
	EMPTY_ELM    = "<root/>"
)

func (s *XLSuite) doInitialParse(c *C, input string) (p *Parser) {

	rd := strings.NewReader(input)
	p, err := NewNewParser(rd)
	c.Assert(err, IsNil)
	c.Assert(p, NotNil)
	c.Assert(p.state, Equals, PRE_START_DOC)

	event, err := p.NextToken()
	c.Assert(err, IsNil)
	c.Assert(event, Equals, START_DOCUMENT)
	c.Assert(p.state, Equals, START_STATE)
	return
}

func (s *XLSuite) doParseXmlDecl(c *C, input string) (
	p *Parser, event PullEvent) {

	p = s.doInitialParse(c, input)

	event, err := p.NextToken()
	c.Assert(err, IsNil)

	c.Assert(p.xmlVersion, Equals, "1.0")
	c.Assert(p.xmlEncoding, Equals, "UTF-8")

	return
}

func (s *XLSuite) doParseXmlDeclWithMisc(c *C, input string,
	misc1 []*MiscItem) (p *Parser, event PullEvent) {

	p = s.doInitialParse(c, input)

	//////////////////////////////////////////////////////////
	// THIS IS OUR OWN LOCAL COPY OF THE EVENT, NOT p.curEvent
	//////////////////////////////////////////////////////////
	event, err := p.NextToken()
	c.Assert(err, IsNil)

	c.Assert(p.xmlVersion, Equals, "1.0")
	c.Assert(p.xmlEncoding, Equals, "UTF-8")

	for i := 0; i < len(misc1); i++ {
		// DEBUG
		fmt.Printf("Misc[%d]: event is %s\n",
			i, PULL_EVENT_NAMES[event])
		// END
		misc := misc1[i]
		t := misc._type
		if event != eventForMiscType[t] {
			fmt.Printf(
				"expected event %s for misc type %s but event is %s\n",
				PULL_EVENT_NAMES[eventForMiscType[t]],
				MiscTypeNames[t],
				PULL_EVENT_NAMES[event])
		}
		c.Assert(event, Equals, eventForMiscType[t])
		switch t {
		case MISC_COMMENT:
			c.Assert(string(p.commentChars), Equals, string(misc.body))
		case MISC_PI:
			c.Assert(string(p.piChars), Equals, string(misc.body))
		case MISC_S:
			c.Assert(string(p.text), Equals, string(misc.body))
		}
		event, err = p.NextToken()
	}
	return
}

// Parse a sequence: XmlDecl Misc* (doctypedecl Misc*) EmptyElement Misc*
func (s *XLSuite) doParseBothDecl(c *C, input string) (
	p *Parser, event PullEvent) {

	var err error
	p, event = s.doParseXmlDecl(c, input)

	// we have seen the XmlDecl; now allow zero or more Misc but
	// requuire doctypedecl
	for event != DOCDECL {
		if event == IGNORABLE_WHITESPACE || event == PROCESSING_INSTRUCTION ||
			event == COMMENT {

			event, err = p.NextToken()
		} else {
			fmt.Printf("expected DOCDECL but got %s\n", PULL_EVENT_NAMES[event])
		}
	}
	c.Assert(event, Equals, DOCDECL)

	event, err = p.NextToken()
	c.Assert(err, IsNil)

	// Allow zero or more Misc but require the EmptyElement
	for event != START_TAG {
		if event == IGNORABLE_WHITESPACE || event == PROCESSING_INSTRUCTION ||
			event == COMMENT {

			event, err = p.NextToken()
		} else {
			fmt.Printf("expected START_TAG but got %s\n", PULL_EVENT_NAMES[event])
			break // XXX SHOULD FAIL
		}
	}
	c.Assert(err, IsNil)
	c.Assert(event, Equals, START_TAG)

	// allow any arbitrary number of Misc
	event, err = p.NextToken()
	// DEBUG
	fmt.Printf("DoParseBothDecl: NextToken => event %s, err %v\n",
		PULL_EVENT_NAMES[event], err)
	// END
	c.Assert(err == nil || err == io.EOF, Equals, true)
	fmt.Printf("err: %v\n", err)
	for event == IGNORABLE_WHITESPACE ||
		event == PROCESSING_INSTRUCTION || event == COMMENT {

		event, err = p.NextToken()
		// DEBUG
		fmt.Printf("DoParseBothDecl: NextToken => event %s, err %v\n",
			PULL_EVENT_NAMES[event], err)
		// END
		c.Assert(err == nil || err == io.EOF, Equals, true)
		fmt.Printf("err: %v\n", err)
	}
	c.Assert(event, Equals, END_DOCUMENT)
	return
}

func (s *XLSuite) TestParseEmptyElm(c *C) {
	if VERBOSITY > 0 {
		fmt.Println("\nTEST_PARSE_EMPTY_ELM")
	}
	s.doInitialParse(c, EMPTY_ELM)
}

func (s *XLSuite) TestParseXmlDeclPlusElm(c *C) {
	if VERBOSITY > 0 {
		fmt.Println("\nTEST_PARSE_XML_DECL_PLUS_ELM")
	}
	s.doParseXmlDecl(c, XML_DECL+EMPTY_ELM)
}

// Parse an XmlDecl followed by an (empty) element followed by Misc
func (s *XLSuite) TestParseXmlDeclPlusElmPlusMisc(c *C) {
	if VERBOSITY > 0 {
		fmt.Println("\nTEST_PARSE_XML_DECL_PLUS_ELM_PLUS_MISC")
	}
	rng := xr.MakeSimpleRNG()
	misc1 := s.createMiscItems(rng) // a small, possibly empty, slice
	miscN := s.createMiscItems(rng) // a small, possibly empty, slice
	s.doParseXmlDeclWithMisc(c, XML_DECL+s.textFromMISlice(misc1)+
		EMPTY_ELM+s.textFromMISlice(miscN), misc1)
}

func (s *XLSuite) TestParseBothDeclPlusElm(c *C) {
	if VERBOSITY > 0 {
		fmt.Println("\nTEST_PARSE_BOTH_DECL_PLUS_ELM")
	}
	s.doParseBothDecl(c, XML_DECL+DOCTYPE_DECL+EMPTY_ELM)
}

// Parse an XmlDecl followed a DocDecl followed by an (empty) element followed
// by Misc
// [1]  document ::= prolog element Misc*
// [22] prolog ::= XMLDecl? Misc* (doctypedecl Misc*)?
//
func (s *XLSuite) TestParseBothDeclPlusElmPlusMisc(c *C) {
	if VERBOSITY > 0 {
		fmt.Println("\nTEST_PARSE_BOTH_DECL_PLUS_ELM_PLUS_MISC")
	}
	rng := xr.MakeSimpleRNG()
	misc1 := s.createMiscItems(rng) // a small, possibly empty, slice
	misc2 := s.createMiscItems(rng) // a small, possibly empty, slice
	miscN := s.createMiscItems(rng) // a small, possibly empty, slice
	s.doParseBothDecl(c,
		XML_DECL+s.textFromMISlice(misc1)+
			DOCTYPE_DECL+s.textFromMISlice(misc2)+
			EMPTY_ELM+s.textFromMISlice(miscN))
}

// Simple test that constants and their string representations agree.
//
func (s *XLSuite) TestParserConst(c *C) {
	c.Assert(PARSER_STATE_NAMES[PRE_START_DOC], Equals, "PRE_START_DOC")
	c.Assert(PARSER_STATE_NAMES[START_ROOT_SEEN], Equals, "START_ROOT_SEEN")
	c.Assert(PARSER_STATE_NAMES[PAST_END_DOC], Equals, "PAST_END_DOC")
}


text:
<?php

namespace Nestor\Events;

abstract class Event
{
    //
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.centurylink.mdw.hub.servlet Class Hierarchy (MDW 6 API JavaDocs)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package com.centurylink.mdw.hub.servlet

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

com.centurylink.mdw.hub.servlet.AccessFilter (implements javax.servlet.Filter)

com.centurylink.mdw.hub.servlet.CustomContentFilter (implements javax.servlet.Filter)

javax.servlet.GenericServlet (implements java.io.Serializable, javax.servlet.Servlet, javax.servlet.ServletConfig)

javax.servlet.http.HttpServlet

com.centurylink.mdw.hub.servlet.AssetContentServlet

com.centurylink.mdw.hub.servlet.TestCaseServlet

com.centurylink.mdw.hub.servlet.AttachmentServlet

com.centurylink.mdw.hub.servlet.CustomContentServlet

com.centurylink.mdw.hub.servlet.ErrorServlet

com.centurylink.mdw.hub.servlet.JsxServlet

com.centurylink.mdw.hub.servlet.LoginServlet

com.centurylink.mdw.hub.servlet.NotFoundServlet

com.centurylink.mdw.hub.servlet.RootServlet

com.centurylink.mdw.hub.servlet.ServiceApiServlet

com.centurylink.mdw.hub.servlet.ServiceServlet

com.centurylink.mdw.hub.servlet.RestServlet

com.centurylink.mdw.hub.servlet.SoapServlet

com.centurylink.mdw.hub.servlet.TemplateServlet

com.centurylink.mdw.hub.servlet.RootFilter (implements javax.servlet.Filter)

com.centurylink.mdw.hub.servlet.StatusResponder

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2019 CenturyLink, Inc.


text:
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Util;
using org.apache.lucene.analysis.shingle;
using org.apache.lucene.analysis.standard;

namespace Lucene.Net.Analysis.Shingle
{

	/// <summary>
	/// A ShingleAnalyzerWrapper wraps a <seealso cref="ShingleFilter"/> around another <seealso cref="Analyzer"/>.
	/// <para>
	/// A shingle is another name for a token based n-gram.
	/// </para>
	/// </summary>
	public sealed class ShingleAnalyzerWrapper : AnalyzerWrapper
	{

	  private readonly Analyzer @delegate;
	  private readonly int maxShingleSize;
	  private readonly int minShingleSize;
	  private readonly string tokenSeparator;
	  private readonly bool outputUnigrams;
	  private readonly bool outputUnigramsIfNoShingles;
	  private readonly string fillerToken;

	  public ShingleAnalyzerWrapper(Analyzer defaultAnalyzer) : this(defaultAnalyzer, ShingleFilter.DEFAULT_MAX_SHINGLE_SIZE)
	  {
	  }

	  public ShingleAnalyzerWrapper(Analyzer defaultAnalyzer, int maxShingleSize) : this(defaultAnalyzer, ShingleFilter.DEFAULT_MIN_SHINGLE_SIZE, maxShingleSize)
	  {
	  }

	  public ShingleAnalyzerWrapper(Analyzer defaultAnalyzer, int minShingleSize, int maxShingleSize) : this(defaultAnalyzer, minShingleSize, maxShingleSize, ShingleFilter.DEFAULT_TOKEN_SEPARATOR, true, false, ShingleFilter.DEFAULT_FILLER_TOKEN)
	  {
	  }

	  /// <summary>
	  /// Creates a new ShingleAnalyzerWrapper
	  /// </summary>
	  /// <param name="delegate"> Analyzer whose TokenStream is to be filtered </param>
	  /// <param name="minShingleSize"> Min shingle (token ngram) size </param>
	  /// <param name="maxShingleSize"> Max shingle size </param>
	  /// <param name="tokenSeparator"> Used to separate input stream tokens in output shingles </param>
	  /// <param name="outputUnigrams"> Whether or not the filter shall pass the original
	  ///        tokens to the output stream </param>
	  /// <param name="outputUnigramsIfNoShingles"> Overrides the behavior of outputUnigrams==false for those
	  ///        times when no shingles are available (because there are fewer than
	  ///        minShingleSize tokens in the input stream)?
	  ///        Note that if outputUnigrams==true, then unigrams are always output,
	  ///        regardless of whether any shingles are available. </param>
	  /// <param name="fillerToken"> filler token to use when positionIncrement is more than 1 </param>
	  public ShingleAnalyzerWrapper(Analyzer @delegate, int minShingleSize, int maxShingleSize, string tokenSeparator, bool outputUnigrams, bool outputUnigramsIfNoShingles, string fillerToken) : base(@delegate.ReuseStrategy)
	  {
		this.@delegate = @delegate;

		if (maxShingleSize < 2)
		{
		  throw new System.ArgumentException("Max shingle size must be >= 2");
		}
		this.maxShingleSize = maxShingleSize;

		if (minShingleSize < 2)
		{
		  throw new System.ArgumentException("Min shingle size must be >= 2");
		}
		if (minShingleSize > maxShingleSize)
		{
		  throw new System.ArgumentException("Min shingle size must be <= max shingle size");
		}
		this.minShingleSize = minShingleSize;

		this.tokenSeparator = (tokenSeparator == null ? "" : tokenSeparator);
		this.outputUnigrams = outputUnigrams;
		this.outputUnigramsIfNoShingles = outputUnigramsIfNoShingles;
		this.fillerToken = fillerToken;
	  }

	  /// <summary>
	  /// Wraps <seealso cref="StandardAnalyzer"/>.
	  /// </summary>
	  public ShingleAnalyzerWrapper(LuceneVersion matchVersion) : this(matchVersion, ShingleFilter.DEFAULT_MIN_SHINGLE_SIZE, ShingleFilter.DEFAULT_MAX_SHINGLE_SIZE)
	  {
	  }

	  /// <summary>
	  /// Wraps <seealso cref="StandardAnalyzer"/>.
	  /// </summary>
	  public ShingleAnalyzerWrapper(LuceneVersion matchVersion, int minShingleSize, int maxShingleSize) : this(new StandardAnalyzer(matchVersion), minShingleSize, maxShingleSize)
	  {
	  }

	  /// <summary>
	  /// The max shingle (token ngram) size
	  /// </summary>
	  /// <returns> The max shingle (token ngram) size </returns>
	  public int MaxShingleSize
	  {
		  get
		  {
			return maxShingleSize;
		  }
	  }

	  /// <summary>
	  /// The min shingle (token ngram) size
	  /// </summary>
	  /// <returns> The min shingle (token ngram) size </returns>
	  public int MinShingleSize
	  {
		  get
		  {
			return minShingleSize;
		  }
	  }

	  public string TokenSeparator
	  {
		  get
		  {
			return tokenSeparator;
		  }
	  }

	  public bool OutputUnigrams
	  {
		  get
		  {
			return outputUnigrams;
		  }
	  }

	  public bool OutputUnigramsIfNoShingles
	  {
		  get
		  {
			return outputUnigramsIfNoShingles;
		  }
	  }

	  public string FillerToken
	  {
		  get
		  {
			return fillerToken;
		  }
	  }

	  public override Analyzer getWrappedAnalyzer(string fieldName)
	  {
		return @delegate;
	  }

	  protected internal override TokenStreamComponents wrapComponents(string fieldName, TokenStreamComponents components)
	  {
		ShingleFilter filter = new ShingleFilter(components.TokenStream, minShingleSize, maxShingleSize);
		filter.MinShingleSize = minShingleSize;
		filter.MaxShingleSize = maxShingleSize;
		filter.TokenSeparator = tokenSeparator;
		filter.OutputUnigrams = outputUnigrams;
		filter.OutputUnigramsIfNoShingles = outputUnigramsIfNoShingles;
		filter.FillerToken = fillerToken;
		return new TokenStreamComponents(components.Tokenizer, filter);
	  }
	}

}


text:
namespace {

// Helper class which expects a check to fire with a certain location and
// message before the end of the current scope.
class ScopedCheckExpectation {
 public:
  ScopedCheckExpectation(const char* file, int line, std::string msg)
      : file_(file),
        line_(line),
        msg_(msg),
        assert_handler_(base::BindRepeating(&ScopedCheckExpectation::Check,
                                            base::Unretained(this))),
        fired_(false) {}
  ~ScopedCheckExpectation() {
    EXPECT_TRUE(fired_) << "CHECK at " << file_ << ":" << line_
                        << " never fired!";
  }

 private:
  void Check(const char* file,
             int line,
             const base::StringPiece msg,
             const base::StringPiece stack) {
    fired_ = true;
    EXPECT_EQ(file, file_);
    EXPECT_EQ(line, line_);
    if (msg_.find("=~") == 0) {
      EXPECT_THAT(std::string(msg), testing::MatchesRegex(msg_.substr(2)));
    } else {
      EXPECT_EQ(std::string(msg), msg_);
    }
  }

  std::string file_;
  int line_;
  std::string msg_;
  logging::ScopedLogAssertHandler assert_handler_;
  bool fired_;
};

// Macro which expects a CHECK to fire with a certain message. If msg starts
// with "=~", it's interpreted as a regular expression.
// Example: EXPECT_CHECK("Check failed: false.", CHECK(false));
#if defined(OFFICIAL_BUILD) && defined(NDEBUG)
#define EXPECT_CHECK(msg, check_expr) \
  do {                                \
    EXPECT_CHECK_DEATH(check_expr);   \
  } while (0)
#else
#define EXPECT_CHECK(msg, check_expr)                          \
  do {                                                         \
    ScopedCheckExpectation check_exp(__FILE__, __LINE__, msg); \
    check_expr;                                                \
  } while (0)
#endif

// Macro which expects a DCHECK to fire if DCHECKs are enabled.
#define EXPECT_DCHECK(msg, check_expr)                                         \
  do {                                                                         \
    if (DCHECK_IS_ON() && logging::LOGGING_DCHECK == logging::LOGGING_FATAL) { \
      ScopedCheckExpectation check_exp(__FILE__, __LINE__, msg);               \
      check_expr;                                                              \
    } else {                                                                   \
      check_expr;                                                              \
    }                                                                          \
  } while (0)

class CheckTest : public testing::Test {};

TEST_F(CheckTest, Basics) {
  EXPECT_CHECK("Check failed: false. ", CHECK(false));

  EXPECT_CHECK("Check failed: false. foo", CHECK(false) << "foo");

  double a = 2, b = 1;
  EXPECT_CHECK("Check failed: a < b (2.000000 vs. 1.000000)", CHECK_LT(a, b));

  EXPECT_CHECK("Check failed: a < b (2.000000 vs. 1.000000)foo",
               CHECK_LT(a, b) << "foo");
}

TEST_F(CheckTest, PCheck) {
  const char file[] = "/nonexistentfile123";
  ignore_result(fopen(file, "r"));
  std::string err =
      logging::SystemErrorCodeToString(logging::GetLastSystemErrorCode());

  EXPECT_CHECK(
      "Check failed: fopen(file, \"r\") != nullptr."
      " : " +
          err,
      PCHECK(fopen(file, "r") != nullptr));

  EXPECT_CHECK(
      "Check failed: fopen(file, \"r\") != nullptr."
      " foo: " +
          err,
      PCHECK(fopen(file, "r") != nullptr) << "foo");

  EXPECT_DCHECK(
      "Check failed: fopen(file, \"r\") != nullptr."
      " : " +
          err,
      DPCHECK(fopen(file, "r") != nullptr));

  EXPECT_DCHECK(
      "Check failed: fopen(file, \"r\") != nullptr."
      " foo: " +
          err,
      DPCHECK(fopen(file, "r") != nullptr) << "foo");
}

TEST_F(CheckTest, CheckOp) {
  int a = 1, b = 2;
  // clang-format off
  EXPECT_CHECK("Check failed: a == b (1 vs. 2)", CHECK_EQ(a, b));
  EXPECT_CHECK("Check failed: a != a (1 vs. 1)", CHECK_NE(a, a));
  EXPECT_CHECK("Check failed: b <= a (2 vs. 1)", CHECK_LE(b, a));
  EXPECT_CHECK("Check failed: b < a (2 vs. 1)",  CHECK_LT(b, a));
  EXPECT_CHECK("Check failed: a >= b (1 vs. 2)", CHECK_GE(a, b));
  EXPECT_CHECK("Check failed: a > b (1 vs. 2)",  CHECK_GT(a, b));

  EXPECT_DCHECK("Check failed: a == b (1 vs. 2)", DCHECK_EQ(a, b));
  EXPECT_DCHECK("Check failed: a != a (1 vs. 1)", DCHECK_NE(a, a));
  EXPECT_DCHECK("Check failed: b <= a (2 vs. 1)", DCHECK_LE(b, a));
  EXPECT_DCHECK("Check failed: b < a (2 vs. 1)",  DCHECK_LT(b, a));
  EXPECT_DCHECK("Check failed: a >= b (1 vs. 2)", DCHECK_GE(a, b));
  EXPECT_DCHECK("Check failed: a > b (1 vs. 2)",  DCHECK_GT(a, b));
  // clang-format on
}

TEST_F(CheckTest, CheckStreamsAreLazy) {
  int called_count = 0;
  int not_called_count = 0;

  auto Called = [&]() {
    ++called_count;
    return 42;
  };
  auto NotCalled = [&]() {
    ++not_called_count;
    return 42;
  };

  CHECK(Called()) << NotCalled();
  CHECK_EQ(Called(), Called()) << NotCalled();
  PCHECK(Called()) << NotCalled();

  DCHECK(Called()) << NotCalled();
  DCHECK_EQ(Called(), Called()) << NotCalled();
  DPCHECK(Called()) << NotCalled();

  EXPECT_EQ(not_called_count, 0);
#if DCHECK_IS_ON()
  EXPECT_EQ(called_count, 8);
#else
  EXPECT_EQ(called_count, 4);
#endif
}

void DcheckEmptyFunction1() {
  // Provide a body so that Release builds do not cause the compiler to
  // optimize DcheckEmptyFunction1 and DcheckEmptyFunction2 as a single
  // function, which breaks the Dcheck tests below.
  LOG(INFO) << "DcheckEmptyFunction1";
}
void DcheckEmptyFunction2() {}

#if defined(DCHECK_IS_CONFIGURABLE)
class ScopedDcheckSeverity {
 public:
  ScopedDcheckSeverity(logging::LogSeverity new_severity)
      : old_severity_(logging::LOGGING_DCHECK) {
    logging::LOGGING_DCHECK = new_severity;
  }

  ~ScopedDcheckSeverity() { logging::LOGGING_DCHECK = old_severity_; }

 private:
  logging::LogSeverity old_severity_;
};
#endif  // defined(DCHECK_IS_CONFIGURABLE)

// https://crbug.com/709067 tracks test flakiness on iOS.
#if defined(OS_IOS)
#define MAYBE_Dcheck DISABLED_Dcheck
#else
#define MAYBE_Dcheck Dcheck
#endif
TEST_F(CheckTest, MAYBE_Dcheck) {
#if defined(DCHECK_IS_CONFIGURABLE)
  // DCHECKs are enabled, and LOGGING_DCHECK is mutable, but defaults to
  // non-fatal. Set it to LOGGING_FATAL to get the expected behavior from the
  // rest of this test.
  ScopedDcheckSeverity dcheck_severity(logging::LOGGING_FATAL);
#endif  // defined(DCHECK_IS_CONFIGURABLE)

#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
  // Release build.
  EXPECT_FALSE(DCHECK_IS_ON());
  EXPECT_FALSE(DLOG_IS_ON(DCHECK));
#elif defined(NDEBUG) && defined(DCHECK_ALWAYS_ON)
  // Release build with real DCHECKS.
  EXPECT_TRUE(DCHECK_IS_ON());
  EXPECT_TRUE(DLOG_IS_ON(DCHECK));
#else
  // Debug build.
  EXPECT_TRUE(DCHECK_IS_ON());
  EXPECT_TRUE(DLOG_IS_ON(DCHECK));
#endif

  EXPECT_DCHECK("Check failed: false. ", DCHECK(false));
  std::string err =
      logging::SystemErrorCodeToString(logging::GetLastSystemErrorCode());
  EXPECT_DCHECK("Check failed: false. : " + err, DPCHECK(false));
  EXPECT_DCHECK("Check failed: 0 == 1 (0 vs. 1)", DCHECK_EQ(0, 1));

  // Test DCHECK on std::nullptr_t
  const void* p_null = nullptr;
  const void* p_not_null = &p_null;
  DCHECK_EQ(p_null, nullptr);
  DCHECK_EQ(nullptr, p_null);
  DCHECK_NE(p_not_null, nullptr);
  DCHECK_NE(nullptr, p_not_null);

  // Test DCHECK on a scoped enum.
  enum class Animal { DOG, CAT };
  DCHECK_EQ(Animal::DOG, Animal::DOG);
  EXPECT_DCHECK("Check failed: Animal::DOG == Animal::CAT (0 vs. 1)",
                DCHECK_EQ(Animal::DOG, Animal::CAT));

  // Test DCHECK on functions and function pointers.
  struct MemberFunctions {
    void MemberFunction1() {
      // See the comment in DcheckEmptyFunction1().
      LOG(INFO) << "Do not merge with MemberFunction2.";
    }
    void MemberFunction2() {}
  };
  void (MemberFunctions::*mp1)() = &MemberFunctions::MemberFunction1;
  void (MemberFunctions::*mp2)() = &MemberFunctions::MemberFunction2;
  void (*fp1)() = DcheckEmptyFunction1;
  void (*fp2)() = DcheckEmptyFunction2;
  void (*fp3)() = DcheckEmptyFunction1;
  DCHECK_EQ(fp1, fp3);
  DCHECK_EQ(mp1, &MemberFunctions::MemberFunction1);
  DCHECK_EQ(mp2, &MemberFunctions::MemberFunction2);
  EXPECT_DCHECK("=~Check failed: fp1 == fp2 \\(\\w+ vs. \\w+\\)",
                DCHECK_EQ(fp1, fp2));
  EXPECT_DCHECK(
      "Check failed: mp2 == &MemberFunctions::MemberFunction1 (1 vs. 1)",
      DCHECK_EQ(mp2, &MemberFunctions::MemberFunction1));
}

TEST_F(CheckTest, DcheckReleaseBehavior) {
  int var1 = 1;
  int var2 = 2;
  int var3 = 3;
  int var4 = 4;

  // No warnings about unused variables even though no check fires and DCHECK
  // may or may not be enabled.
  DCHECK(var1) << var2;
  DPCHECK(var1) << var3;
  DCHECK_EQ(var1, 1) << var4;
}

TEST_F(CheckTest, DCheckEqStatements) {
  bool reached = false;
  if (false)
    DCHECK_EQ(false, true);  // Unreached.
  else
    DCHECK_EQ(true, reached = true);  // Reached, passed.
  ASSERT_EQ(DCHECK_IS_ON() ? true : false, reached);

  if (false)
    DCHECK_EQ(false, true);  // Unreached.
}

TEST_F(CheckTest, CheckEqStatements) {
  bool reached = false;
  if (false)
    CHECK_EQ(false, true);  // Unreached.
  else
    CHECK_EQ(true, reached = true);  // Reached, passed.
  ASSERT_TRUE(reached);

  if (false)
    CHECK_EQ(false, true);  // Unreached.
}

#if defined(DCHECK_IS_CONFIGURABLE)
TEST_F(CheckTest, ConfigurableDCheck) {
  // Verify that DCHECKs default to non-fatal in configurable-DCHECK builds.
  // Note that we require only that DCHECK is non-fatal by default, rather
  // than requiring that it be exactly INFO, ERROR, etc level.
  EXPECT_LT(logging::LOGGING_DCHECK, logging::LOGGING_FATAL);
  DCHECK(false);

  // Verify that DCHECK* aren't hard-wired to crash on failure.
  logging::LOGGING_DCHECK = logging::LOG_INFO;
  DCHECK(false);
  DCHECK_EQ(1, 2);

  // Verify that DCHECK does crash if LOGGING_DCHECK is set to LOGGING_FATAL.
  logging::LOGGING_DCHECK = logging::LOGGING_FATAL;
  EXPECT_CHECK("Check failed: false. ", DCHECK(false));
  EXPECT_CHECK("Check failed: 1 == 2 (1 vs. 2)", DCHECK_EQ(1, 2));
}

TEST_F(CheckTest, ConfigurableDCheckFeature) {
  // Initialize FeatureList with and without DcheckIsFatal, and verify the
  // value of LOGGING_DCHECK. Note that we don't require that DCHECK take a
  // specific value when the feature is off, only that it is non-fatal.

  {
    base::test::ScopedFeatureList feature_list;
    feature_list.InitFromCommandLine("DcheckIsFatal", "");
    EXPECT_EQ(logging::LOGGING_DCHECK, logging::LOGGING_FATAL);
  }

  {
    base::test::ScopedFeatureList feature_list;
    feature_list.InitFromCommandLine("", "DcheckIsFatal");
    EXPECT_LT(logging::LOGGING_DCHECK, logging::LOGGING_FATAL);
  }

  // The default case is last, so we leave LOGGING_DCHECK in the default state.
  {
    base::test::ScopedFeatureList feature_list;
    feature_list.InitFromCommandLine("", "");
    EXPECT_LT(logging::LOGGING_DCHECK, logging::LOGGING_FATAL);
  }
}
#endif  // defined(DCHECK_IS_CONFIGURABLE)

struct StructWithOstream {
  bool operator==(const StructWithOstream& o) const { return &o == this; }
};
#if !(defined(OFFICIAL_BUILD) && defined(NDEBUG))
std::ostream& operator<<(std::ostream& out, const StructWithOstream&) {
  return out << "ostream";
}
#endif

struct StructWithToString {
  bool operator==(const StructWithToString& o) const { return &o == this; }
  std::string ToString() const { return "ToString"; }
};

struct StructWithToStringAndOstream {
  bool operator==(const StructWithToStringAndOstream& o) const {
    return &o == this;
  }
  std::string ToString() const { return "ToString"; }
};
#if !(defined(OFFICIAL_BUILD) && defined(NDEBUG))
std::ostream& operator<<(std::ostream& out,
                         const StructWithToStringAndOstream&) {
  return out << "ostream";
}
#endif

struct StructWithToStringNotStdString {
  struct PseudoString {};

  bool operator==(const StructWithToStringNotStdString& o) const {
    return &o == this;
  }
  PseudoString ToString() const { return PseudoString(); }
};
#if !(defined(OFFICIAL_BUILD) && defined(NDEBUG))
std::ostream& operator<<(std::ostream& out,
                         const StructWithToStringNotStdString::PseudoString&) {
  return out << "ToString+ostream";
}
#endif

TEST_F(CheckTest, OstreamVsToString) {
  StructWithOstream a, b;
  EXPECT_CHECK("Check failed: a == b (ostream vs. ostream)", CHECK_EQ(a, b));

  StructWithToString c, d;
  EXPECT_CHECK("Check failed: c == d (ToString vs. ToString)", CHECK_EQ(c, d));

  StructWithToStringAndOstream e, f;
  EXPECT_CHECK("Check failed: e == f (ostream vs. ostream)", CHECK_EQ(e, f));

  StructWithToStringNotStdString g, h;
  EXPECT_CHECK("Check failed: g == h (ToString+ostream vs. ToString+ostream)",
               CHECK_EQ(g, h));
}

#define EXPECT_LOG_ERROR(msg, expr, expected_line)                             \
  do {                                                                         \
    static bool got_log_message = false;                                       \
    ASSERT_EQ(logging::GetLogMessageHandler(), nullptr);                       \
    logging::SetLogMessageHandler([](int severity, const char* file, int line, \
                                     size_t message_start,                     \
                                     const std::string& str) {                 \
      EXPECT_FALSE(got_log_message);                                           \
      got_log_message = true;                                                  \
      EXPECT_EQ(severity, logging::LOG_ERROR);                                 \
      EXPECT_EQ(str.substr(message_start), (msg));                             \
      EXPECT_STREQ(__FILE__, file);                                            \
      EXPECT_EQ(expected_line, line);                                          \
      return true;                                                             \
    });                                                                        \
    expr;                                                                      \
    EXPECT_TRUE(got_log_message);                                              \
    logging::SetLogMessageHandler(nullptr);                                    \
  } while (0)

#define EXPECT_NO_LOG(expr)                                                    \
  do {                                                                         \
    ASSERT_EQ(logging::GetLogMessageHandler(), nullptr);                       \
    logging::SetLogMessageHandler([](int severity, const char* file, int line, \
                                     size_t message_start,                     \
                                     const std::string& str) {                 \
      EXPECT_TRUE(false) << "Unexpected log: " << str;                         \
      return true;                                                             \
    });                                                                        \
    expr;                                                                      \
    logging::SetLogMessageHandler(nullptr);                                    \
  } while (0)

TEST_F(CheckTest, NotReached) {
#if BUILDFLAG(ENABLE_LOG_ERROR_NOT_REACHED)
  // Expect LOG(ERROR) without the streamed params.
  EXPECT_LOG_ERROR("NOTREACHED() hit.\n", NOTREACHED() << "foo", __LINE__);
#else
  // Expect a DCHECK with streamed params intact.
  EXPECT_DCHECK("Check failed: false. foo", NOTREACHED() << "foo");
#endif
}

TEST_F(CheckTest, NotImplemented) {
  static const std::string expected_msg =
      std::string("Not implemented reached in ") + __PRETTY_FUNCTION__;

#if DCHECK_IS_ON()
  // Expect LOG(ERROR) with streamed params intact.
  EXPECT_LOG_ERROR(expected_msg + "foo\n", NOTIMPLEMENTED() << "foo", __LINE__);
#else
  // Expect nothing.
  EXPECT_NO_LOG(NOTIMPLEMENTED() << "foo");
#endif
}

void NiLogOnce() {
  // Note: The stream param is not logged.
  NOTIMPLEMENTED_LOG_ONCE() << "foo";
}

TEST_F(CheckTest, NotImplementedLogOnce) {
  static const std::string expected_msg =
      "Not implemented reached in void (anonymous namespace)::NiLogOnce()\n";

#if DCHECK_IS_ON()
  EXPECT_LOG_ERROR(expected_msg, NiLogOnce(), __LINE__ - 8);
  EXPECT_NO_LOG(NiLogOnce());
#else
  EXPECT_NO_LOG(NiLogOnce());
  EXPECT_NO_LOG(NiLogOnce());
#endif
}

}  // namespace


text:
package com.starjobs.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.starjobs.mapper.ChargeActivityMapper;
import com.starjobs.pojo.ChargeActivity;
import com.starjobs.pojo.ChargeActivityExample;
import com.starjobs.service.ChargeActivityService;

@Service
public class ChargeActivityServiceImpl implements ChargeActivityService {
	@Autowired
	private ChargeActivityMapper chargeActivityMapper;

	@Override
	public Map<String, Object> getChargeActivityList() {
		Map<String,Object> resultMap = new HashMap<String,Object>(2);
		ChargeActivityExample example = new ChargeActivityExample();
		example.createCriteria();
		List<ChargeActivity>activityList = chargeActivityMapper.selectByExample(example);
		resultMap.put("activityList", activityList);
		return resultMap;
	}

}


text:
package net.md_5.bungee.protocol.packet;

import io.netty.buffer.ByteBuf;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;

@Getter
@ToString
@EqualsAndHashCode(callSuper = false)
public class PacketD1Team extends DefinedPacket
{

    private String name;
    /**
     * 0 - create, 1 remove, 2 info update, 3 player add, 4 player remove.
     */
    private byte mode;
    private String displayName;
    private String prefix;
    private String suffix;
    private boolean friendlyFire;
    private short playerCount;
    private String[] players;

    private PacketD1Team()
    {
        super( 0xD1 );
    }

    /**
     * Packet to destroy a team.
     *
     * @param name
     */
    public PacketD1Team(String name)
    {
        this();
        this.name = name;
        this.mode = 1;
    }

    @Override
    public void read(ByteBuf buf)
    {
        name = readString( buf );
        mode = buf.readByte();
        if ( mode == 0 || mode == 2 )
        {
            displayName = readString( buf );
            prefix = readString( buf );
            suffix = readString( buf );
            friendlyFire = buf.readBoolean();
        }
        if ( mode == 0 || mode == 3 || mode == 4 )
        {
            players = new String[ buf.readShort() ];
            for ( int i = 0; i < getPlayers().length; i++ )
            {
                players[i] = readString( buf );
            }
        }
    }

    @Override
    public void write(ByteBuf buf)
    {
        writeString( name, buf );
        buf.writeByte( mode );
        if ( mode == 0 || mode == 2 )
        {
            writeString( displayName, buf );
            writeString( prefix, buf );
            writeString( suffix, buf );
            buf.writeBoolean( friendlyFire );
        }
        if ( mode == 0 || mode == 3 || mode == 4 )
        {
            buf.writeShort( players.length );
            for ( int i = 0; i < players.length; i++ )
            {
                writeString( players[i], buf );
            }
        }
    }

    @Override
    public void handle(AbstractPacketHandler handler) throws Exception
    {
        handler.handle( this );
    }
}


text:
/**
 * Generated with Acceleo
 */
package org.wso2.developerstudio.eclipse.gmf.esb.parts.forms;

// Start of user code for imports
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.Enumerator;

import org.eclipse.emf.ecore.util.EcoreAdapterFactory;

import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;

import org.eclipse.emf.eef.runtime.EEFRuntimePlugin;

import org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent;

import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent;

import org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart;

import org.eclipse.emf.eef.runtime.impl.notify.PropertiesEditionEvent;

import org.eclipse.emf.eef.runtime.part.impl.SectionPropertiesEditingPart;

import org.eclipse.emf.eef.runtime.ui.parts.PartComposer;

import org.eclipse.emf.eef.runtime.ui.parts.sequence.BindingCompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionStep;

import org.eclipse.emf.eef.runtime.ui.utils.EditingUtils;

import org.eclipse.emf.eef.runtime.ui.widgets.EEFFeatureEditorDialog;
import org.eclipse.emf.eef.runtime.ui.widgets.EMFComboViewer;
import org.eclipse.emf.eef.runtime.ui.widgets.FormUtils;

import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;

import org.eclipse.jface.window.Window;

import org.eclipse.swt.SWT;

import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;

import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;

import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;

import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage;

import org.wso2.developerstudio.eclipse.gmf.esb.parts.EsbViewsRepository;
import org.wso2.developerstudio.eclipse.gmf.esb.parts.TransactionMediatorPropertiesEditionPart;
import org.wso2.developerstudio.eclipse.gmf.esb.presentation.EEFPropertyViewUtil;
import org.wso2.developerstudio.eclipse.gmf.esb.providers.EsbMessages;

// End of user code

/**
 *
 * @generated NOT
 */
public class TransactionMediatorPropertiesEditionPartForm extends SectionPropertiesEditingPart implements IFormPropertiesEditionPart, TransactionMediatorPropertiesEditionPart {

	protected Text description;
	protected Text commentsList;
	protected Button editCommentsList;
	protected EList commentsListList;
	protected Button reverse;
	protected EMFComboViewer action;
    protected Control[] commentsElements;
    protected Control[] reverseElements;
    protected Composite propertiesGroup;

	/**
	 * For {@link ISection} use only.
	 */
	public TransactionMediatorPropertiesEditionPartForm() { super(); }

	/**
	 * Default constructor
	 * @param editionComponent the {@link IPropertiesEditionComponent} that manage this part
	 *
	 */
	public TransactionMediatorPropertiesEditionPartForm(IPropertiesEditionComponent editionComponent) {
		super(editionComponent);
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart#
	 *  createFigure(org.eclipse.swt.widgets.Composite, org.eclipse.ui.forms.widgets.FormToolkit)
	 *
	 */
	public Composite createFigure(final Composite parent, final FormToolkit widgetFactory) {
		Form form = widgetFactory.createForm(parent);
		view = form.getBody();
		GridLayout layout = new GridLayout();
		layout.numColumns = 3;
		view.setLayout(layout);
		createControls(widgetFactory, view);
		return form;
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart#
	 *  createControls(org.eclipse.ui.forms.widgets.FormToolkit, org.eclipse.swt.widgets.Composite)
	 *
	 */
	public void createControls(final FormToolkit widgetFactory, Composite view) {
		CompositionSequence transactionMediatorStep = new BindingCompositionSequence(propertiesEditionComponent);
		CompositionStep propertiesStep = transactionMediatorStep.addStep(EsbViewsRepository.TransactionMediator.Properties.class);
		propertiesStep.addStep(EsbViewsRepository.TransactionMediator.Properties.commentsList);
		propertiesStep.addStep(EsbViewsRepository.TransactionMediator.Properties.reverse);
		propertiesStep.addStep(EsbViewsRepository.TransactionMediator.Properties.action);
        propertiesStep.addStep(EsbViewsRepository.TransactionMediator.Properties.description);

		composer = new PartComposer(transactionMediatorStep) {

			@Override
			public Composite addToPart(Composite parent, Object key) {
				if (key == EsbViewsRepository.TransactionMediator.Properties.class) {
					return createPropertiesGroup(widgetFactory, parent);
				}
				if (key == EsbViewsRepository.TransactionMediator.Properties.description) {
					return createDescriptionText(widgetFactory, parent);
				}
				if (key == EsbViewsRepository.TransactionMediator.Properties.commentsList) {
					return createCommentsListMultiValuedEditor(widgetFactory, parent);
				}
				if (key == EsbViewsRepository.TransactionMediator.Properties.reverse) {
					return createReverseCheckbox(widgetFactory, parent);
				}
				if (key == EsbViewsRepository.TransactionMediator.Properties.action) {
					return createActionEMFComboViewer(widgetFactory, parent);
				}
				return parent;
			}
		};
		composer.compose(view);
	}
    /**
     * @generated NOT
     */
	protected Composite createPropertiesGroup(FormToolkit widgetFactory, final Composite parent) {
		Section propertiesSection = widgetFactory.createSection(parent, Section.TITLE_BAR | Section.TWISTIE | Section.EXPANDED);
		propertiesSection.setText(EsbMessages.TransactionMediatorPropertiesEditionPart_PropertiesGroupLabel);
		GridData propertiesSectionData = new GridData(GridData.FILL_HORIZONTAL);
		propertiesSectionData.horizontalSpan = 3;
		propertiesSection.setLayoutData(propertiesSectionData);
		propertiesGroup = widgetFactory.createComposite(propertiesSection);
		GridLayout propertiesGroupLayout = new GridLayout();
		propertiesGroupLayout.numColumns = 3;
		propertiesGroup.setLayout(propertiesGroupLayout);
		propertiesSection.setClient(propertiesGroup);
		return propertiesGroup;
	}

	protected Composite createDescriptionText(FormToolkit widgetFactory, Composite parent) {
		createDescription(parent, EsbViewsRepository.TransactionMediator.Properties.description, EsbMessages.TransactionMediatorPropertiesEditionPart_DescriptionLabel);
		description = widgetFactory.createText(parent, ""); //$NON-NLS-1$
		description.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
		widgetFactory.paintBordersFor(parent);
		GridData descriptionData = new GridData(GridData.FILL_HORIZONTAL);
		description.setLayoutData(descriptionData);
		description.addFocusListener(new FocusAdapter() {
			/**
			 * @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
			 *
			 */
			@Override
			@SuppressWarnings("synthetic-access")
			public void focusLost(FocusEvent e) {
				if (propertiesEditionComponent != null) {
					propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(
							TransactionMediatorPropertiesEditionPartForm.this,
							EsbViewsRepository.TransactionMediator.Properties.description,
							PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, description.getText()));
					propertiesEditionComponent
							.firePropertiesChanged(new PropertiesEditionEvent(
									TransactionMediatorPropertiesEditionPartForm.this,
									EsbViewsRepository.TransactionMediator.Properties.description,
									PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_LOST,
									null, description.getText()));
				}
			}

			/**
			 * @see org.eclipse.swt.events.FocusAdapter#focusGained(org.eclipse.swt.events.FocusEvent)
			 */
			@Override
			public void focusGained(FocusEvent e) {
				if (propertiesEditionComponent != null) {
					propertiesEditionComponent
							.firePropertiesChanged(new PropertiesEditionEvent(
									TransactionMediatorPropertiesEditionPartForm.this,
									null,
									PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_GAINED,
									null, null));
				}
			}
		});
		description.addKeyListener(new KeyAdapter() {
			/**
			 * @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
			 *
			 */
			@Override
			@SuppressWarnings("synthetic-access")
			public void keyPressed(KeyEvent e) {
				if (e.character == SWT.CR) {
					if (propertiesEditionComponent != null)
						propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(TransactionMediatorPropertiesEditionPartForm.this, EsbViewsRepository.TransactionMediator.Properties.description, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, description.getText()));
				}
			}
		});
		EditingUtils.setID(description, EsbViewsRepository.TransactionMediator.Properties.description);
		EditingUtils.setEEFtype(description, "eef::Text"); //$NON-NLS-1$
		FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.TransactionMediator.Properties.description, EsbViewsRepository.FORM_KIND), null); //$NON-NLS-1$
		// Start of user code for createDescriptionText

		// End of user code
		return parent;
	}

    /**
     * @generated NOT
     */
	protected Composite createCommentsListMultiValuedEditor(FormToolkit widgetFactory, Composite parent) {
	    Control [] previousControls = propertiesGroup.getChildren();
        commentsList = widgetFactory.createText(parent, "", SWT.READ_ONLY); //$NON-NLS-1$
		GridData commentsListData = new GridData(GridData.FILL_HORIZONTAL);
		commentsListData.horizontalSpan = 2;
		commentsList.setLayoutData(commentsListData);
		EditingUtils.setID(commentsList, EsbViewsRepository.TransactionMediator.Properties.commentsList);
		EditingUtils.setEEFtype(commentsList, "eef::MultiValuedEditor::field"); //$NON-NLS-1$
		editCommentsList = widgetFactory.createButton(parent, getDescription(EsbViewsRepository.TransactionMediator.Properties.commentsList, EsbMessages.TransactionMediatorPropertiesEditionPart_CommentsListLabel), SWT.NONE);
		GridData editCommentsListData = new GridData();
		editCommentsList.setLayoutData(editCommentsListData);
		editCommentsList.addSelectionListener(new SelectionAdapter() {

			/**
			 * {@inheritDoc}
			 *
			 * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
			 *
			 */
			public void widgetSelected(SelectionEvent e) {
				EEFFeatureEditorDialog dialog = new EEFFeatureEditorDialog(
						commentsList.getShell(), "TransactionMediator", new AdapterFactoryLabelProvider(adapterFactory), //$NON-NLS-1$
						commentsListList, EsbPackage.eINSTANCE.getEsbElement_CommentsList().getEType(), null,
						false, true,
						null, null);
				if (dialog.open() == Window.OK) {
					commentsListList = dialog.getResult();
					if (commentsListList == null) {
						commentsListList = new BasicEList();
					}
					commentsList.setText(commentsListList.toString());
					propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(TransactionMediatorPropertiesEditionPartForm.this, EsbViewsRepository.TransactionMediator.Properties.commentsList, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, new BasicEList(commentsListList)));
					setHasChanged(true);
				}
			}
		});
		EditingUtils.setID(editCommentsList, EsbViewsRepository.TransactionMediator.Properties.commentsList);
		EditingUtils.setEEFtype(editCommentsList, "eef::MultiValuedEditor::browsebutton"); //$NON-NLS-1$
		// Start of user code for createCommentsListMultiValuedEditor
		Control [] newControls = propertiesGroup.getChildren();
        commentsElements = EEFPropertyViewUtil.getTableElements(previousControls, newControls);
        // End of user code
		return parent;
	}

	/**
     * @generated NOT
     */
	protected Composite createReverseCheckbox(FormToolkit widgetFactory, Composite parent) {
	    Control [] previousControls = propertiesGroup.getChildren();
        reverse = widgetFactory.createButton(parent, getDescription(EsbViewsRepository.TransactionMediator.Properties.reverse, EsbMessages.TransactionMediatorPropertiesEditionPart_ReverseLabel), SWT.CHECK);
		reverse.addSelectionListener(new SelectionAdapter() {

			/**
			 * {@inheritDoc}
			 *
			 * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
			 *
			 */
			public void widgetSelected(SelectionEvent e) {
				if (propertiesEditionComponent != null)
					propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(TransactionMediatorPropertiesEditionPartForm.this, EsbViewsRepository.TransactionMediator.Properties.reverse, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, new Boolean(reverse.getSelection())));
			}

		});
		GridData reverseData = new GridData(GridData.FILL_HORIZONTAL);
		reverseData.horizontalSpan = 2;
		reverse.setLayoutData(reverseData);
		EditingUtils.setID(reverse, EsbViewsRepository.TransactionMediator.Properties.reverse);
		EditingUtils.setEEFtype(reverse, "eef::Checkbox"); //$NON-NLS-1$
		FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.TransactionMediator.Properties.reverse, EsbViewsRepository.FORM_KIND), null); //$NON-NLS-1$
		// Start of user code for createReverseCheckbox
        Control [] newControls = propertiesGroup.getChildren();
        reverseElements = EEFPropertyViewUtil.getTableElements(previousControls, newControls);
		// End of user code
		return parent;
	}

	/**
	 * @generated NOT
	 */
	protected Composite createActionEMFComboViewer(FormToolkit widgetFactory, Composite parent) {
		createDescription(parent, EsbViewsRepository.TransactionMediator.Properties.action, EsbMessages.TransactionMediatorPropertiesEditionPart_ActionLabel);
		action = new EMFComboViewer(parent);
		action.setContentProvider(new ArrayContentProvider());
		action.setLabelProvider(new AdapterFactoryLabelProvider(EEFRuntimePlugin.getDefault().getAdapterFactory()));
		GridData actionData = new GridData(GridData.FILL_HORIZONTAL);
		action.getCombo().setLayoutData(actionData);
                action.getCombo().addListener(SWT.MouseVerticalWheel, new Listener() {

                    @Override
                    public void handleEvent(Event arg0) {
                        arg0.doit = false;
                    }
                });
		action.addSelectionChangedListener(new ISelectionChangedListener() {

			/**
			 * {@inheritDoc}
			 *
			 * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
			 *
			 */
			public void selectionChanged(SelectionChangedEvent event) {
				if (propertiesEditionComponent != null)
					propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(TransactionMediatorPropertiesEditionPartForm.this, EsbViewsRepository.TransactionMediator.Properties.action, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, getAction()));
			}

		});
		action.setID(EsbViewsRepository.TransactionMediator.Properties.action);
		FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.TransactionMediator.Properties.action, EsbViewsRepository.FORM_KIND), null); //$NON-NLS-1$
		// Start of user code for createActionEMFComboViewer

		// End of user code
		return parent;
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#firePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent)
	 *
	 */
	public void firePropertiesChanged(IPropertiesEditionEvent event) {
		// Start of user code for tab synchronization

		// End of user code
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.TransactionMediatorPropertiesEditionPart#getDescription()
	 *
	 */
	public String getDescription() {
		return description.getText();
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.TransactionMediatorPropertiesEditionPart#setDescription(String newValue)
	 *
	 */
	public void setDescription(String newValue) {
		if (newValue != null) {
			description.setText(newValue);
		} else {
			description.setText(""); //$NON-NLS-1$
		}
		boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.TransactionMediator.Properties.description);
		if (eefElementEditorReadOnlyState && description.isEnabled()) {
			description.setEnabled(false);
			description.setToolTipText(EsbMessages.TransactionMediator_ReadOnly);
		} else if (!eefElementEditorReadOnlyState && !description.isEnabled()) {
			description.setEnabled(true);
		}

	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.TransactionMediatorPropertiesEditionPart#getCommentsList()
	 *
	 */
	public EList getCommentsList() {
		return commentsListList;
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.TransactionMediatorPropertiesEditionPart#setCommentsList(EList newValue)
	 *
	 */
	public void setCommentsList(EList newValue) {
		commentsListList = newValue;
		if (newValue != null) {
			commentsList.setText(commentsListList.toString());
		} else {
			commentsList.setText(""); //$NON-NLS-1$
		}
		boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.TransactionMediator.Properties.commentsList);
		if (eefElementEditorReadOnlyState && commentsList.isEnabled()) {
			commentsList.setEnabled(false);
			commentsList.setToolTipText(EsbMessages.TransactionMediator_ReadOnly);
		} else if (!eefElementEditorReadOnlyState && !commentsList.isEnabled()) {
			commentsList.setEnabled(true);
		}

	}

	public void addToCommentsList(Object newValue) {
		commentsListList.add(newValue);
		if (newValue != null) {
			commentsList.setText(commentsListList.toString());
		} else {
			commentsList.setText(""); //$NON-NLS-1$
		}
	}

	public void removeToCommentsList(Object newValue) {
		commentsListList.remove(newValue);
		if (newValue != null) {
			commentsList.setText(commentsListList.toString());
		} else {
			commentsList.setText(""); //$NON-NLS-1$
		}
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.TransactionMediatorPropertiesEditionPart#getReverse()
	 *
	 */
	public Boolean getReverse() {
		return Boolean.valueOf(reverse.getSelection());
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.TransactionMediatorPropertiesEditionPart#setReverse(Boolean newValue)
	 *
	 */
	public void setReverse(Boolean newValue) {
		if (newValue != null) {
			reverse.setSelection(newValue.booleanValue());
		} else {
			reverse.setSelection(false);
		}
		boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.TransactionMediator.Properties.reverse);
		if (eefElementEditorReadOnlyState && reverse.isEnabled()) {
			reverse.setEnabled(false);
			reverse.setToolTipText(EsbMessages.TransactionMediator_ReadOnly);
		} else if (!eefElementEditorReadOnlyState && !reverse.isEnabled()) {
			reverse.setEnabled(true);
		}

	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.TransactionMediatorPropertiesEditionPart#getAction()
	 *
	 */
	public Enumerator getAction() {
		Enumerator selection = (Enumerator) ((StructuredSelection) action.getSelection()).getFirstElement();
		return selection;
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.TransactionMediatorPropertiesEditionPart#initAction(Object input, Enumerator current)
	 */
	public void initAction(Object input, Enumerator current) {
		action.setInput(input);
		action.modelUpdating(new StructuredSelection(current));
		boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.TransactionMediator.Properties.action);
		if (eefElementEditorReadOnlyState && action.isEnabled()) {
			action.setEnabled(false);
			action.setToolTipText(EsbMessages.TransactionMediator_ReadOnly);
		} else if (!eefElementEditorReadOnlyState && !action.isEnabled()) {
			action.setEnabled(true);
		}

	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.TransactionMediatorPropertiesEditionPart#setAction(Enumerator newValue)
	 *
	 */
	public void setAction(Enumerator newValue) {
		action.modelUpdating(new StructuredSelection(newValue));
		boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.TransactionMediator.Properties.action);
		if (eefElementEditorReadOnlyState && action.isEnabled()) {
			action.setEnabled(false);
			action.setToolTipText(EsbMessages.TransactionMediator_ReadOnly);
		} else if (!eefElementEditorReadOnlyState && !action.isEnabled()) {
			action.setEnabled(true);
		}

	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart#getTitle()
	 *
	 */
	public String getTitle() {
		return EsbMessages.TransactionMediator_Part_Title;
	}

	// Start of user code additional methods
    @Override
    public void refresh() {
        super.refresh();
        validate();
    }

    public void validate() {
        EEFPropertyViewUtil epv = new EEFPropertyViewUtil(view);
        epv.hideEntry(commentsElements, false);
        epv.hideEntry(reverseElements, false);
        view.layout(true, true);
    }
	// End of user code

}


text:
package sur.snapps.sentoff.api.spending;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import sur.snapps.sentoff.api.JsonReference;
import sur.snapps.sentoff.api.JsonRequest;
import sur.snapps.sentoff.api.store.JsonStoreDetails;
import sur.snapps.sentoff.api.validation.AmountValue;
import sur.snapps.sentoff.api.validation.DateValue;
import sur.snapps.sentoff.api.validation.PresentInDB;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Collections;
import java.util.List;

/**
 * @author rogge
 * @since 26/03/2016.
 */
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class AddSpendingRequest extends JsonRequest {

    @NotNull
    @DateValue
    private String date;
    @NotNull
    @AmountValue
    private String amount;

    @Valid
    @JsonProperty("store")
    private JsonStoreDetails storeDetails;

    @Valid
    @PresentInDB("STORE_LOCATIONS")
    @JsonProperty("storeRef")
    private JsonReference storeReference;

    @Valid
    private List<Payment> payments = Collections.emptyList();

    @Valid
    @JsonProperty("products")
    private List<PurchasedProduct> purchasedProducts = Collections.emptyList();

    public void setAmount(String amount) {
        this.amount = amount;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getAmount() {
        return amount;
    }

    public String getDate() {
        return date;
    }

    public List<Payment> getPayments() {
        return Collections.unmodifiableList(payments);
    }

    public void addPayment(Payment payment) {
        payments.add(payment);
    }

    public List<PurchasedProduct> getPurchasedProducts() {
        return Collections.unmodifiableList(purchasedProducts);
    }

    public void addPurchasedProduct(PurchasedProduct purchasedProduct) {
        purchasedProducts.add(purchasedProduct);
    }

    public JsonStoreDetails getStoreDetails() {
        return storeDetails;
    }

    public void setStoreDetails(JsonStoreDetails storeDetails) {
        this.storeDetails = storeDetails;
    }

    public JsonReference getStoreReference() {
        return storeReference;
    }

    public void setStoreReference(JsonReference storeReference) {
        this.storeReference = storeReference;
    }
}


text:
#ifndef LIBGM_TABLE_BASE_HPP
#define LIBGM_TABLE_BASE_HPP

namespace libgm { namespace experimental {

  /**
   * The base class of all table factor expressions.
   * This class must be specialized for each specific factor class.
   */
  template <typename Space, typename RealType, typename Derived>
  class table_base;

} } // namespace libgm::experimental

#endif


text:
class UsersDataObject < ActiveRecord::Base
  validates_presence_of :user_id, :data_object_id
  validates_uniqueness_of :data_object_id

  has_one :user
  has_one :data_object
end


text:
using System;

namespace MasDev.Common
{
	public interface IExclusiveAccessProvider
	{
		IDisposable StartExclusiveAccess (IIdentifier identifier);
	}

	public interface IIdentifier
	{
		string Identify { get; }
	}
}


text:
// Copyright (c) 2016-2017 Vadim Macagon
// MIT License, see LICENSE file for full terms.

import * as React from 'react';
import { observer } from 'mobx-react';
import { Observable, Subject, Subscription } from '@reactivex/rxjs';
import { IronFlexLayout } from '../styles';
import { stylable, themable } from '../decorators';
import { ILayoutComponent, ILayoutComponentProps } from './layout-container';
import { PanelModel } from './panel-model';
import { PaperToolbarComponent } from '../paper';
import { ContextComponent } from '../context';

/**
 * Container component that displays its content with an optional header.
 */
@stylable
@themable
@observer
export class PanelComponent
       extends ContextComponent<PanelComponent.IProps, void, PanelComponent.IContext>
       implements ILayoutComponent {

  static contextTypes = {
    theme: React.PropTypes.object.isRequired,
    freeStyle: React.PropTypes.object.isRequired,
    renderChild: React.PropTypes.func.isRequired
  };

  private _styleId: string;
  private _className: string;
  private _element: HTMLDivElement;

  /**
   * Stream that will yield a `null` value whenever the size of the element bound to this model
   * may have changed. Elements that perform some computation based on their actual size should
   * rerun those computations whenever this stream yields a value to account for any change in size.
   */
  private _didResizeStream = new Subject<void>();
  private _didResizeStreamSub: Subscription;

  private _onSetRef = (ref: HTMLDivElement) => {
    this._element = ref;
    if (this.props.onSetRef) {
      this.props.onSetRef(this.id, this);
    }
  }

  get id(): string {
    return this.props.model.id;
  }

  getClientSize(): { width: number; height: number } {
    if (this._element) {
      return { width: this._element.clientWidth, height: this._element.clientHeight };
    } else {
      throw new Error('Reference to DOM element not set.');
    }
  }

  componentWillMount(): void {
    this._styleId = this.context.freeStyle.registerStyle({
      boxSizing: 'border-box',
      position: 'relative',
      display: 'block',
      backgroundColor: this.context.theme.primaryBackgroundColor,
      '> .content-wrapper': IronFlexLayout.fit
    });
    this._className = `hydragon-panel ${this._styleId}`;
  }

  componentDidMount(): void {
    if (this.props.parentDidResizeStream) {
      this._didResizeStreamSub = this.props.parentDidResizeStream.subscribe(this._didResizeStream);
    }
  }

  componentWillUnmount(): void {
    if (this._didResizeStreamSub) {
      this._didResizeStreamSub.unsubscribe();
    }
    this._didResizeStream = null;
  }

  renderContent(): JSX.Element | JSX.Element[] {
    const { model } = this.props;
    const items = model.items.map(
      item => this.context.renderChild(item, { key: item.id })
    );

    if (model.showHeader) {
      return (
        <paper-header-panel>
          <PaperToolbarComponent
            styles={{
              backgroundColor: 'rgb(56, 56, 56)',
              height: '30px',
              title: {
                'font-size': '14px',
                'font-weight': 'bold',
                'text-transform': 'uppercase',
                'margin-left': '0'
              }
            }}>

{model.title}

          </PaperToolbarComponent>
          { items }
        </paper-header-panel>
      );
    } else {
      return items;
    }
  }

  render() {
    const { model } = this.props;
    const inlineStyle = {
      width: (model.width !== undefined) ? model.width : undefined,
      height: (model.height !== undefined) ? model.height : undefined,
      flex: (this.props.flexBasis !== undefined) ? `0 0 ${this.props.flexBasis}` : undefined
    };

    return (

        {this.renderContent()}

    );
  }
}

export namespace PanelComponent {
  export interface IProps extends ILayoutComponentProps<PanelComponent> {
    model: PanelModel;
    flexBasis?: string;
    parentDidResizeStream?: Observable<void>;
  }

  export interface IContext
         extends stylable.IContext, themable.IContext {
    renderChild(model: any, props: any): React.ReactElement<any>;
  }
}


text:
Just writes to a file under the root directory

## TODO: organize these commands

Check is plugin will build with your version of fpb:
```
fpb --check path/to/plugin
```

Build RPM:
```
fpb --build path/to/plugin
```

Install plugin on fuel master:
```
fuel plugins --install plugin-name-2.0-2.0.1-0.noarch.rpm
```

Get current deployment graph on fuel master
```
fuel graph --env 1 --download
```

# Resources

```
https://wiki.openstack.org/wiki/Fuel/Plugins#Preparing_an_environment_for_plugin_development
https://wiki.openstack.org/wiki/Fuel/Plugins#deployment_tasks.yaml
```


text:
#pragma once
#include "stdafx.h"
#include "File.h"
#include "FileSystem.h"
using namespace fb;

class File::Impl {
public:
	boost::filesystem::path mPath;
	std::string mStrPath;
	Impl(const char* path)
		: mPath(path)
	{
		mStrPath = mPath.generic_string();
	}
};

File::File(const char* path)
	: mImpl(new Impl(path))
{
}

File::~File() {

}

FilePtr File::From(const char* path) {
	return FilePtr(new File(path), [](File* p) {delete p; });
}

bool File::Exists() const {
	return boost::filesystem::exists(mImpl->mPath);
}

FilePtr File::Parent() const {
	return File::From(mImpl->mPath.parent_path().generic_string().c_str());
}

std::string File::Absolute() const {
	std::string ret = boost::filesystem::absolute(mImpl->mPath).generic_string();
	if (ret.size() > 2 && ret.back() == '.')
		ret.erase(ret.end() - 1);
	return ret;
}

bool File::IsAbsolute() const
{
	return mImpl->mPath.is_absolute();
}

bool File::IsDir() const {
	return boost::filesystem::is_directory(mImpl->mPath);
}

bool File::MakeDir() const {
	bool ret = false;
	try {
		ret = boost::filesystem::create_directories(mImpl->mPath);
	}
	catch (boost::filesystem::filesystem_error& err) {
		 Logger::Log(FB_ERROR_LOG_ARG, err.what());
	}
	return ret;
}

bool File::operator==(const File& other) const {
	if (mImpl->mPath.empty() || other.mImpl->mPath.empty())
		return false;

	return mImpl->mPath == other.mImpl->mPath;
}

const std::string& File::Path() const {
	return mImpl->mStrPath;
}

const char* File::c_str() const {
	return mImpl->mStrPath.c_str();
}

File::PtrArray File::ListFiles() const {
	PtrArray files;
	if (!IsDir())
		return files;

	DirectoryIterator it(mImpl->mPath.generic_string().c_str(), false);
	while (it.HasNext()) {
		std::string path(it.GetNextFilePath());
		if (path != "." || path != "..") {
			files.push_back(File::From(path.c_str()));
		}
	}
	return files;
}

void File::DeleteOnExit() {
	FileSystem::DeleteOnExit(mImpl->mPath.generic_string().c_str());
}

bool File::HasExtension(const char* ext) {
	return FileSystem::HasExtension(mImpl->mPath.generic_string().c_str(), ext);
}

time_t File::LastModified() const {
	return boost::filesystem::last_write_time(mImpl->mPath);
}

ByteArray File::ReadBinary() const {
	return FileSystem::ReadBinaryFile(mImpl->mStrPath.c_str());
}


text:
'use strict';

// MODULES //

var float64ToFloat32 = require( '@stdlib/number/float64/base/to-float32' );
var ssumpw = require( '@stdlib/blas/ext/base/ssumpw' ).ndarray;
var sapxsumpw = require( '@stdlib/blas/ext/base/sapxsumpw' ).ndarray;

// MAIN //

/**
* Computes the arithmetic mean of a single-precision floating-point strided array using a two-pass error correction algorithm.
*
* ## Method
*
* -   This implementation uses a two-pass approach, as suggested by Neely (1966).
*
* ## References
*
* -   Neely, Peter M. 1966. "Comparison of Several Algorithms for Computation of Means, Standard Deviations and Correlation Coefficients." _Communications of the ACM_ 9 (7). Association for Computing Machinery: 496–99. doi:[10.1145/365719.365958](https://doi.org/10.1145/365719.365958).
* -   Schubert, Erich, and Michael Gertz. 2018. "Numerically Stable Parallel Computation of (Co-)Variance." In _Proceedings of the 30th International Conference on Scientific and Statistical Database Management_. New York, NY, USA: Association for Computing Machinery. doi:[10.1145/3221269.3223036](https://doi.org/10.1145/3221269.3223036).
*
* @param {PositiveInteger} N - number of indexed elements
* @param {Float32Array} x - input array
* @param {integer} stride - stride length
* @param {NonNegativeInteger} offset - starting index
* @returns {number} arithmetic mean
*
* @example
* var Float32Array = require( '@stdlib/array/float32' );
* var floor = require( '@stdlib/math/base/special/floor' );
*
* var x = new Float32Array( [ 2.0, 1.0, 2.0, -2.0, -2.0, 2.0, 3.0, 4.0 ] );
* var N = floor( x.length / 2 );
*
* var v = smeanpn( N, x, 2, 1 );
* // returns 1.25
*/
function smeanpn( N, x, stride, offset ) {
	var mu;
	var c;

	if ( N <= 0 ) {
		return NaN;
	}
	if ( N === 1 || stride === 0 ) {
		return x[ offset ];
	}
	// Compute an estimate for the mean:
	mu = float64ToFloat32( ssumpw( N, x, stride, offset ) / N );

	// Compute an error term:
	c = float64ToFloat32( sapxsumpw( N, -mu, x, stride, offset ) / N );

	return float64ToFloat32( mu + c );
}

// EXPORTS //

module.exports = smeanpn;


text:
//
//  MapButton.m
//  寻路算法demo
//
//  Created by 胡杨林 on 16/11/11.
//  Copyright © 2016年 胡杨林. All rights reserved.
//

#import "MapButton.h"

@implementation MapButton

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end