text:
package de.theit.jenkins.crowd;

import com.atlassian.crowd.exception.ApplicationPermissionException;
import com.atlassian.crowd.exception.ExpiredCredentialException;
import com.atlassian.crowd.exception.GroupNotFoundException;
import com.atlassian.crowd.exception.InactiveAccountException;
import com.atlassian.crowd.exception.InvalidAuthenticationException;
import com.atlassian.crowd.exception.OperationFailedException;
import com.atlassian.crowd.exception.UserNotFoundException;
import com.atlassian.crowd.model.group.Group;
import com.atlassian.crowd.model.user.User;

import hudson.Extension;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.security.AbstractPasswordBasedSecurityRealm;
import hudson.security.GroupDetails;
import hudson.security.SecurityRealm;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import hudson.util.Secret;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;

import jenkins.model.Jenkins;

import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.verb.POST;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import static de.theit.jenkins.crowd.ErrorMessages.accountExpired;
import static de.theit.jenkins.crowd.ErrorMessages.applicationPermission;
import static de.theit.jenkins.crowd.ErrorMessages.expiredCredentials;
import static de.theit.jenkins.crowd.ErrorMessages.groupNotFound;
import static de.theit.jenkins.crowd.ErrorMessages.invalidAuthentication;
import static de.theit.jenkins.crowd.ErrorMessages.operationFailed;
import static de.theit.jenkins.crowd.ErrorMessages.specifyApplicationName;
import static de.theit.jenkins.crowd.ErrorMessages.specifyApplicationPassword;
import static de.theit.jenkins.crowd.ErrorMessages.specifyCrowdUrl;
import static de.theit.jenkins.crowd.ErrorMessages.specifySessionValidationInterval;
import static de.theit.jenkins.crowd.ErrorMessages.userNotFound;
import static de.theit.jenkins.crowd.ErrorMessages.userNotValid;

/**
 * This class provides the security realm for authenticating users against a
 * remote Crowd server.
 *
 * @author Thorsten Heit (theit@gmx.de)
 * @since 06.09.2011
 * @version $Id$
 */
public class CrowdSecurityRealm extends AbstractPasswordBasedSecurityRealm {
    /** Used for logging purposes. */
    private static final Logger LOG = Logger.getLogger(CrowdSecurityRealm.class.getName());

    /** Contains the Crowd server URL. */
    public final String url;

    /** Contains the application name to access Crowd. */
    public final String applicationName;

    /** Contains the application password to access Crowd. */
    public final Secret password;

    /** Contains the Crowd group to which a user must belong to. */
    public final String group;

    /** Specifies whether nested groups can be used. */
    public final boolean nestedGroups;

    /** Don't use SSO, only REST API authentication. */
    // TODO: Currently this just disables CrowdServletFilter,
    // (auto-logout), maybe worth disabling other SSO handling too.
    public final boolean useSSO;

    /**
     * The number of minutes to cache authentication validation in the session.
     * If this value is set to 0, each HTTP request will be authenticated with
     * the Crowd server.
     */
    public final int sessionValidationInterval;

    /**
     * A domain to use when setting cookies, overriding the SSO Domain set in Crowd
     * (since Crowd 2.5.2).
     * cookie.domain details
     */
    public final String cookieDomain;

    /**
     * SSO cookie name for application.
     * cookie.tokenkey details
     */
    public final String cookieTokenkey;

    public final Boolean useProxy;
    public final String httpProxyHost;
    public final String httpProxyPort;
    public final String httpProxyUsername;
    public final Secret httpProxyPassword;

    public final String socketTimeout;
    public final String httpTimeout;
    public final String httpMaxConnections;

    /**
     * The cache configuration
     *
     * @since 1.9
     */
    private final CacheConfiguration cache;

    /**
     * The configuration data necessary for accessing the services on the remote
     * Crowd server.
     */
    private transient CrowdConfigurationService configuration;

    /**
     * Default constructor. Fields in config.jelly must match the parameter
     * names in the "DataBoundConstructor".
     *
     * @param url                       The URL for Crowd.
     * @param applicationName           The application name.
     * @param password                  The application password.
     * @param group                     The group to which users must belong to. If
     *                                  this parameter is
     *                                  not specified, a users group membership will
     *                                  not be checked.
     * @param nestedGroups              true when nested groups may be
     *                                  used.
     *                                  false else.
     * @param sessionValidationInterval The number of minutes to cache
     *                                  authentication validation in
     *                                  the session. If this value is set to
     *                                  0, each HTTP
     *                                  request will be authenticated with the Crowd
     *                                  server.
     * @param useSSO                    Enable SSO authentication.
     * @param cookieDomain              The cookie domain
     * @param cookieTokenkey            The cookie token key
     * @param useProxy                  Specifies if a proxy should be used
     * @param httpProxyHost             The http proxy host
     * @param httpProxyPort             The http proxy port
     * @param httpProxyUsername         The http proxy username
     * @param httpProxyPassword         The http proxy password
     * @param socketTimeout             The socket timeout
     * @param httpTimeout               The http timeout
     * @param httpMaxConnections        The http max connections
     * @param cache                     The cache configuration
     */
    @DataBoundConstructor
    public CrowdSecurityRealm(String url, String applicationName, Secret password, String group, boolean nestedGroups,
            int sessionValidationInterval, boolean useSSO, String cookieDomain,
            String cookieTokenkey, Boolean useProxy, String httpProxyHost, String httpProxyPort,
            String httpProxyUsername, Secret httpProxyPassword, String socketTimeout,
            String httpTimeout, String httpMaxConnections, CacheConfiguration cache) {
        this.cookieTokenkey = cookieTokenkey;
        this.useProxy = useProxy;
        this.httpProxyHost = httpProxyHost;
        this.httpProxyPort = httpProxyPort;
        this.httpProxyUsername = httpProxyUsername;
        this.httpProxyPassword = httpProxyPassword;
        this.socketTimeout = socketTimeout;
        this.httpTimeout = httpTimeout;
        this.httpMaxConnections = httpMaxConnections;
        this.url = StringUtils.trimToEmpty(url);
        this.applicationName = StringUtils.trimToEmpty(applicationName);
        this.password = password;
        this.group = StringUtils.trimToEmpty(group);
        this.nestedGroups = nestedGroups;
        this.sessionValidationInterval = sessionValidationInterval;
        this.useSSO = useSSO;
        this.cookieDomain = cookieDomain;
        this.cache = cache;
    }

    /**
     * Default constructor. Fields in config.jelly must match the parameter
     * names in the "DataBoundConstructor".
     *
     * @param url                       The URL for Crowd.
     * @param applicationName           The application name.
     * @param password                  The application password.
     * @param group                     The group to which users must belong to. If
     *                                  this parameter is not specified, a users
     *                                  group membership will not be checked.
     * @param nestedGroups              true when nested groups may be
     *                                  used. false else.
     * @param sessionValidationInterval The number of minutes to cache
     *                                  authentication validation in the session. If
     *                                  this value is set to 0, each
     *                                  HTTP request will be authenticated with the
     *                                  Crowd server.
     * @param useSSO                    Enable SSO authentication.
     * @param cookieDomain              The cookie domain
     * @param cookieTokenkey            The cookie token key
     * @param useProxy                  Specifies if a proxy should be used
     * @param httpProxyHost             The http proxy host
     * @param httpProxyPort             The http proxy port
     * @param httpProxyUsername         The http proxy username
     * @param httpProxyPassword         The http proxy password
     * @param socketTimeout             The socket timeout
     * @param httpTimeout               The http timeout
     * @param httpMaxConnections        The http max connections
     * @param cache                     The cache configuration
     *
     * @deprecated retained for backwards binary compatibility.
     */
    @Deprecated
    public CrowdSecurityRealm(String url, String applicationName, String password, String group, boolean nestedGroups,
            int sessionValidationInterval, boolean useSSO, String cookieDomain,
            String cookieTokenkey, Boolean useProxy, String httpProxyHost, String httpProxyPort,
            String httpProxyUsername, String httpProxyPassword, String socketTimeout,
            String httpTimeout, String httpMaxConnections, CacheConfiguration cache) {
        this(url, applicationName, Secret.fromString(password), group, nestedGroups, sessionValidationInterval,
                useSSO,
                cookieDomain, cookieTokenkey, useProxy, httpProxyHost, httpProxyPort, httpProxyUsername,
                Secret.fromString(httpProxyPassword), socketTimeout, httpTimeout, httpMaxConnections, cache);
        // If this constructor is called, make sure to re-save the configuration.
        // This way, migrated secrets are persisted securely without user interaction.
        getDescriptor().save();
    }

    /**
     * Fields in config.jelly must match the parameter names in the
     * "DataBoundConstructor".
     *
     * @param url                       The URL for Crowd.
     * @param applicationName           The application name.
     * @param password                  The application password.
     * @param group                     The group to which users must belong to. If
     *                                  this parameter is not specified, a users
     *                                  group membership will not be checked.
     * @param nestedGroups              true when nested groups may be
     *                                  used. false else.
     * @param sessionValidationInterval The number of minutes to cache
     *                                  authentication validation in the session. If
     *                                  this value is set to 0, each
     *                                  HTTP request will be authenticated with the
     *                                  Crowd server.
     * @param useSSO                    Enable SSO authentication.
     * @param cookieDomain              The cookie domain
     * @param cookieTokenkey            The cookie token key
     * @param useProxy                  Specifies if a proxy should be used
     * @param httpProxyHost             The http proxy host
     * @param httpProxyPort             The http proxy port
     * @param httpProxyUsername         The http proxy username
     * @param httpProxyPassword         The http proxy password
     * @param socketTimeout             The socket timeout
     * @param httpTimeout               The http timeout
     * @param httpMaxConnections        The http max connections
     *
     * @deprecated retained for backwards binary compatibility.
     */
    @Deprecated
    public CrowdSecurityRealm(String url, String applicationName, String password, String group, boolean nestedGroups,
            int sessionValidationInterval, boolean useSSO, String cookieDomain,
            String cookieTokenkey, Boolean useProxy, String httpProxyHost, String httpProxyPort,
            String httpProxyUsername, String httpProxyPassword, String socketTimeout,
            String httpTimeout, String httpMaxConnections) {
        this(url, applicationName, password, group, nestedGroups,
                sessionValidationInterval, useSSO, cookieDomain,
                cookieTokenkey, useProxy, httpProxyHost, httpProxyPort,
                httpProxyUsername, httpProxyPassword, socketTimeout,
                httpTimeout, httpMaxConnections, null);
    }

    public CacheConfiguration getCache() {
        return cache;
    }

    public Integer getCacheSize() {
        return cache == null ? null : cache.getSize();
    }

    public Integer getCacheTTL() {
        return cache == null ? null : cache.getTtl();
    }

    /**
     * Initializes all objects necessary to talk to / with Crowd.
     */
    private void initializeConfiguration() {
        configuration = new CrowdConfigurationService(
                url, applicationName, password, sessionValidationInterval,
                useSSO, cookieDomain, cookieTokenkey, useProxy, httpProxyHost, httpProxyPort, httpProxyUsername,
                httpProxyPassword, socketTimeout, httpTimeout, httpMaxConnections,
                cache != null, getCacheSize(), getCacheTTL(),
                group, nestedGroups);
    }

    /**
     * {@inheritDoc}
     *
     * @see hudson.security.AbstractPasswordBasedSecurityRealm#createSecurityComponents()
     */
    @Override
    public SecurityComponents createSecurityComponents() {
        if (null == configuration) {
            initializeConfiguration();
        }

        AuthenticationManager crowdAuthenticationManager = new CrowdAuthenticationManager(configuration);
        UserDetailsService crowdUserDetails = new CrowdUserDetailsService(configuration);

        if (useSSO) {
            CrowdRememberMeServices ssoService = new CrowdRememberMeServices(configuration);
            return new SecurityComponents(crowdAuthenticationManager, crowdUserDetails, ssoService);
        } else {
            return new SecurityComponents(crowdAuthenticationManager, crowdUserDetails);
        }
    }

    /**
     * {@inheritDoc}
     *
     * @see hudson.security.SecurityRealm#doLogout(org.kohsuke.stapler.StaplerRequest,
     *      org.kohsuke.stapler.StaplerResponse)
     */
    @Override
    @POST
    public void doLogout(StaplerRequest req, StaplerResponse rsp)
            throws IOException, ServletException {
        SecurityRealm realm = Jenkins.get().getSecurityRealm();

        if (useSSO) {
            if (realm instanceof CrowdSecurityRealm
                    && realm.getSecurityComponents().rememberMe2 instanceof CrowdRememberMeServices) {
                ((CrowdRememberMeServices) realm.getSecurityComponents().rememberMe2).logout(req, rsp);
            }
        }

        super.doLogout(req, rsp);
    }

    /**
     * {@inheritDoc}
     *
     * @see hudson.security.SecurityRealm#createFilter(javax.servlet.FilterConfig)
     */
    @Override
    public Filter createFilter(FilterConfig filterConfig) {
        if (null == this.configuration) {
            initializeConfiguration();
        }

        Filter defaultFilter = super.createFilter(filterConfig);

        if (!useSSO) {
            return defaultFilter;
        }

        return new CrowdServletFilter(this, this.configuration, defaultFilter);
    }

    /**
     * {@inheritDoc}
     *
     * @deprecated use {@link #loadUserByUsername2}
     * @see hudson.security.AbstractPasswordBasedSecurityRealm#loadUserByUsername(java.lang.String)
     */
    @Override
    @Deprecated
    public org.acegisecurity.userdetails.UserDetails loadUserByUsername(String username)
            throws org.acegisecurity.userdetails.UsernameNotFoundException,
            org.springframework.dao.DataAccessException {
        return getSecurityComponents().userDetails.loadUserByUsername(username);
    }

    /**
     * {@inheritDoc}
     *
     * @see hudson.security.AbstractPasswordBasedSecurityRealm#loadUserByUsername2(java.lang.String)
     */
    @Override
    public UserDetails loadUserByUsername2(String username) throws UsernameNotFoundException {
        return getSecurityComponents().userDetails2.loadUserByUsername(username);
    }

    // TODO: Implement missing loadGroupByGroupname2
    /**
     * {@inheritDoc}
     *
     * @deprecated use {@link #loadGroupByGroupname2}
     * @since 1.549
     * @see hudson.security.SecurityRealm#loadGroupByGroupname(java.lang.String)
     */
    @Override
    @Deprecated
    public GroupDetails loadGroupByGroupname(String groupname, boolean fetchMembers)
            throws org.acegisecurity.userdetails.UsernameNotFoundException,
            org.springframework.dao.DataAccessException {
        try {
            return loadGroupByGroupname2(groupname, fetchMembers);
        } catch (AuthenticationException x) {
            throw org.acegisecurity.AuthenticationException.fromSpring(x);
        }
    }

    /**
     * {@inheritDoc}
     *
     * @deprecated use {@link #loadGroupByGroupname2}
     * @see hudson.security.AbstractPasswordBasedSecurityRealm#loadGroupByGroupname(java.lang.String)
     */
    @Override
    @Deprecated
    public GroupDetails loadGroupByGroupname(String groupname)
            throws org.acegisecurity.userdetails.UsernameNotFoundException,
            org.springframework.dao.DataAccessException {
        try {
            // load the user object from the remote Crowd server
            LOG.log(Level.FINER, "Trying to load group: {0}", groupname);
            final Group crowdGroup = this.configuration.getGroup(groupname);

            return new GroupDetails() {
                @Override
                public String getName() {
                    return crowdGroup.getName();
                }
            };
        } catch (GroupNotFoundException ex) {
            LOG.log(Level.INFO, groupNotFound(groupname));
            throw new org.springframework.dao.DataAccessException(groupNotFound(groupname), ex);
        } catch (ApplicationPermissionException ex) {
            LOG.log(Level.WARNING, applicationPermission());
            throw new org.springframework.dao.DataAccessException(applicationPermission(), ex);
        } catch (InvalidAuthenticationException ex) {
            LOG.log(Level.WARNING, invalidAuthentication());
            throw new org.springframework.dao.DataAccessException(invalidAuthentication(), ex);
        } catch (OperationFailedException ex) {
            LOG.log(Level.SEVERE, operationFailed(), ex);
            throw new org.springframework.dao.DataAccessException(operationFailed(), ex);
        }
    }

    /**
     * {@inheritDoc}
     *
     * @see hudson.security.AbstractPasswordBasedSecurityRealm#authenticate2(java.lang.String,
     *      java.lang.String)
     *
     */
    @Override
    protected UserDetails authenticate2(String pUsername, String pPassword) throws AuthenticationException {
        User user;

        // ensure that the group is available, active and that the user
        // is a member of it
        if (!this.configuration.isGroupMember(pUsername)) {
            throw new InsufficientAuthenticationException(
                    userNotValid(pUsername, this.configuration.getAllowedGroupNames()));
        }

        try {
            // authenticate user
            LOG.log(Level.FINE, "Authenticate user '{0}' using password {1}", new Object[]{pUsername, null != pPassword ? "'<available>'" : "'<not specified>'"});
            user = this.configuration.authenticateUser(pUsername, pPassword);
        } catch (UserNotFoundException ex) {
            LOG.log(Level.INFO, userNotFound(pUsername));
            throw new BadCredentialsException(userNotFound(pUsername), ex);
        } catch (ExpiredCredentialException ex) {
            LOG.log(Level.WARNING, expiredCredentials(pUsername));
            throw new BadCredentialsException(expiredCredentials(pUsername), ex);
        } catch (InactiveAccountException ex) {
            LOG.log(Level.WARNING, accountExpired(pUsername));
            throw new AccountExpiredException(accountExpired(pUsername), ex);
        } catch (ApplicationPermissionException ex) {
            LOG.log(Level.WARNING, applicationPermission());
            throw new AuthenticationServiceException(applicationPermission(),
                    ex);
        } catch (InvalidAuthenticationException ex) {
            LOG.log(Level.WARNING, invalidAuthentication());
            throw new AuthenticationServiceException(invalidAuthentication(),
                    ex);
        } catch (OperationFailedException ex) {
            LOG.log(Level.SEVERE, operationFailed(), ex);
            throw new AuthenticationServiceException(operationFailed(), ex);
        }

        // create the list of granted authorities
        List<GrantedAuthority> authorities = new ArrayList<>();
        // add the "authenticated" authority to the list of granted
        // authorities...
        authorities.add(SecurityRealm.AUTHENTICATED_AUTHORITY2);
        // ..and all authorities retrieved from the Crowd server
        authorities.addAll(this.configuration.getAuthoritiesForUser(pUsername));

        return new CrowdUser(user, authorities);
    }

    /**
     * Descriptor for {@link CrowdSecurityRealm}. Used as a singleton. The class
     * is marked as public so that it can be accessed from views.
     *
     * @author Thorsten Heit (theit@gmx.de)
     * @since 06.09.2011 13:35:41
     * @version $Id$
     */
    @Extension
    public static final class DescriptorImpl extends Descriptor<SecurityRealm> {
        /**
         * Default constructor.
         */
        public DescriptorImpl() {
            super(CrowdSecurityRealm.class);
        }

        /**
         * Performs on-the-fly validation of the form field 'url'.
         *
         * @param url
         *            The URL of the Crowd server.
         *
         * @return Indicates the outcome of the validation. This is sent to the
         *         browser.
         */
        @POST
        public FormValidation doCheckUrl(@QueryParameter final String url) {
            if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
                return FormValidation.ok();
            }

            if (0 == url.length()) {
                return FormValidation.error(specifyCrowdUrl());
            }

            return FormValidation.ok();
        }

        /**
         * Performs on-the-fly validation of the form field 'application name'.
         *
         * @param applicationName The application name.
         *
         * @return Indicates the outcome of the validation. This is sent to the
         *         browser.
         */
        @POST
        public FormValidation doCheckApplicationName(
                @QueryParameter final String applicationName) {
            if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
                return FormValidation.ok();
            }

            if (0 == applicationName.length()) {
                return FormValidation.error(specifyApplicationName());
            }

            return FormValidation.ok();
        }

        /**
         * Performs on-the-fly validation of the form field 'password'.
         *
         * @param password
         *                 The application's password.
         *
         * @return Indicates the outcome of the validation. This is sent to the
         *         browser.
         */
        @POST
        public FormValidation doCheckPassword(
                @QueryParameter final String password) {
            if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
                return FormValidation.ok();
            }

            if (0 == password.length()) {
                return FormValidation.error(specifyApplicationPassword());
            }

            return FormValidation.ok();
        }

        /**
         * Performs on-the-fly validation of the form field 'session validation
         * interval'.
         *
         * @param sessionValidationInterval The session validation interval time in
         *                                  minutes.
         * @return Indicates the outcome of the validation. This is sent to the
         *         browser.
         */
        @POST
        public FormValidation doCheckSessionValidationInterval(
                @QueryParameter final String sessionValidationInterval) {
            if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
                return FormValidation.ok();
            }

            try {
                if (0 == sessionValidationInterval.length()
                        || Integer.parseInt(sessionValidationInterval) < 0) {
                    return FormValidation.error(specifySessionValidationInterval());
                }
            } catch (NumberFormatException ex) {
                return FormValidation.error(specifySessionValidationInterval());
            }

            return FormValidation.ok();
        }

        /**
         * Checks whether the connection to the Crowd server can be established
         * using the given credentials.
         *
         * @param url                       The URL of the Crowd server.
         * @param applicationName           The application name.
         * @param password                  The application's password.
         * @param group                     The Crowd groups users have to belong to if
         *                                  specified.
         * @param useSSO                    Specifies if SSO should be used
         * @param cookieDomain              The cookie domain
         * @param sessionValidationInterval The session validation interval
         * @param cookieTokenkey            The cookie token key
         * @param useProxy                  Specifies if a proxy should be used
         * @param httpProxyHost             The http proxy host
         * @param httpProxyPort             The http proxy port
         * @param httpProxyUsername         The http proxy username
         * @param httpProxyPassword         The http proxy password
         * @param socketTimeout             The socket timeout
         * @param httpTimeout               The http timeout
         * @param httpMaxConnections        The http max connections
         * @return Indicates the outcome of the validation. This is sent to the
         *         browser.
         */
        @POST
        public FormValidation doTestConnection(@QueryParameter String url, @QueryParameter String applicationName,
                @QueryParameter String password, @QueryParameter String group, @QueryParameter boolean useSSO,
                @QueryParameter String cookieDomain, @QueryParameter int sessionValidationInterval,
                @QueryParameter String cookieTokenkey, @QueryParameter Boolean useProxy,
                @QueryParameter String httpProxyHost,
                @QueryParameter String httpProxyPort, @QueryParameter String httpProxyUsername,
                @QueryParameter String httpProxyPassword, @QueryParameter String socketTimeout,
                @QueryParameter String httpTimeout, @QueryParameter String httpMaxConnections) {

            Jenkins.get().checkPermission(Jenkins.ADMINISTER);
            CrowdConfigurationService tConfiguration = new CrowdConfigurationService(
                    url, applicationName, Secret.fromString(password), sessionValidationInterval,
                    useSSO, cookieDomain, cookieTokenkey, useProxy, httpProxyHost, httpProxyPort, httpProxyUsername,
                    Secret.fromString(httpProxyPassword), socketTimeout, httpTimeout, httpMaxConnections,
                    false, null, null,
                    group, false);

            try {
                tConfiguration.testConnection();

                // ensure that the given group names are available and active
                for (String groupName : tConfiguration.getAllowedGroupNames()) {
                    if (!tConfiguration.isGroupActive(groupName)) {
                        return FormValidation.error(groupNotFound(groupName));
                    }
                }

                return FormValidation.ok("OK");
            } catch (InvalidAuthenticationException ex) {
                LOG.log(Level.WARNING, invalidAuthentication(), ex);
                return FormValidation.error(invalidAuthentication());
            } catch (ApplicationPermissionException ex) {
                LOG.log(Level.WARNING, applicationPermission(), ex);
                return FormValidation.error(applicationPermission());
            } catch (OperationFailedException ex) {
                LOG.log(Level.SEVERE, operationFailed(), ex);
                return FormValidation.error(operationFailed());
            } finally {
                tConfiguration.shutdown();
            }
        }

        /**
         * {@inheritDoc}
         *
         * @see hudson.model.Descriptor#getDisplayName()
         */
        @Override
        public String getDisplayName() {
            return "Crowd 2";
        }
    }

    public static class CacheConfiguration extends AbstractDescribableImpl<CacheConfiguration> {
        private final int size;
        private final int ttl;

        @DataBoundConstructor
        public CacheConfiguration(int size, int ttl) {
            this.size = Math.max(10, Math.min(size, 1000));
            this.ttl = Math.max(30, Math.min(ttl, 3600));
        }

        public int getSize() {
            return size;
        }

        public int getTtl() {
            return ttl;
        }

        @Extension
        public static class DescriptorImpl extends Descriptor<CacheConfiguration> {

            @Override
            public String getDisplayName() {
                return "";
            }

            public ListBoxModel doFillSizeItems() {
                ListBoxModel m = new ListBoxModel();
                m.add("10");
                m.add("20");
                m.add("50");
                m.add("100");
                m.add("200");
                m.add("500");
                m.add("1000");
                return m;
            }

            public ListBoxModel doFillTtlItems() {
                ListBoxModel m = new ListBoxModel();
                // TODO: use Messages (not that there were any translations before)
                m.add("30 sec", "30");
                m.add("1 min", "60");
                m.add("2 min", "120");
                m.add("5 min", "300");
                m.add("10 min", "600");
                m.add("15 min", "900");
                m.add("30 min", "1800");
                m.add("1 hour", "3600");
                return m;
            }

        }
    }
}


text:
extern int some_val;

namespace NS {
  class C {
    void method_decl();
    int method_def1() { ++some_val; return undef_val1; }
    inline int method_def2();
  };
}

inline int NS::C::method_def2() {
  ++some_val; return undef_val2;
}

static inline int foo1() {
  ++some_val; return undef_val3;
}

#ifdef BLAH

static inline int foo2() {
  ++some_val; return undef_val4;
}

#endif

#endif

redpajama_set_name: RedPajamaGithub


text:
#import "BaseState.h"
#import "BLEConnectionDelegate.h"

#define RSS_APP_ACTION_LOAD_METADATA  1
#define RSS_APP_ACTION_LOAD_BLOCK  2
#define RSS_APP_ACTION_LOAD_PACKET  3
#define RSS_APP_ACTION_LOAD_DETAIL_METADATA  4
#define RSS_APP_ACTION_LOAD_DETAIL_TITLE_BLOCK  5
#define RSS_APP_ACTION_LOAD_DETAIL_DESCRIPTION_BLOCK  6
#define RSS_APP_ACTION_LOAD_DETAIL_PACKET  7

@interface RSSState : BaseState

-(void)processIncomingData:(unsigned char *) data length:(int) length;
-(BLEConnectionDelegate*) getBLEDelegate;
+(RSSState *)getRSSState;

@end


text:
package io.fabric8.servicemix.facade;

import javax.management.MBeanServerConnection;

/**
 * Facade to a remote ServiceMixContext using JMX
 */
public class RemoteJMXServiceMixFacade extends ServiceMixFacadeSupport {

    public RemoteJMXServiceMixFacade(MBeanServerConnection mBeanServer) throws Exception {
        super(mBeanServer);
    }

}


text:
Accessing and altering arguments from patches

--FILE--
<?php

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 1);
error_reporting(E_ALL | E_STRICT);

require __DIR__ . "/../Patchwork.php";
require __DIR__ . "/includes/Functions.php";

Patchwork\replace("setArrayElement", function(array &$array, $key, $value) {
    $array[$key] = $value;
});

$array = [0, 1, "foo" => 2, 3];

setArrayElement($array, "foo", "bar");

assert($array == [0, 1, "foo" => "bar", 3]);

?>
===DONE===

--EXPECT--
===DONE===


text:
    Specifies what to do when a previously generated view is not referenced anymore.

        Note: when using multiple Job DSL build steps in a single job, set this to "Delete" only for the last Job
        DSL build step. Otherwise views may be deleted and re-created. See
        JENKINS-44142 for details.


text:
package com.example.mycoolweather.gson;

import com.google.gson.annotations.SerializedName;

/**
 * Created by Administrator on 2017/7/3.
 *
 * 使用@SerializedName注解的方式让Json字段和Java字段之间建立映射关系
 *
 *      "basic":{
 *          "city":"苏州"
 *          "id":"CN101190401"
 *          "update":{
 *              "loc":"2017-07-03 15:12"
 *          }
 *      }
 */

public class Basic {
    @SerializedName("city")
    public String cityName;

    @SerializedName("id")
    public String weatherId;

    public Update update;

    public class Update{
        @SerializedName("loc")
        public  String updateTime;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>tk.skuro</groupId>
    <artifactId>clojure-maven-archetype</artifactId>
    <version>1.4-SNAPSHOT</version>
    <packaging>maven-archetype</packaging>

    <name>clojure-maven-archetype</name>
    <description>A simple Maven archetype for Clojure</description>
    <url>http://github.com/skuro/clojure-maven-archetype</url>

    <parent>
        <groupId>org.sonatype.oss</groupId>
        <artifactId>oss-parent</artifactId>
        <version>7</version>
    </parent>

    <developers>
        <developer>
            <id>skuro</id>
            <name>Carlo Sciolla</name>
            <roles>
                <role>maintainer</role>
            </roles>
            <email>skuro@skuro.tk</email>
        </developer>
    </developers>

    <scm>
        <connection>scm:git:git://github.com/skuro/clojure-maven-archetype.git</connection>
        <developerConnection>scm:git:git@github.com:skuro/clojure-maven-archetype.git</developerConnection>
        <url>https://github.com/skuro/clojure-maven-archetype</url>
    </scm>

    <licenses>
        <license>
            <url>http://www.opensource.org/licenses/MIT</url>
            <name>MIT License</name>
        </license>
    </licenses>

    <build>
        <extensions>
            <extension>
                <groupId>org.apache.maven.archetype</groupId>
                <artifactId>archetype-packaging</artifactId>
                <version>2.2</version>
            </extension>
        </extensions>

        <pluginManagement>
            <plugins>
                <plugin>
                    <artifactId>maven-archetype-plugin</artifactId>
                    <version>2.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

</project>


text:
body {
  font-family: 'Lato', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  overflow-x: hidden;
}
p {
  font-size: 20px;
}
p.small {
  font-size: 16px;
}
a,
a:hover,
a:focus,
a:active,
a.active {
  color: #18BC9C;
  outline: none;
}
h1,
h2,
h3,
h4,
h5,
h6 {
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  font-weight: 700;
}
hr.star-light,
hr.star-primary {
  padding: 0;
  border: none;
  border-top: solid 5px;
  text-align: center;
  max-width: 250px;
  margin: 25px auto 30px;
}
hr.star-light:after,
hr.star-primary:after {
  content: "\f005";
  font-family: FontAwesome;
  display: inline-block;
  position: relative;
  top: -0.8em;
  font-size: 2em;
  padding: 0 0.25em;
}
hr.star-light {
  border-color: white;
}
hr.star-light:after {
  background-color: #43464C;
  color: white;
}
hr.star-primary {
  border-color: #282830;
}
hr.star-primary:after {
  background-color: white;
  color: #282830;
}
.img-centered {
  margin: 0 auto;
}
header {
  text-align: center;
  background: #43464C;
  color: #D2D7D3;
}
header .container {
  padding-top: 100px;
  padding-bottom: 50px;
}
header img {
  display: block;
  margin: 0 auto 20px;
}
header .intro-text .name {
  display: block;
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  font-weight: 700;
  font-size: 2em;
}
header .intro-text .skills {
  font-size: 1.25em;
  font-weight: 300;
}
@media (min-width: 768px) {
  header .container {
    padding-top: 200px;
    padding-bottom: 100px;
  }
  header .intro-text .name {
    font-size: 4.75em;
  }
  header .intro-text .skills {
    font-size: 1.75em;
  }
}
.navbar-custom {
  background: #282830;
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  font-weight: 700;
  border: none;
}
.navbar-custom a:focus {
  outline: none;
}
.navbar-custom .navbar-brand {
  color: white;
}
.navbar-custom .navbar-brand:hover,
.navbar-custom .navbar-brand:focus,
.navbar-custom .navbar-brand:active,
.navbar-custom .navbar-brand.active {
  color: white;
}
.navbar-custom .navbar-nav {
  letter-spacing: 1px;
}
.navbar-custom .navbar-nav li a {
  color: white;
}
.navbar-custom .navbar-nav li a:hover {
  color: #18BC9C;
  outline: none;
}
.navbar-custom .navbar-nav li a:focus,
.navbar-custom .navbar-nav li a:active {
  color: white;
}
.navbar-custom .navbar-nav li.active a {
  color: white;
  background: #23a073;
}
.navbar-custom .navbar-nav li.active a:hover,
.navbar-custom .navbar-nav li.active a:focus,
.navbar-custom .navbar-nav li.active a:active {
  color: white;
  background: #23a073;
}
.navbar-custom .navbar-toggle {
  color: white;
  text-transform: uppercase;
  font-size: 10px;
  border-color: white;
}
.navbar-custom .navbar-toggle:hover,
.navbar-custom .navbar-toggle:focus {
  background-color: #18BC9C;
  color: white;
  border-color: #18BC9C;
}
@media (min-width: 768px) {
  .navbar-custom {
    padding: 25px 0;
    -webkit-transition: padding 0.3s;
    -moz-transition: padding 0.3s;
    transition: padding 0.3s;
  }
  .navbar-custom .navbar-brand {
    font-size: 2em;
    -webkit-transition: all 0.3s;
    -moz-transition: all 0.3s;
    transition: all 0.3s;
  }
  .navbar-custom.affix {
    padding: 10px 0;
  }
  .navbar-custom.affix .navbar-brand {
    font-size: 1.5em;
  }
}
section {
  padding: 100px 0;
}
section h2 {
  margin: 0;
  font-size: 3em;
}
section.success {
  background: #43464C;
  color: #D2D7D3;
}
@media (max-width: 767px) {
  section {
    padding: 75px 0;
  }
  section.first {
    padding-top: 75px;
  }
}
#portfolio {
  background: #fdf8ef;
}

#portfolio .portfolio-item {
  margin: 0 0 15px;
  right: 0;
}
#portfolio .portfolio-item .portfolio-link {
  display: block;
  position: relative;
  max-width: 400px;
  margin: 0 auto;
}
#portfolio .portfolio-item .portfolio-link .caption {
  background: rgba(24, 188, 156, 0.9);
  position: absolute;
  width: 100%;
  height: 100%;
  opacity: 0;
  transition: all ease 0.5s;
  -webkit-transition: all ease 0.5s;
  -moz-transition: all ease 0.5s;
}
#portfolio .portfolio-item .portfolio-link .caption:hover {
  opacity: 1;
}
#portfolio .portfolio-item .portfolio-link .caption .caption-content {
  position: absolute;
  width: 100%;
  height: 20px;
  font-size: 20px;
  text-align: center;
  top: 50%;
  margin-top: -12px;
  color: white;
}
#portfolio .portfolio-item .portfolio-link .caption .caption-content i {
  margin-top: -12px;
}
#portfolio .portfolio-item .portfolio-link .caption .caption-content h3,
#portfolio .portfolio-item .portfolio-link .caption .caption-content h4 {
  margin: 0;
}
#portfolio * {
  z-index: 2;
}
@media (min-width: 767px) {
  #portfolio .portfolio-item {
    margin: 0 0 30px;
  }
}
.floating-label-form-group {
  position: relative;
  margin-bottom: 0;
  padding-bottom: 0.5em;
  border-bottom: 1px solid #eeeeee;
}
.floating-label-form-group input,
.floating-label-form-group textarea {
  z-index: 1;
  position: relative;
  padding-right: 0;
  padding-left: 0;
  border: none;
  border-radius: 0;
  font-size: 1.5em;
  background: none;
  box-shadow: none !important;
  resize: none;
}
.floating-label-form-group label {
  display: block;
  z-index: 0;
  position: relative;
  top: 2em;
  margin: 0;
  font-size: 0.85em;
  line-height: 1.764705882em;
  vertical-align: middle;
  vertical-align: baseline;
  opacity: 0;
  -webkit-transition: top 0.3s ease,opacity 0.3s ease;
  -moz-transition: top 0.3s ease,opacity 0.3s ease;
  -ms-transition: top 0.3s ease,opacity 0.3s ease;
  transition: top 0.3s ease,opacity 0.3s ease;
}
.floating-label-form-group:not(:first-child) {
  padding-left: 14px;
  border-left: 1px solid #eeeeee;
}
.floating-label-form-group-with-value label {
  top: 0;
  opacity: 1;
}
.floating-label-form-group-with-focus label {
  color: #18BC9C;
}
form .row:first-child .floating-label-form-group {
  border-top: 1px solid #eeeeee;
}
footer {
  color: white;
}
footer h3 {
  margin-bottom: 30px;
}
footer .footer-above {
  padding-top: 50px;
  background-color: #282830;
}
footer .footer-col {
  margin-bottom: 50px;
}
footer .footer-below {
  padding: 25px 0;
  background-color: #282830;
}
.btn-outline {
  color: white;
  font-size: 20px;
  border: solid 2px white;
  background: transparent;
  transition: all 0.3s ease-in-out;
  margin-top: 15px;
}
.btn-outline:hover,
.btn-outline:focus,
.btn-outline:active,
.btn-outline.active {
  color: #18BC9C;
  background: white;
  border: solid 2px white;
}
.btn-primary {
  color: white;
  background-color: #2C3E50;
  border-color: #2C3E50;
  font-weight: 700;
}
.btn-primary:hover,
.btn-primary:focus,
.btn-primary:active,
.btn-primary.active,
.open .dropdown-toggle.btn-primary {
  color: white;
  background-color: #1a242f;
  border-color: #161f29;
}
.btn-primary:active,
.btn-primary.active,
.open .dropdown-toggle.btn-primary {
  background-image: none;
}
.btn-primary.disabled,
.btn-primary[disabled],
fieldset[disabled] .btn-primary,
.btn-primary.disabled:hover,
.btn-primary[disabled]:hover,
fieldset[disabled] .btn-primary:hover,
.btn-primary.disabled:focus,
.btn-primary[disabled]:focus,
fieldset[disabled] .btn-primary:focus,
.btn-primary.disabled:active,
.btn-primary[disabled]:active,
fieldset[disabled] .btn-primary:active,
.btn-primary.disabled.active,
.btn-primary[disabled].active,
fieldset[disabled] .btn-primary.active {
  background-color: #2C3E50;
  border-color: #2C3E50;
}
.btn-primary .badge {
  color: #2C3E50;
  background-color: white;
}
.btn-success {
  color: white;
  background-color: #18BC9C;
  border-color: #18BC9C;
  font-weight: 700;
}
.btn-success:hover,
.btn-success:focus,
.btn-success:active,
.btn-success.active,
.open .dropdown-toggle.btn-success {
  color: white;
  background-color: #128f76;
  border-color: #11866f;
}
.btn-success:active,
.btn-success.active,
.open .dropdown-toggle.btn-success {
  background-image: none;
}
.btn-success.disabled,
.btn-success[disabled],
fieldset[disabled] .btn-success,
.btn-success.disabled:hover,
.btn-success[disabled]:hover,
fieldset[disabled] .btn-success:hover,
.btn-success.disabled:focus,
.btn-success[disabled]:focus,
fieldset[disabled] .btn-success:focus,
.btn-success.disabled:active,
.btn-success[disabled]:active,
fieldset[disabled] .btn-success:active,
.btn-success.disabled.active,
.btn-success[disabled].active,
fieldset[disabled] .btn-success.active {
  background-color: #18BC9C;
  border-color: #18BC9C;
}
.btn-success .badge {
  color: #18BC9C;
  background-color: white;
}
.btn-social {
  display: inline-block;
  height: 50px;
  width: 50px;
  border: 2px solid white;
  border-radius: 100%;
  text-align: center;
  font-size: 20px;
  line-height: 45px;
}
.btn:focus,
.btn:active,
.btn.active {
  outline: none;
}
.scroll-top {
  position: fixed;
  right: 2%;
  bottom: 2%;
  width: 50px;
  height: 50px;
  z-index: 1049;
}
.scroll-top .btn {
  font-size: 20px;
  width: 50px;
  height: 50px;
  border-radius: 100%;
  line-height: 28px;
}
.scroll-top .btn:focus {
  outline: none;
}
.portfolio-modal .modal-content {
  border-radius: 0;
  background-clip: border-box;
  -webkit-box-shadow: none;
  box-shadow: none;
  border: none;
  min-height: 100%;
  padding: 100px 0;
  text-align: center;
}
.portfolio-modal .modal-content h2 {
  margin: 0;
  font-size: 3em;
}
.portfolio-modal .modal-content img {
  margin-bottom: 30px;
}
.portfolio-modal .modal-content .item-details {
  margin: 30px 0;
}
.portfolio-modal .close-modal {
  position: absolute;
  width: 75px;
  height: 75px;
  background-color: transparent;
  top: 25px;
  right: 25px;
  cursor: pointer;
}
.portfolio-modal .close-modal:hover {
  opacity: 0.3;
}
.portfolio-modal .close-modal .lr {
  height: 75px;
  width: 1px;
  margin-left: 35px;
  background-color: #2C3E50;
  transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  /* IE 9 */
  -webkit-transform: rotate(45deg);
  /* Safari and Chrome */
  z-index: 1051;
}
.portfolio-modal .close-modal .lr .rl {
  height: 75px;
  width: 1px;
  background-color: #2C3E50;
  transform: rotate(90deg);
  -ms-transform: rotate(90deg);
  /* IE 9 */
  -webkit-transform: rotate(90deg);
  /* Safari and Chrome */
  z-index: 1052;
}
.portfolio-modal .modal-backdrop {
  opacity: 0;
  display: none;
}

.panel {
  background-color: #3D3D44;
  color: #E7E7E7;
  border: 0px;
  -webkit-box-shadow: 1px 2px 3px 2px rgba(0, 0, 0, .06);
          box-shadow: 1px 2px 3px 2px rgba(0, 0, 0, .06);

}

.panel .panel-heading {
  background-color: #282830;
  color: #E7E7E7;
  font-size: 1.6em;
  border: 0px;
  -webkit-box-shadow: 0px 3px 2px 1px rgba(0, 0, 0, .05);
          box-shadow: 0px 3px 2px 1px rgba(0, 0, 0, .05);
}

.panel .panel-body p {
  font-size: 0.9em;
}

.panel > .panel-body + .table, .panel > .panel-body + .table-responsive, .panel > .table + .panel-body, .panel > .table-responsive + .panel-body {
  border: 0px;
}

.panel .table > thead > tr > th {
  text-align: center;
  font-size: 1.6em;
  border-bottom: 2px solid rgba(255, 255, 255, 0.2);
}

.panel .table > tbody > tr > td {
  border-top: 1px dashed rgba(255, 255, 255, 0.1);
}

/*Programming Languages*/
.table > tbody > tr > td:first-child {
  font-size: 1.2em;
  font-family: monospace;
  color: #23A073;
}

.skills {
  margin-top: 50px;
}

.fa-star {
  color: #D2D7D3
}
.fa-star-half {
  color: #D2D7D3
}


text:
package ucar.nc2.iosp.bufr;

import ucar.nc2.util.Indent;
import java.util.Formatter;

/**
 * Helper class for debugging BUFR descriptors
 *
 * @author caron
 * @since Nov 16, 2009
 */
class DebugOut {
  Formatter f;
  Indent indent;
  int fldno; // track fldno to compare with EU output

  DebugOut(Formatter f) {
    this.f = f;
    this.indent = new Indent(2);
    this.indent.setIndentLevel(0);
    this.fldno = 1;
  }

  String indent() {
    return indent.toString();
  }

}


text:
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

-- -----------------------------------------------------
-- Schema sistema_comision
-- -----------------------------------------------------
DROP SCHEMA IF EXISTS `sistema_comision` ;

-- -----------------------------------------------------
-- Schema sistema_comision
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `sistema_comision` DEFAULT CHARACTER SET utf8 ;
USE `sistema_comision` ;

-- -----------------------------------------------------
-- Table `sistema_comision`.`perfil_usuarios`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `sistema_comision`.`perfil_usuarios` ;

CREATE TABLE IF NOT EXISTS `sistema_comision`.`perfil_usuarios` (
  `Id` INT NOT NULL AUTO_INCREMENT,
  `nombre` VARCHAR(100) NULL,
  `descripcion` VARCHAR(300) NULL,
  PRIMARY KEY (`Id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `sistema_comision`.`direccion`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `sistema_comision`.`direccion` ;

CREATE TABLE IF NOT EXISTS `sistema_comision`.`direccion` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `calle` VARCHAR(200) NULL,
  `sector` VARCHAR(200) NULL,
  `ciudad` VARCHAR(200) NULL,
  `provincia` VARCHAR(200) NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `sistema_comision`.`persona`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `sistema_comision`.`persona` ;

CREATE TABLE IF NOT EXISTS `sistema_comision`.`persona` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `nombre` VARCHAR(200) NULL,
  `apellido` VARCHAR(200) NULL,
  `documento_identidad` VARCHAR(100) NULL,
  `sexo` CHAR(1) NULL,
  `correo` VARCHAR(100) NULL,
  `celular` VARCHAR(45) NULL,
  `direccion_id` INT NOT NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `fk_persona_direccion1`
    FOREIGN KEY (`direccion_id`)
    REFERENCES `sistema_comision`.`direccion` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

CREATE INDEX `fk_persona_direccion1_idx` ON `sistema_comision`.`persona` (`direccion_id` ASC);

CREATE INDEX `nombre` ON `sistema_comision`.`persona` (`nombre` ASC);

CREATE INDEX `apellido` ON `sistema_comision`.`persona` (`apellido` ASC);

CREATE FULLTEXT INDEX `nombre_completo` ON `sistema_comision`.`persona` (`nombre` ASC, `apellido` ASC);

CREATE INDEX `document_identidad` ON `sistema_comision`.`persona` (`documento_identidad` ASC);

-- -----------------------------------------------------
-- Table `sistema_comision`.`usuarios`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `sistema_comision`.`usuarios` ;

CREATE TABLE IF NOT EXISTS `sistema_comision`.`usuarios` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `contrasenia` VARCHAR(200) NULL,
  `desactivado` TINYINT(1) NULL,
  `persona_id` INT NOT NULL,
  `perfil_usuarios_Id` INT NOT NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `fk_usuarios_persona1`
    FOREIGN KEY (`persona_id`)
    REFERENCES `sistema_comision`.`persona` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_usuarios_perfil_usuarios1`
    FOREIGN KEY (`perfil_usuarios_Id`)
    REFERENCES `sistema_comision`.`perfil_usuarios` (`Id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

CREATE INDEX `fk_usuarios_persona1_idx` ON `sistema_comision`.`usuarios` (`persona_id` ASC);

CREATE INDEX `fk_usuarios_perfil_usuarios1_idx` ON `sistema_comision`.`usuarios` (`perfil_usuarios_Id` ASC);

-- -----------------------------------------------------
-- Table `sistema_comision`.`tipo_inmuebles`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `sistema_comision`.`tipo_inmuebles` ;

CREATE TABLE IF NOT EXISTS `sistema_comision`.`tipo_inmuebles` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `nombre` VARCHAR(200) NULL,
  `descripcion` VARCHAR(200) NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `sistema_comision`.`moneda`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `sistema_comision`.`moneda` ;

CREATE TABLE IF NOT EXISTS `sistema_comision`.`moneda` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `nombre` VARCHAR(100) NULL,
  `simbolo` VARCHAR(20) NULL,
  `tasa` DECIMAL NULL,
  `es_principal` TINYINT(1) NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `sistema_comision`.`inmuebles`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `sistema_comision`.`inmuebles` ;

CREATE TABLE IF NOT EXISTS `sistema_comision`.`inmuebles` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `detalles` VARCHAR(1000) NULL,
  `precio` DECIMAL NULL,
  `superficie` VARCHAR(50) NULL,
  `dormitorios` INT NULL,
  `tipo_inmuebles_id` INT NOT NULL,
  `direccion_id` INT NOT NULL,
  `moneda_id` INT NOT NULL,
  `comision_venta` DECIMAL NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `fk_inmuebles_tipo_inmuebles1`
    FOREIGN KEY (`tipo_inmuebles_id`)
    REFERENCES `sistema_comision`.`tipo_inmuebles` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_inmuebles_direccion1`
    FOREIGN KEY (`direccion_id`)
    REFERENCES `sistema_comision`.`direccion` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_inmuebles_moneda1`
    FOREIGN KEY (`moneda_id`)
    REFERENCES `sistema_comision`.`moneda` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

CREATE INDEX `fk_inmuebles_tipo_inmuebles1_idx` ON `sistema_comision`.`inmuebles` (`tipo_inmuebles_id` ASC);

CREATE INDEX `fk_inmuebles_direccion1_idx` ON `sistema_comision`.`inmuebles` (`direccion_id` ASC);

CREATE INDEX `fk_inmuebles_moneda1_idx` ON `sistema_comision`.`inmuebles` (`moneda_id` ASC);

-- -----------------------------------------------------
-- Table `sistema_comision`.`ventas`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `sistema_comision`.`ventas` ;

CREATE TABLE IF NOT EXISTS `sistema_comision`.`ventas` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `usuarios_id` INT NOT NULL,
  `moneda_id` INT NOT NULL,
  `persona_id` INT NOT NULL,
  `precio` DECIMAL NULL,
  `inmuebles_id` INT NOT NULL,
  PRIMARY KEY (`id`, `inmuebles_id`),
  CONSTRAINT `fk_ventas_usuarios1`
    FOREIGN KEY (`usuarios_id`)
    REFERENCES `sistema_comision`.`usuarios` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_ventas_inmuebles1`
    FOREIGN KEY (`id`)
    REFERENCES `sistema_comision`.`inmuebles` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_ventas_moneda1`
    FOREIGN KEY (`moneda_id`)
    REFERENCES `sistema_comision`.`moneda` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_ventas_persona1`
    FOREIGN KEY (`persona_id`)
    REFERENCES `sistema_comision`.`persona` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_ventas_inmuebles2`
    FOREIGN KEY (`inmuebles_id`)
    REFERENCES `sistema_comision`.`inmuebles` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

CREATE INDEX `fk_ventas_usuarios1_idx` ON `sistema_comision`.`ventas` (`usuarios_id` ASC);

CREATE INDEX `fk_ventas_inmuebles1_idx` ON `sistema_comision`.`ventas` (`id` ASC);

CREATE INDEX `fk_ventas_moneda1_idx` ON `sistema_comision`.`ventas` (`moneda_id` ASC);

CREATE INDEX `fk_ventas_persona1_idx` ON `sistema_comision`.`ventas` (`persona_id` ASC);

CREATE INDEX `fk_ventas_inmuebles2_idx` ON `sistema_comision`.`ventas` (`inmuebles_id` ASC);

-- -----------------------------------------------------
-- Table `sistema_comision`.`auditoria`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `sistema_comision`.`auditoria` ;

CREATE TABLE IF NOT EXISTS `sistema_comision`.`auditoria` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `tabla` VARCHAR(45) NULL,
  `registro_id` INT NOT NULL,
  `action` VARCHAR(45) NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

USE `sistema_comision`;

DELIMITER $$

USE `sistema_comision`$$
DROP TRIGGER IF EXISTS `sistema_comision`.`usuarios_AFTER_INSERT` $$
USE `sistema_comision`$$
CREATE DEFINER = CURRENT_USER TRIGGER `sistema_comision`.`usuarios_AFTER_INSERT` AFTER INSERT ON `usuarios` FOR EACH ROW
BEGIN
INSERT INTO `auditoria` (`tabla`, `registro_id`, `action`) values("usuarios", NEW.id, "insert");
END$$

USE `sistema_comision`$$
DROP TRIGGER IF EXISTS `sistema_comision`.`usuarios_AFTER_UPDATE` $$
USE `sistema_comision`$$
CREATE DEFINER = CURRENT_USER TRIGGER `sistema_comision`.`usuarios_AFTER_UPDATE` AFTER UPDATE ON `usuarios` FOR EACH ROW
BEGIN
INSERT INTO `auditoria` (`tabla`, `registro_id`, `action`)  values("usuarios", OLD.id, "update");
END$$

USE `sistema_comision`$$
DROP TRIGGER IF EXISTS `sistema_comision`.`usuarios_BEFORE_DELETE` $$
USE `sistema_comision`$$
CREATE DEFINER = CURRENT_USER TRIGGER `sistema_comision`.`usuarios_BEFORE_DELETE` BEFORE DELETE ON `usuarios` FOR EACH ROW
BEGIN
INSERT INTO `auditoria` (`tabla`, `registro_id`, `action`)  values("usuarios", OLD.id, "delete");
END$$

USE `sistema_comision`$$
DROP TRIGGER IF EXISTS `sistema_comision`.`ventas_AFTER_INSERT` $$
USE `sistema_comision`$$
CREATE DEFINER = CURRENT_USER TRIGGER `sistema_comision`.`ventas_AFTER_INSERT` AFTER INSERT ON `ventas` FOR EACH ROW
BEGIN
INSERT INTO `auditoria` (`tabla`, `registro_id`, `action`)  values("ventas", NEW.id, "insert");
END$$

USE `sistema_comision`$$
DROP TRIGGER IF EXISTS `sistema_comision`.`ventas_AFTER_UPDATE` $$
USE `sistema_comision`$$
CREATE DEFINER = CURRENT_USER TRIGGER `sistema_comision`.`ventas_AFTER_UPDATE` AFTER UPDATE ON `ventas` FOR EACH ROW
BEGIN
INSERT INTO `auditoria` (`tabla`, `registro_id`, `action`)  values("ventas", NEW.id, "update");
END$$

USE `sistema_comision`$$
DROP TRIGGER IF EXISTS `sistema_comision`.`ventas_AFTER_DELETE` $$
USE `sistema_comision`$$
CREATE DEFINER = CURRENT_USER TRIGGER `sistema_comision`.`ventas_AFTER_DELETE` AFTER DELETE ON `ventas` FOR EACH ROW
BEGIN
INSERT INTO `auditoria` (`tabla`, `registro_id`, `action`)  values("ventas", OLD.id, "delete");
END$$

DELIMITER ;
SET SQL_MODE = '';
GRANT USAGE ON *.* TO usuario_sistemas_comisiones;
 DROP USER usuario_sistemas_comisiones;
SET SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
CREATE USER 'usuario_sistemas_comisiones' IDENTIFIED BY '123456';

GRANT ALL ON `sistema_comision`.* TO 'usuario_sistemas_comisiones';
GRANT SELECT ON TABLE `sistema_comision`.* TO 'usuario_sistemas_comisiones';
GRANT SELECT, INSERT, TRIGGER ON TABLE `sistema_comision`.* TO 'usuario_sistemas_comisiones';
GRANT SELECT, INSERT, TRIGGER, UPDATE, DELETE ON TABLE `sistema_comision`.* TO 'usuario_sistemas_comisiones';
GRANT EXECUTE ON ROUTINE `sistema_comision`.* TO 'usuario_sistemas_comisiones';

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;


text:
<?xml version="1.0" encoding="UTF-8"?>
<localEntry xmlns="http://ws.apache.org/ns/synapse" key="{0}" src="{1}"/>


text:
package de.meldanor.unsafeme;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * @author Kilian Gärtner
 * @since 24.07.2015
 */
public class UnsafeSerializerTest {

    @Test
    public void testSimpleClass() throws Exception {
        UnsafeSerializer<String> stringSerializer = new UnsafeSerializer<>(new StringSerializer());

        Human objectOne = new Human("Felix", 18, 60.7);
        Human objectTwo = new Human("Tim", 1, 5.2);
        Human nonHuman = new Human("Jesus", -1, 3.141592653589793);

        assertEquals("" +
                        "age: 18" + System.lineSeparator() +
                        "mass: 60.7" + System.lineSeparator() +
                        "name: Felix" + System.lineSeparator(),
                stringSerializer.serialize(objectOne));

        assertEquals("" +
                        "age: 1" + System.lineSeparator() +
                        "mass: 5.2" + System.lineSeparator() +
                        "name: Tim" + System.lineSeparator(),
                stringSerializer.serialize(objectTwo));

        assertEquals("" +
                        "age: -1" + System.lineSeparator() +
                        "mass: 3.141592653589793" + System.lineSeparator() +
                        "name: Jesus" + System.lineSeparator(),
                stringSerializer.serialize(nonHuman));

        assertEquals("null", stringSerializer.serialize(null));
    }

    @SuppressWarnings("unused")
    private static class Human {
        private final String name;
        private int age;
        private double mass;

        public Human(String name, int age, double mass) {
            this.name = name;
            this.age = age;
            this.mass = mass;
        }
    }

    @Test
    public void testAllDatatypesSerializer() throws Exception {

        UnsafeSerializer<String> stringSerializer = new UnsafeSerializer<>(new StringSerializer());
        AllDataTypesClass objectOne = new AllDataTypesClass(true, 'a', (byte) 64, (short) 16384, 1073741824,
                1073741824L, 1.1F, 2.2F, "Hi");

        assertEquals("" +
                "aBoolean: true" + System.lineSeparator() +
                "aByte: 64" + System.lineSeparator() +
                "aChar: a" + System.lineSeparator() +
                "aDouble: 2.200000047683716" + System.lineSeparator() +
                "aFloat: 1.1" + System.lineSeparator() +
                "aLong: 1073741824" + System.lineSeparator() +
                "aShort: 16384" + System.lineSeparator() +
                "anInt: 1073741824" + System.lineSeparator() +
                "string: Hi" + System.lineSeparator(), stringSerializer.serialize(objectOne));
    }

    @SuppressWarnings("unused")
    private static class AllDataTypesClass {
        private final boolean aBoolean;
        private final char aChar;
        private final byte aByte;
        private final short aShort;
        private final int anInt;
        private final long aLong;
        private final float aFloat;
        private final double aDouble;
        private final String string;

        public AllDataTypesClass(boolean aBoolean, char aChar, byte aByte, short aShort, int anInt, long aLong,
                                 float aFloat, double aDouble, String string) {
            this.aBoolean = aBoolean;
            this.aChar = aChar;
            this.aByte = aByte;
            this.aShort = aShort;
            this.anInt = anInt;
            this.aLong = aLong;
            this.aFloat = aFloat;
            this.aDouble = aDouble;
            this.string = string;
        }
    }
}


text:
inject_into_file "app/helpers/application_helper.rb", after: "module ApplicationHelper\n" do
<<-EOF

  def link_for obj, name = :name, i: false, b: false
    return nil unless obj
    raise "not respond to \#{name}" unless obj.respond_to? name

    html = link_to obj.send(name), obj
    html = content_tag :i, html if i
    html = content_tag :b, html if b
    html
  end
EOF
end


text:
<?php

namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;
use JMS\SecurityExtraBundle\Annotation\Secure;
use AppBundle\Entity\File;
use AppBundle\Form\FileType;

/**
 * File controller.
 *
 * @Route("/file")
 */
class FileController extends Controller
{

    /**
     * Lists all File entities.
     *
     * @Route("/", name="file")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('AppBundle:File')->findReleased();
        $maps = $em->getRepository('AppBundle:Map')->findMaps();

        return array(
            'entities' => $entities,
            'maps' => $maps,
        );
    }
    /**
     * Creates a new File entity.
     *
     * @Route("/{map}/create", name="file_create")
     * @Method("POST")
     * @Template("AppBundle:File:new.html.twig")
     */
    public function createAction(Request $request, $map)
    {
        $entity = new File();
        $user = $this->getUser();
        $entity->setUser($user);
        $form = $this->createCreateForm($entity, $map);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('myuploads'));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a form to create a File entity.
     *
     * @param File $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(File $entity, $map)
    {
        $options = array('mapid' => $map);
        $form = $this->createForm(new FileType($options), $entity, array(
            'action' => $this->generateUrl('file_create', array('map' => $map)),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new File entity.
     *
     * @Route("/{map}/new", name="file_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction($map)
    {
        $entity = new File();
        $form   = $this->createCreateForm($entity, $map);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a File entity.
     *
     * @Route("/{id}/show", name="file_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AppBundle:File')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find File entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Finds and displays a File.
     *
     * @Route("/{id}/get", name="file_get")
     *
     */
    public function getAction($id)
    {

        $em = $this->getDoctrine()->getManager();
        $file = $em->getRepository('AppBundle:File')->find($id);

        $helper = $this->container->get('vich_uploader.templating.helper.uploader_helper');
        $path = $helper->asset($file, 'file');
        $ext = strtolower($file->getExt());

        $response = new Response();

        $response->setStatusCode(200);
        switch ($ext) {
            case "png":
                $response->headers->set('Content-Type', 'image/png');
                break;
            case "gif":
                $response->headers->set('Content-Type', 'image/gif');
                break;
            case "jpeg":
                $response->headers->set('Content-Type', 'image/jpeg');
                break;
            case "jpg":
                $response->headers->set('Content-Type', 'image/jpeg');
                break;
            default:
                $response->headers->set('Content-Type', 'application/octet-stream');
        }
        $response->setContent(file_get_contents($path));

        return $response;
    }

    /**
     * Displays a form to edit an existing File entity.
     *
     * @Route("/{id}/edit", name="file_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AppBundle:File')->find($id);
        $map = $entity->getLocation()->getMap()->getId();

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find File entity.');
        }

        $editForm = $this->createEditForm($entity, $map);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a File entity.
    *
    * @param File $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(File $entity, $map)
    {
        $options = array('mapid' => $map);
        $form = $this->createForm(new FileType($options), $entity, array(
            'action' => $this->generateUrl('file_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing File entity.
     *
     * @Route("/{id}", name="file_update")
     * @Method("PUT")
     * @Template("AppBundle:File:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AppBundle:File')->find($id);
        $map = $entity->getLocation()->getMap()->getId();

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find File entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity, $map);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('file'));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a File entity.
     *
     * @Route("/{id}", name="file_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('AppBundle:File')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find File entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('myuploads'));
    }

    /**
     * Creates a form to delete a File entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('file_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }

    /**
     * Lists all Point entities.
     *
     * @Route("/myuploads", name="myuploads")
     * @Method("GET")
     * @Template("AppBundle:File:index.html.twig")
     */
    public function myFilesAction()
    {
        $em = $this->getDoctrine()->getManager();
        $user = $this->getUser();

        $entities = $em->getRepository('AppBundle:File')->findMine($user);
        $maps = $em->getRepository('AppBundle:Map')->findMaps();

        return array(
            'entities' => $entities,
            'maps' => $maps,
        );
    }

    /**
     * Lists all unreleased Point entities.
     *
     * @Secure(roles="ROLE_ADMIN")
     * @Route("/upload_pending", name="upload_pending")
     * @Method("GET")
     * @Template("AppBundle:File:index.html.twig")
     */
    public function pendingAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('AppBundle:File')->findPending();
        $maps = $em->getRepository('AppBundle:Map')->findAll();

        return array(
            'entities' => $entities,
            'maps' => $maps,
        );
    }

    /**
     * Releases an existing Point entity.
     *
     * @Secure(roles="ROLE_ADMIN")
     * @Route("/{id}/release", name="file_release")
     * @Method("GET")
     * @Template("AppBundle:File:index.html.twig")
     */
    public function releaseAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AppBundle:File')->find($id);
        $entity->setStatus(1);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find File entity.');
        }

        $em->flush();

        return $this->redirect($this->generateUrl('file'));
    }

}


text:
package nextmethod.web.razor;

public interface State {

    StateMachine.StateResult invoke();

}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Basic usage:
 *
 * Loading it from your controller:
 *
 * $this->load->library('ChromeLogger');
 *
 * Basic usage:
 *
 * [SEND INFO, $var can be anything ]:
 * $this->chromelogger->info($var = 'This is an INFO message');
 *
 * [SEND WARNING, $var can be anything ]:
 * $this->chromelogger->warn($var = 'This is a WARN message');
 *
 * [SEND ERROR, $var can be anything ]:
 * $this->chromelogger->error($var = 'This is an ERROR message');
 *
 * [JUST LOG, $var can be anything ]:
 * $this->chromelogger->log($var = 'This is just a LOG');
 *
 * [GROUP, Send information grouped, $var is the header for that group ]:
 * $this->chromelogger->group($var = 'Group I');
 * $this->chromelogger->info('Some info for group I');
 * $this->chromelogger->info('Some more info for group I');
 * $this->chromelogger->group_end();
 *
 * $this->chromelogger->group($var = 'Group II');
 * $this->chromelogger->info('Some info for group II');
 * $this->chromelogger->info('Some more info for group II');
 * $this->chromelogger->group_end();
 *
 * [GROUP COLLAPSED, Same as group() only it will send it so that it is collapsed on console, $var is the header for that group ]:
 * $this->chromelogger->group_collapsed($var = 'Group II');
 * $this->chromelogger->info('Some info for group II');
 * $this->chromelogger->info('Some more info for group II');
 * $this->chromelogger->group_end();
 *
 * [TABLE, will display the info as an ordered table on console, $var can be anything but preferably a list of objects so it actually makes sense ]:
 * $p1 = new Person('John', 'Wayne', 'M');
 * $p2 = new Person('Gena', 'Rowllands', 'F');
 * $p3 = new Person('Clark', 'Gable', 'M');
 *
 * $this->chromelogger->table($p1, $p2, $p3);
 */

require_once('ChromePhp/ChromePhp.php');

class Chrome_logger {

	private $chromephp = NULL;
	private $log_allowed = FALSE;
	private $log_refusal_msg = '';
	private $log_refusal_sent = FALSE;

	public function __construct()
	{
		//Save this as reference so we have it availlable through all our instance
		$this->chromephp =& ChromePhp::getInstance();

		if(defined('ENVIRONMENT'))
		{
			switch (ENVIRONMENT)
			{
				case 'development':
					$this->log_allowed = TRUE;
				break;

				case 'testing':
				case 'production':
					$this->log_allowed = FALSE;
					$this->log_refusal_msg = "'ENVIRONMENT' constant not set to 'development' therefore, for security reasons, backtrace and logs from server are not shown. Set 'ENVIRONMENT' constant to 'development' to show such info here.";
					$log_refusal_sent = TRUE;
				break;

				default:
					$this->log_allowed = FALSE;
					$this->log_refusal_msg = "The application 'ENVIRONMENT' constant is set incorrectly. You must set it to 'development' in order to show server backtraces and logs here.";
					$log_refusal_sent = TRUE;
			}
		}
		else
		{
			$this->log_allowed = FALSE;
			$this->log_refusal_msg = 'Application environment constant not set, so you cannot use this library!';
		}

		if($this->log_allowed == TRUE)
		{
			//Change backtrace level to 2, otherwise we are going to get all backtrace info sent
			//from the main ChromePhp.php file and ChromePhp class since we are wrapping it here
			$this->chromephp->addSetting( ChromePHP::BACKTRACE_LEVEL, '2' );
		}
		else
		{
			//dont show the actual file that initially generated the backtrace log refusal for security reasons
			$this->chromephp->addSetting( ChromePHP::BACKTRACE_LEVEL, '-1' );
		}
	}

	private function is_logging_output_allowed()
	{
		if($this->log_allowed == FALSE)
		{
			//send header for refusal reason only once, at least for the current instance
			if($this->log_refusal_sent == FALSE)
			{
				$this->chromephp->log($this->log_refusal_msg);
				$this->log_refusal_sent = TRUE;
			}

			return FALSE;
		}

		return TRUE;
	}

	public function log()
	{
		if($this->is_logging_output_allowed())
		{
			return $this->chromephp->log( func_get_args() );
		}
	}

	public function warn()
	{
		if($this->is_logging_output_allowed())
		{
			return $this->chromephp->warn( func_get_args() );
		}
	}

	public function error()
	{
		if($this->is_logging_output_allowed())
		{
			return $this->chromephp->error( func_get_args() );
		}
	}

	public function group()
	{
		if($this->is_logging_output_allowed())
		{
			return $this->chromephp->group( func_get_args() );
		}
	}

	public function info()
	{
		if($this->is_logging_output_allowed())
		{
			return $this->chromephp->info( func_get_args() );
		}
	}

	public function group_collapsed()
	{
		if($this->is_logging_output_allowed())
		{
			return $this->chromephp->groupCollapsed( func_get_args() );
		}
	}

	public function group_end()
	{
		if($this->is_logging_output_allowed())
		{
			return $this->chromephp->groupEnd( func_get_args() );
		}
	}

	public function table()
	{
		if($this->is_logging_output_allowed())
		{
			return $this->chromephp->table( func_get_args() );
		}
	}

	public function add_setting($key, $value)
	{
		if($this->is_logging_output_allowed())
		{
			$this->chromephp->addSetting($key, $value);
		}
	}

	public function add_settings($settings)
	{
		if($this->is_logging_output_allowed())
		{
			$this->chromephp->addSettings($settings);
		}
	}

	public function get_setting($key)
	{
		if($this->is_logging_output_allowed())
		{
			return $this->chromephp->getSetting($key);
		}

		return NULL;
	}
}


text:
package com.google.gdata.data.dublincore;

import com.google.gdata.data.ExtensionDescription;
import com.google.gdata.data.ValueConstruct;

/**
 * Language of the resource.
 *
 *
 */
@ExtensionDescription.Default(
    nsAlias = DublincoreNamespace.DC_ALIAS,
    nsUri = DublincoreNamespace.DC,
    localName = Language.XML_NAME)
public class Language extends ValueConstruct {

  /** XML element name */
  static final String XML_NAME = "language";

  /**
   * Default mutable constructor.
   */
  public Language() {
    this(null);
  }

  /**
   * Constructor (mutable or immutable).
   *
   * @param value immutable value or null for a mutable value
   */
  public Language(String value) {
    super(DublincoreNamespace.DC_NS, XML_NAME, null, value);
  }

  /**
   * Returns the extension description, specifying whether it is required, and
   * whether it is repeatable.
   *
   * @param required   whether it is required
   * @param repeatable whether it is repeatable
   * @return extension description
   */
  public static ExtensionDescription getDefaultDescription(boolean required,
      boolean repeatable) {
    ExtensionDescription desc =
        ExtensionDescription.getDefaultDescription(Language.class);
    desc.setRequired(required);
    desc.setRepeatable(repeatable);
    return desc;
  }

  @Override
  public String toString() {
    return "{Language value=" + getValue() + "}";
  }

}


text:
<!DOCTYPE html>

  <title>backgrid-text-cell</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="X-UA-Compatible" content="chrome=1">
  <meta name="fragment" content="!">

  <link rel="shortcut icon" type="image/ico" href="favicon.ico" />
  <link rel="stylesheet" href="resources/css/app-0b2d94a756da271cc9ed4a65f4837560.css" type="text/css" />

backgrid-text-cell

backgrid-text-cell

Backgrid.js Extensions

TextCell

Backgrid.Extension.TextCell

Backgrid.Extension.TextareaEditor

Generated on Wed 01 Feb 2017 19:16:37 by JSDuck 4.10.4.


text:
all: image tag

IMAGE=okernel
OKERNEL_REPO=https://github.com/linux-okernel/linux-okernel
DEPS=Dockerfile.okernel Makefile kernel_config.okernel Dockerfile.kvmod

DEBUG ?= 0

ifdef KERNEL
ifneq ($(KERNEL),latest)
ifneq (,$(findstring ok-,$(KERNEL)))
KERNEL_VERSION=$(KERNEL)
IMAGE_VERSION=$(KERNEL_VERSION)
LATEST=0
else
$(error Error, valid okernel kernel versions begin with "ok-")
endif
else
KERNEL_VERSION=linux-okernel
IMAGE_VERSION=$(shell git ls-remote --tags $(OKERNEL_REPO) ok-\* | awk -F"/" '{print $$3}' | tail -1)
LATEST=1
endif
else
KERNEL_VERSION=linux-okernel
IMAGE_VERSION=$(shell git ls-remote --tags $(OKERNEL_REPO) ok-\* | awk -F"/" '{print $$3}' | tail -1)
LATEST=1
endif

ifdef HTTP_PROXY
	PROXY_ARG = --build-arg HTTP_PROXY=$(HTTP_PROXY)
endif

ifdef HTTPS_PROXY
	PROXY_ARG += --build-arg HTTPS_PROXY=$(HTTPS_PROXY)
endif

.PHONY: image push tag kvmod
image: $(DEPS)
	BUILD=$$( tar cf - $^ | docker build -f $< $(PROXY_ARG) --build-arg DEBUG=$(DEBUG) --build-arg KERNEL_VERSION=$(KERNEL_VERSION) -q -t $(IMAGE):build - ) && [ -n "$$BUILD" ] && echo "Built $$BUILD" && echo "$$BUILD" > build_info

default: tag

kvmod:
	docker build --no-cache --build-arg IMAGE=$(IMAGE):$(IMAGE_VERSION) -t okernel-kvmod:$(IMAGE_VERSION) - < Dockerfile.kvmod

push: image
	(docker tag $(IMAGE):build $(IMAGE):$(IMAGE_VERSION) && \
	 docker push $(IMAGE):$(IMAGE_VERSION))
	docker rmi $(IMAGE):build
	rm -f hash

tag: image
	docker tag $(IMAGE):build $(IMAGE):$(IMAGE_VERSION)
ifeq (1,$(LATEST))
	docker tag $(IMAGE):build $(IMAGE):latest
endif
	docker rmi $(IMAGE):build
	rm -f hash

.PHONY: clean
clean:
	rm -f build_info

.DELETE_ON_ERROR:


text:
package com.bj58;

public class T {

}


text:
package org.builditbreakit.seada.logappend;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.builditbreakit.seada.common.data.GalleryState;
import org.builditbreakit.seada.common.io.LogFileReader;
import org.builditbreakit.seada.logappend.io.LogFileWriter;

public class GalleryUpdateManager {

	private Map<String, GalleryUpdate> states = new HashMap<String, GalleryUpdate>();

	private static final Pattern cantBeFile = Pattern.compile(".*/$");

	/**
	 * Find the existing gallery state for a particular path -- or create a new one, if
	 * the path doesn't exist yet. This allows the same state to be reused without being
	 * read/written between each use.
	 */
	public GalleryUpdate getGalleryFor(AppendCommand cmd) throws IOException, SecurityException {
		String lf = cmd.getLogfile();
		File f;
		// Special handling of empty filename to match oracle's (mis)behavior:
		if (lf.isEmpty()) {
			f = File.createTempFile(".empty", ".tmp");
			f.deleteOnExit();
		} else {
			Matcher m = cantBeFile.matcher(lf);
			if (m.matches()) {
				throw new IOException("Bad logfile.");
			}
			f = new File(lf);
		}
		String password = cmd.getToken();
		// Convert to canonical version of path so different paths to the same logfile
		// are resolved to the same thing.
		String key = f.getCanonicalPath();
		GalleryUpdate item = states.get(key);
		if (item == null) {
			GalleryState state;
			if (f.exists()) {
				LogFileReader reader = new LogFileReader(new File(key));
				state = reader.read(password);
			} else {
				state = new GalleryState();
			}
			item = new GalleryUpdate(state, f, password);
			states.put(key, item);
		} else if (!item.password.equals(password)) {
			throw new IllegalArgumentException("Can't change password now.");
		}
		return item;
	}

	public boolean save() {
		boolean ok = true;
		for (GalleryUpdate item : states.values()) {
			if (item.modified) {
				try {
					LogFileWriter writer = new LogFileWriter(item.path);
					writer.write(item.state, item.password);
				} catch (IOException e) {
					System.out.println("invalid");
					ok = false;
				}
			}
		}
		return ok;
	}

}


text:
package org.odlabs.wiquery.ui.selectable;

import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.odlabs.wiquery.core.behavior.WiQueryAbstractBehavior;
import org.odlabs.wiquery.core.javascript.JsQuery;
import org.odlabs.wiquery.core.javascript.JsStatement;
import org.odlabs.wiquery.core.options.Options;
import org.odlabs.wiquery.ui.commons.WiQueryUIPlugin;
import org.odlabs.wiquery.ui.core.JsScopeUiEvent;
import org.odlabs.wiquery.ui.mouse.MouseJavaScriptResourceReference;
import org.odlabs.wiquery.ui.widget.WidgetJavaScriptResourceReference;

/**
 * $Id$
 *

 * Wicket behabior to use the JQuery UI Selectable behavior
 *

 *
 * * Example : Java code:
 * 	    List<String> values = Arrays.asList(
	    		"Value 1",
	    		"Value 2",
	    		"Value 3",
	    		"Value 4",
	    		"Value 5");

	    ListView<String> listView = new ListView<String>("listView", values) {
 *
 * @Override protected void populateItem(ListItem<String> item) { item.add(new
 *           Label("item", item.getModel())); } };
 *
 *           WebMarkupContainer selectableWicket = new
 *           WebMarkupContainer("selectableWicket"); selectableWicket.add(new
 *           SelectableBehavior()); selectableWicket.add(listView); add(selectableWicket);
 *
 *
 *           HTML code:
 *

 *
 *
 * @author Julien Roche
 * @since 1.0
 */
@WiQueryUIPlugin
public class SelectableBehavior extends WiQueryAbstractBehavior
{
	/**
	 * Enumeration for the tolerance option
	 *
	 * @author Julien Roche
	 *
	 */
	public enum ToleranceEnum
	{
		TOUCH,
		FIT;
	}

	// Constants
	/** Constant of serialization */
	private static final long serialVersionUID = 2L;

	// Properties
	private Options options;

	/**
	 * Default constructor
	 */
	public SelectableBehavior()
	{
		super();
		options = new Options();
	}

	@Override
	public void onBind()
	{
		super.onBind();
		options.setOwner(getComponent());
	}

	@Override
	public void detach(Component component)
	{
		super.detach(component);
		options.detach();
	}

	@Override
	public void renderHead(Component component, IHeaderResponse response)
	{
		response.renderJavaScriptReference(WidgetJavaScriptResourceReference.get());
		response.renderJavaScriptReference(MouseJavaScriptResourceReference.get());
		response.renderJavaScriptReference(SelectableJavaScriptResourceReference.get());
	}

	/**
	 * @return the cancel option value
	 */
	public String getCancel()
	{
		String cancel = this.options.getLiteral("cancel");
		return cancel == null ? "input,option" : cancel;
	}

	/**
	 * @return the delay option value
	 */
	public int getDelay()
	{
		if (this.options.containsKey("delay"))
		{
			return this.options.getInt("delay");
		}

		return 0;
	}

	/**
	 * @return the distance option value
	 */
	public int getDistance()
	{
		if (this.options.containsKey("distance"))
		{
			return this.options.getInt("distance");
		}

		return 0;
	}

	/**
	 * @return the cancel option value
	 */
	public String getFilter()
	{
		String filter = this.options.getLiteral("filter");
		return filter == null ? "*" : filter;
	}

	/**
	 * Method retrieving the options of the component
	 *
	 * @return the options
	 */
	protected Options getOptions()
	{
		return options;
	}

	/**
	 * @return the tolerance option enum
	 */
	public ToleranceEnum getTolerance()
	{
		String tolerance = this.options.getLiteral("tolerance");
		return tolerance == null ? ToleranceEnum.TOUCH : ToleranceEnum.valueOf(tolerance
			.toUpperCase());
	}

	/**
	 * @return the autoRefresh option enum
	 */
	public boolean isAutoRefresh()
	{
		if (this.options.containsKey("autoRefresh"))
		{
			return this.options.getBoolean("autoRefresh");
		}

		return true;
	}

	/**
	 * This determines whether to refresh (recalculate) the position and size of each
	 * selected at the beginning of each select operation. If you have many many items,
	 * you may want to set this to false and call the refresh method manually.
	 *
	 * @param autoRefresh
	 * @return instance of the current behavior
	 */
	public SelectableBehavior setAutoRefresh(boolean autoRefresh)
	{
		this.options.put("autoRefresh", autoRefresh);
		return this;
	}

	/**
	 * Disables (true) or enables (false) the selectable. Can be set when initialising
	 * (first creating) the selectable.
	 *
	 * @param disabled
	 * @return instance of the current behavior
	 */
	public SelectableBehavior setDisabled(boolean disabled)
	{
		this.options.put("disabled", disabled);
		return this;
	}

	/**
	 * @return the disabled option
	 */
	public boolean isDisabled()
	{
		if (this.options.containsKey("disabled"))
		{
			return this.options.getBoolean("disabled");
		}

		return false;
	}

	/**
	 * Set's the prevent selecting if you start on elements matching the selector
	 *
	 * @param cancel
	 *            Selector (default : ':input,option')
	 * @return instance of the current behavior
	 */
	public SelectableBehavior setCancel(String cancel)
	{
		this.options.putLiteral("cancel", cancel);
		return this;
	}

	/**
	 * Set's the delay (in milliseconds) to define when the selecting should start
	 *
	 * @param delay
	 * @return instance of the current behavior
	 */
	public SelectableBehavior setDelay(int delay)
	{
		this.options.put("delay", delay);
		return this;
	}

	/**
	 * Set's the tolerance in pixels
	 *
	 * @param distance
	 * @return instance of the current behavior
	 */
	public SelectableBehavior setDistance(int distance)
	{
		this.options.put("distance", distance);
		return this;
	}

	/**
	 * Set's the matching child to be selectable
	 *
	 * @param filter
	 *            Selector (default : '*')
	 * @return instance of the current behavior
	 */
	public SelectableBehavior setFilter(String filter)
	{
		this.options.putLiteral("filter", filter);
		return this;
	}

	/**
	 * Set's the tolerance
	 *

	 *
fit: draggable overlaps the droppable entirely

	 *
touch: draggable overlaps the droppable any amount

	 *

	 *
	 * @param tolerance
	 * @return instance of the current behavior
	 */
	public SelectableBehavior setTolerance(ToleranceEnum tolerance)
	{
		this.options.putLiteral("tolerance", tolerance.toString().toLowerCase());
		return this;
	}

	@Override
	public JsStatement statement()
	{
		return new JsQuery(this.getComponent()).$().chain("selectable",
			this.options.getJavaScriptOptions());
	}

	/*---- Events section ----*/
	/**
	 * Set's the selected event This event is triggered at the end of the select
	 * operation, on each element added to the selection.
	 *
	 * @param selected
	 *            Associated JsScopeUiEvent
	 * @return instance of the current behavior
	 */
	public SelectableBehavior setSelectedEvent(JsScopeUiEvent selected)
	{
		this.options.put("selected", selected);
		return this;
	}

	/**
	 * Set's the selecting event This event is triggered during the select operation, on
	 * each element added to the selection.
	 *
	 * @param selecting
	 *            Associated JsScopeUiEvent
	 * @return instance of the current behavior
	 */
	public SelectableBehavior setSelectingEvent(JsScopeUiEvent selecting)
	{
		this.options.put("selecting", selecting);
		return this;
	}

	/**
	 * Set's the start event This event is triggered at the beginning of the select
	 * operation.
	 *
	 * @param start
	 *            Associated JsScopeUiEvent
	 * @return instance of the current behavior
	 */
	public SelectableBehavior setStartEvent(JsScopeUiEvent start)
	{
		this.options.put("start", start);
		return this;
	}

	/**
	 * Set's the stop event This event is triggered at the end of the select operation.
	 *
	 * @param stop
	 *            Associated JsScopeUiEvent
	 * @return instance of the current behavior
	 */
	public SelectableBehavior setStopEvent(JsScopeUiEvent stop)
	{
		this.options.put("stop", stop);
		return this;
	}

	/**
	 * Set's the unselected event This event is triggered at the end of the select
	 * operation, on each element removed from the selection.
	 *
	 * @param unselected
	 *            Associated JsScopeUiEvent
	 * @return instance of the current behavior
	 */
	public SelectableBehavior setUnselectedEvent(JsScopeUiEvent unselected)
	{
		this.options.put("unselected", unselected);
		return this;
	}

	/**
	 * Set's the unselecting event This event is triggered during the select operation, on
	 * each element removed from the selection.
	 *
	 * @param unselecting
	 *            Associated JsScopeUiEvent
	 * @return instance of the current behavior
	 */
	public SelectableBehavior setUnselectingEvent(JsScopeUiEvent unselecting)
	{
		this.options.put("unselecting", unselecting);
		return this;
	}

	/*---- Methods section ----*/
	/**
	 * Method to destroy This will return the element back to its pre-init state.
	 *
	 * @return the associated JsStatement
	 */
	public JsStatement destroy()
	{
		return new JsQuery(getComponent()).$().chain("selectable", "'destroy'");
	}

	/**
	 * Method to destroy within the ajax request
	 *
	 * @param ajaxRequestTarget
	 */
	public void destroy(AjaxRequestTarget ajaxRequestTarget)
	{
		ajaxRequestTarget.appendJavaScript(this.destroy().render().toString());
	}

	/**
	 * Method to disable
	 *
	 * @return the associated JsStatement
	 */
	public JsStatement disable()
	{
		return new JsQuery(getComponent()).$().chain("selectable", "'disable'");
	}

	/**
	 * Method to disable within the ajax request
	 *
	 * @param ajaxRequestTarget
	 */
	public void disable(AjaxRequestTarget ajaxRequestTarget)
	{
		ajaxRequestTarget.appendJavaScript(this.disable().render().toString());
	}

	/**
	 * Method to enable
	 *
	 * @return the associated JsStatement
	 */
	public JsStatement enable()
	{
		return new JsQuery(getComponent()).$().chain("selectable", "'enable'");
	}

	/**
	 * Method to enable within the ajax request
	 *
	 * @param ajaxRequestTarget
	 */
	public void enable(AjaxRequestTarget ajaxRequestTarget)
	{
		ajaxRequestTarget.appendJavaScript(this.enable().render().toString());
	}

	/**
	 * Method to refresh
	 *
	 * @return the associated JsStatement
	 */
	public JsStatement refresh()
	{
		return new JsQuery(getComponent()).$().chain("selectable", "'refresh'");
	}

	/**
	 * Method to refresh within the ajax request
	 *
	 * @param ajaxRequestTarget
	 */
	public void refresh(AjaxRequestTarget ajaxRequestTarget)
	{
		ajaxRequestTarget.appendJavaScript(this.refresh().render().toString());
	}

	/**
	 * Method to returns the .ui-selectable element
	 *
	 * @return the associated JsStatement
	 */
	public JsStatement widget()
	{
		return new JsQuery(getComponent()).$().chain("selectable", "'widget'");
	}

	/**
	 * Method to returns the .ui-selectable element within the ajax request
	 *
	 * @param ajaxRequestTarget
	 */
	public void widget(AjaxRequestTarget ajaxRequestTarget)
	{
		ajaxRequestTarget.appendJavaScript(this.widget().render().toString());
	}
}