text:
package de.theit.jenkins.crowd;

import com.atlassian.crowd.exception.ApplicationAccessDeniedException;
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.InvalidTokenException;
import com.atlassian.crowd.exception.OperationFailedException;
import com.atlassian.crowd.exception.UserNotFoundException;
import com.atlassian.crowd.integration.http.CrowdHttpAuthenticator;
import com.atlassian.crowd.integration.http.CrowdHttpAuthenticatorImpl;
import com.atlassian.crowd.integration.http.util.CrowdHttpTokenHelper;
import com.atlassian.crowd.integration.http.util.CrowdHttpTokenHelperImpl;
import com.atlassian.crowd.integration.http.util.CrowdHttpValidationFactorExtractorImpl;
import com.atlassian.crowd.integration.rest.service.factory.RestCrowdClientFactory;
import com.atlassian.crowd.model.authentication.ValidationFactor;
import com.atlassian.crowd.model.group.Group;
import com.atlassian.crowd.model.user.User;
import com.atlassian.crowd.service.client.ClientProperties;
import com.atlassian.crowd.service.client.ClientPropertiesImpl;
import com.atlassian.crowd.service.client.CrowdClient;

import hudson.util.Secret;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.SystemUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import static de.theit.jenkins.crowd.ErrorMessages.applicationPermission;
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.userNotFound;

/**
 * This class contains all objects that are necessary to access the REST
 * services on the remote Crowd server. Additionally it contains some helper
 * methods to check for group membership and availability.
 *
 * @author Thorsten Heit (theit@gmx.de)
 * @version $Id$
 * @since 08.09.2011
 */
public class CrowdConfigurationService {

    /**
     * Classloader problem with Java 11 and jaxb
     *
     */
    // TODO remove it if a better solutions is found without classloader hack
    // @Issue("JENKINS-59301")
    private static final boolean IS_MIN_JAVA_11 = SystemUtils.JAVA_VERSION_FLOAT >= 11.0f;

    /**
     * Used for logging purposes.
     */
    private static final Logger LOG = Logger.getLogger(CrowdConfigurationService.class.getName());

    /**
     * The maximum number of groups that can be fetched from the Crowd server
     * for a user in one request.
     */
    private static final int MAX_GROUPS = 500;

    /**
     * Holds the Crowd client properties.
     */
    private final ClientProperties clientProperties;

    /**
     * The Crowd client to access the REST services on the remote Crowd server.
     */
    private final CrowdClient crowdClient;

    /**
     * The helper class for Crowd SSO token operations.
     */
    private final CrowdHttpTokenHelper tokenHelper;

    /**
     * The interface used to manage HTTP authentication and web/SSO
     * authentication integration.
     */
    private final CrowdHttpAuthenticator crowdHttpAuthenticator;

    /**
     * The names of all user groups that are allowed to login.
     */
    private final ArrayList<String> allowedGroupNames;

    /**
     * Specifies whether nested groups may be used.
     */
    private final boolean nestedGroups;

    private final boolean useSSO;

    private final boolean useCache;

    private final Integer cacheSize;

    private final Integer cacheTTL;

    private CacheMap<String, Boolean> isGroupMemberCache = null;

    private CacheMap<String, User> userFromSSOTokenCache = null;

    private CacheMap<String, User> userCache = null;

    private CacheMap<String, Group> groupCache = null;

    private CacheMap<String, Collection<GrantedAuthority>> authoritiesForUserCache = null;

    /**
     * Creates a new Crowd configuration object.
     *
     * @param url                       The Crowd URL
     * @param applicationName           The Crowd application name
     * @param password                  The Crowd application password
     * @param sessionValidationInterval The session validation interval
     * @param useSSO                    Specifies if SSO should be enabled
     * @param cookieDomain              The cookie domain
     * @param cookieTokenkey            The cookie token key
     * @param useProxy                  the 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 useCache                  The use cache
     * @param cacheSize                 the cache size
     * @param cacheTTL                  The cache TTL
     * @param pGroupNames               The group names to use when authenticating
     *                                  Crowd users. May
     *                                  not be null.
     * @param pNestedGroups             Specifies whether nested groups should be
     *                                  used when validating
     *                                  users against a group name.
     */
    public CrowdConfigurationService(String url, String applicationName, Secret password,
            int sessionValidationInterval, boolean useSSO,
            String cookieDomain, String cookieTokenkey, Boolean useProxy,
            String httpProxyHost, String httpProxyPort, String httpProxyUsername,
            Secret httpProxyPassword, String socketTimeout,
            String httpTimeout, String httpMaxConnections,
            boolean useCache, Integer cacheSize, Integer cacheTTL,
            String pGroupNames, boolean pNestedGroups) {

        LOG.log(Level.INFO, "Groups given for Crowd configuration service: {0}", pGroupNames);

        this.allowedGroupNames = new ArrayList<>();
        for (String group : pGroupNames.split(",")) {
            group = group.trim();
            if (group.length() > 0) {
                LOG.log(Level.FINE, "-> adding allowed group name: {0}", group);
                this.allowedGroupNames.add(group);
            }
        }
        this.nestedGroups = pNestedGroups;
        this.useSSO = useSSO;
        this.useCache = useCache;
        this.cacheSize = cacheSize;
        this.cacheTTL = cacheTTL;
        Properties props = getProperties(url, applicationName, Secret.toString(password), sessionValidationInterval,
                useSSO, cookieDomain, cookieTokenkey, useProxy, httpProxyHost, httpProxyPort, httpProxyUsername,
                Secret.toString(httpProxyPassword), socketTimeout, httpTimeout, httpMaxConnections);
        this.clientProperties = ClientPropertiesImpl.newInstanceFromProperties(props);
        this.crowdClient = new RestCrowdClientFactory().newInstance(this.clientProperties);
        this.tokenHelper = CrowdHttpTokenHelperImpl.getInstance(CrowdHttpValidationFactorExtractorImpl.getInstance());
        this.crowdHttpAuthenticator = new CrowdHttpAuthenticatorImpl(
                this.crowdClient,
                this.clientProperties,
                this.tokenHelper);
    }

    public List<String> getAllowedGroupNames() {
        return allowedGroupNames;
    }

    public boolean isUseSSO() {
        return useSSO;
    }

    /**
     * Checks whether the user is a member of one of the Crowd groups whose
     * members are allowed to login.
     *
     * @param username The name of the user to check. May not be null
     *                 or empty.
     * @return true if and only if the group exists, is active and
     *         the user is either a direct group member or, if nested groups may
     *         be used, a nested group member. false else.
     */
    public boolean isGroupMember(String username) {
        if (username == null) {
            return false; // prevent NPE
        }
        if (allowedGroupNames.isEmpty()) {
            return true;
        }

        // Load the entry from cache if it's valid return it
        Boolean retval = getValidValueFromCache(username, isGroupMemberCache);
        if (retval != null) {
            return retval;
        }

        // no entry was found try to get one
        try {
            for (String group : this.allowedGroupNames) {
                retval = isGroupMember(username, group);
                if (retval) {
                    break;
                }
            }
        } catch (ApplicationPermissionException ex) {
            LOG.log(Level.WARNING, applicationPermission());
            retval = null;
        } catch (InvalidAuthenticationException ex) {
            LOG.log(Level.WARNING, invalidAuthentication());
            retval = null;
        } catch (OperationFailedException ex) {
            LOG.log(Level.SEVERE, operationFailed(), ex);
            retval = null;
        }

        // If correct object was returned save it to cache
        // checking if key is present is redundant
        setValueToCache(username, retval, isGroupMemberCache);

        return Boolean.TRUE.equals(retval);
    }

    /**
     * Checks if the specified group name exists on the remote Crowd server and
     * is active.
     *
     * @param groupName The name of the group to check. May not be null
     *                  or empty.
     * @return true if and only if the group name is not empty,
     *         does exist on the remote Crowd server and is active.
     *         false else.
     * @throws InvalidAuthenticationException If the application and password are
     *                                        not valid.
     * @throws ApplicationPermissionException If the application is not permitted to
     *                                        perform the requested operation on the
     *                                        server
     * @throws OperationFailedException       If the operation has failed for any
     *                                        other reason, including
     *                                        invalid arguments and the operation
     *                                        not being supported on
     *                                        the server.
     */
    public boolean isGroupActive(String groupName)
            throws InvalidAuthenticationException,
            ApplicationPermissionException, OperationFailedException {
        boolean retval = false;

        try {
            LOG.log(Level.FINE, "Checking whether group is active: {0}", groupName);
            Group group = getGroup(groupName);
            if (null != group) {
                retval = group.isActive();
            }
        } catch (GroupNotFoundException ex) {
            LOG.log(Level.FINE, groupNotFound(groupName));
        }

        return retval;
    }

    /**
     * Retrieves the list of all (nested) groups from the Crowd server that the
     * user is a member of.
     *
     * @param username The name of the user. May not be null.
     * @return The list of all groups that the user is a member of. Always
     *         non-null.
     */
    public Collection<GrantedAuthority> getAuthoritiesForUser(String username) {
        if (username == null) {
            return null; // prevent NPE
        }

        // Load the entry from cache if it's valid return it
        Collection<GrantedAuthority> authorities = getValidValueFromCache(username, authoritiesForUserCache);
        if (authorities != null) {
            return authorities;
        }

        // no cache entry was found try to get one
        authorities = new TreeSet<>(
                new Comparator<GrantedAuthority>() {
                    @Override
                    public int compare(GrantedAuthority ga1,
                            GrantedAuthority ga2) {
                        return ga1.getAuthority().compareTo(ga2.getAuthority());
                    }
                });
        HashSet<String> groupNames = new HashSet<>();

        // retrieve the names of all groups the user is a directly or indirectly member
        // of if this configuration setting is active/enabled
        try {
            int index = 0;
            String membership = this.nestedGroups ? "nested" : "direct";
            LOG.log(Level.FINE, "Retrieve list of groups with {0} membership for user '{1}'...",
                    new Object[] { membership, username });

            while (true) {
                LOG.log(Level.FINEST, "Fetching groups [{0}...{1}]...",
                        new Object[] { index, (index + MAX_GROUPS - 1) });

                List<Group> groups;
                if (this.nestedGroups) {
                    groups = getGroupsForNestedUser(username, index, MAX_GROUPS);
                } else {
                    groups = getGroupsForUser(username, index, MAX_GROUPS);
                }

                if (null == groups || groups.isEmpty()) {
                    break;
                }
                for (Group group : groups) {
                    if (group.isActive()) {
                        groupNames.add(group.getName());
                    }
                }
                index += MAX_GROUPS;
            }
        } catch (UserNotFoundException ex) {
            LOG.log(Level.INFO, userNotFound(username));
        } catch (InvalidAuthenticationException ex) {
            LOG.log(Level.WARNING, invalidAuthentication());
        } catch (ApplicationPermissionException ex) {
            LOG.log(Level.WARNING, applicationPermission());
        } catch (OperationFailedException ex) {
            LOG.log(Level.SEVERE, operationFailed(), ex);
        }

        // now create the list of authorities
        for (String str : groupNames) {
            authorities.add(new SimpleGrantedAuthority(str));
        }

        // If correct object was returned save it to cache
        // checking if key is present is redundant
        setValueToCache(username, authorities, authoritiesForUserCache);

        return authorities;
    }

    public User authenticateUser(String login, String password) throws UserNotFoundException, InactiveAccountException,
            ExpiredCredentialException, ApplicationPermissionException, InvalidAuthenticationException,
            OperationFailedException {
        LOG.log(Level.FINEST, "CrowdClient.authenticateUser()");
        ClassLoader orgContextClassLoader = null;
        Thread currentThread = null;
        if (IS_MIN_JAVA_11) {
            currentThread = Thread.currentThread();
            orgContextClassLoader = currentThread.getContextClassLoader();
            currentThread.setContextClassLoader(CrowdConfigurationService.class.getClassLoader());
        }
        try {
            return crowdClient.authenticateUser(login, password);
        } finally {
            if (currentThread != null) {
                currentThread.setContextClassLoader(orgContextClassLoader);
            }
        }
    }

    public User getUser(String username) throws UserNotFoundException, OperationFailedException,
            ApplicationPermissionException, InvalidAuthenticationException {
        // Load the entry from cache if it's valid return it
        User retval = getValidValueFromCache(username, userCache);
        if (retval != null) {
            return retval;
        }

        LOG.log(Level.FINEST, "CrowdClient.getUser()");

        ClassLoader orgContextClassLoader = null;
        Thread currentThread = null;
        if (IS_MIN_JAVA_11) {
            currentThread = Thread.currentThread();
            orgContextClassLoader = currentThread.getContextClassLoader();
            currentThread.setContextClassLoader(CrowdConfigurationService.class.getClassLoader());
        }
        try {
            retval = crowdClient.getUser(username);
        } finally {
            if (currentThread != null) {
                currentThread.setContextClassLoader(orgContextClassLoader);
            }
        }

        // If correct object was returned save it to cache
        // checking if key is present is redundant
        setValueToCache(username, retval, userCache);

        return retval;
    }

    public Group getGroup(String name) throws GroupNotFoundException, OperationFailedException,
            InvalidAuthenticationException, ApplicationPermissionException {
        // Load the entry from cache if it's valid return it
        Group retval = getValidValueFromCache(name, groupCache);
        if (retval != null) {
            return retval;
        }

        LOG.log(Level.FINEST, "CrowdClient.getGroup()");

        ClassLoader orgContextClassLoader = null;
        Thread currentThread = null;
        if (IS_MIN_JAVA_11) {
            currentThread = Thread.currentThread();
            orgContextClassLoader = currentThread.getContextClassLoader();
            currentThread.setContextClassLoader(CrowdConfigurationService.class.getClassLoader());
        }
        try {
            retval = crowdClient.getGroup(name);
        } finally {
            if (currentThread != null) {
                currentThread.setContextClassLoader(orgContextClassLoader);
            }
        }

        // If correct object was returned save it to cache
        // checking if key is present is redundant
        setValueToCache(name, retval, groupCache);

        return retval;
    }

    public List<Group> getGroupsForNestedUser(String username, int start, int size)
            throws OperationFailedException, InvalidAuthenticationException, ApplicationPermissionException,
            UserNotFoundException {
        LOG.log(Level.FINEST, "CrowdClient.getGroupsForNestedUser()");
        ClassLoader orgContextClassLoader = null;
        Thread currentThread = null;
        if (IS_MIN_JAVA_11) {
            currentThread = Thread.currentThread();
            orgContextClassLoader = currentThread.getContextClassLoader();
            currentThread.setContextClassLoader(CrowdConfigurationService.class.getClassLoader());
        }
        try {
            return crowdClient.getGroupsForNestedUser(username, start, size);
        } finally {
            if (currentThread != null) {
                currentThread.setContextClassLoader(orgContextClassLoader);
            }
        }
    }

    public List<Group> getGroupsForUser(String username, int start, int size) throws OperationFailedException,
            InvalidAuthenticationException, ApplicationPermissionException, UserNotFoundException {
        LOG.log(Level.FINEST, "CrowdClient.getGroupsForUser()");
        ClassLoader orgContextClassLoader = null;
        Thread currentThread = null;
        if (IS_MIN_JAVA_11) {
            currentThread = Thread.currentThread();
            orgContextClassLoader = currentThread.getContextClassLoader();
            currentThread.setContextClassLoader(CrowdConfigurationService.class.getClassLoader());
        }
        try {
            return crowdClient.getGroupsForUser(username, start, size);
        } finally {
            if (currentThread != null) {
                currentThread.setContextClassLoader(orgContextClassLoader);
            }
        }
    }

    public boolean isUserDirectGroupMember(String username, String groupname)
            throws OperationFailedException, ApplicationPermissionException, InvalidAuthenticationException {
        LOG.log(Level.FINEST, "CrowdClient.isUserDirectGroupMember()");

        ClassLoader orgContextClassLoader = null;
        Thread currentThread = null;
        if (IS_MIN_JAVA_11) {
            currentThread = Thread.currentThread();
            orgContextClassLoader = currentThread.getContextClassLoader();
            currentThread.setContextClassLoader(CrowdConfigurationService.class.getClassLoader());
        }
        try {
            return crowdClient.isUserDirectGroupMember(username, groupname);
        } finally {
            if (currentThread != null) {
                currentThread.setContextClassLoader(orgContextClassLoader);
            }
        }
    }

    public boolean isUserNestedGroupMember(String username, String groupname)
            throws OperationFailedException, ApplicationPermissionException, InvalidAuthenticationException {
        LOG.log(Level.FINEST, "CrowdClient.isUserNestedGroupMember()");

        ClassLoader orgContextClassLoader = null;
        Thread currentThread = null;
        if (IS_MIN_JAVA_11) {
            currentThread = Thread.currentThread();
            orgContextClassLoader = currentThread.getContextClassLoader();
            currentThread.setContextClassLoader(CrowdConfigurationService.class.getClassLoader());
        }
        try {
            return crowdClient.isUserNestedGroupMember(username, groupname);
        } finally {
            if (currentThread != null) {
                currentThread.setContextClassLoader(orgContextClassLoader);
            }
        }
    }

    public void validateSSOAuthentication(String token, List<ValidationFactor> list)
            throws OperationFailedException, InvalidAuthenticationException, ApplicationPermissionException,
            InvalidTokenException {
        LOG.log(Level.FINEST, "CrowdClient.validateSSOAuthentication()");

        ClassLoader orgContextClassLoader = null;
        Thread currentThread = null;
        if (IS_MIN_JAVA_11) {
            currentThread = Thread.currentThread();
            orgContextClassLoader = currentThread.getContextClassLoader();
            currentThread.setContextClassLoader(CrowdConfigurationService.class.getClassLoader());
        }
        try {
            crowdClient.validateSSOAuthentication(token, list);
        } finally {
            if (currentThread != null) {
                currentThread.setContextClassLoader(orgContextClassLoader);
            }
        }
    }

    public User findUserFromSSOToken(String token) throws OperationFailedException, InvalidAuthenticationException,
            ApplicationPermissionException, InvalidTokenException {
        // Load the entry from cache if it's valid return it
        User retval = getValidValueFromCache(token, userFromSSOTokenCache);
        if (retval != null) {
            return retval;
        }

        LOG.log(Level.FINEST, "CrowdClient.findUserFromSSOToken()");

        ClassLoader orgContextClassLoader = null;
        Thread currentThread = null;
        if (IS_MIN_JAVA_11) {
            currentThread = Thread.currentThread();
            orgContextClassLoader = currentThread.getContextClassLoader();
            currentThread.setContextClassLoader(CrowdConfigurationService.class.getClassLoader());
        }
        try {
            retval = crowdClient.findUserFromSSOToken(token);
        } finally {
            if (currentThread != null) {
                currentThread.setContextClassLoader(orgContextClassLoader);
            }
        }

        // If correct object was returned save it to cache
        // checking if key is present is redundant
        setValueToCache(token, retval, userFromSSOTokenCache);

        return retval;
    }

    public void shutdown() {
        LOG.log(Level.FINEST, "CrowdClient.shutdown()");

        ClassLoader orgContextClassLoader = null;
        Thread currentThread = null;
        if (IS_MIN_JAVA_11) {
            currentThread = Thread.currentThread();
            orgContextClassLoader = currentThread.getContextClassLoader();
            currentThread.setContextClassLoader(CrowdConfigurationService.class.getClassLoader());
        }
        try {
            crowdClient.shutdown();
        } finally {
            if (currentThread != null) {
                currentThread.setContextClassLoader(orgContextClassLoader);
            }
        }
    }

    public void testConnection()
            throws OperationFailedException, InvalidAuthenticationException, ApplicationPermissionException {
        ClassLoader orgContextClassLoader = null;
        Thread currentThread = null;
        if (IS_MIN_JAVA_11) {
            currentThread = Thread.currentThread();
            orgContextClassLoader = currentThread.getContextClassLoader();
            currentThread.setContextClassLoader(CrowdConfigurationService.class.getClassLoader());
        }
        LOG.log(Level.FINEST, "CrowdClient.testConnection()");

        try {
            crowdClient.testConnection();
        } finally {
            if (currentThread != null) {
                currentThread.setContextClassLoader(orgContextClassLoader);
            }
        }
    }

    public String getCrowdToken(HttpServletRequest httpServletRequest) {
        LOG.log(Level.FINEST, "TokenHelper.getCrowdToken()");
        return tokenHelper.getCrowdToken(httpServletRequest, clientProperties.getCookieTokenKey());
    }

    public List<ValidationFactor> getValidationFactors(HttpServletRequest request) {
        LOG.log(Level.FINEST, "TokenHelper.getValidationFactorExtractor().getValidationFactors()");
        return tokenHelper.getValidationFactorExtractor().getValidationFactors(request);
    }

    public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws ApplicationPermissionException, InvalidAuthenticationException, OperationFailedException {
        LOG.log(Level.FINEST, "CrowdHttpAuthenticator.logout()");

        ClassLoader orgContextClassLoader = null;
        Thread currentThread = null;
        if (IS_MIN_JAVA_11) {
            currentThread = Thread.currentThread();
            orgContextClassLoader = currentThread.getContextClassLoader();
            currentThread.setContextClassLoader(CrowdConfigurationService.class.getClassLoader());
        }
        try {
            crowdHttpAuthenticator.logout(httpServletRequest, httpServletResponse);
        } finally {
            if (currentThread != null) {
                currentThread.setContextClassLoader(orgContextClassLoader);
            }
        }
    }

    public User authenticate(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
            String name,
            String credentials)
            throws ApplicationPermissionException, InvalidAuthenticationException, OperationFailedException,
            ApplicationAccessDeniedException, ExpiredCredentialException, InactiveAccountException,
            InvalidTokenException {
        LOG.log(Level.FINEST, "CrowdHttpAuthenticator.authenticate()");
        ClassLoader orgContextClassLoader = null;
        Thread currentThread = null;
        if (IS_MIN_JAVA_11) {
            currentThread = Thread.currentThread();
            orgContextClassLoader = currentThread.getContextClassLoader();
            currentThread.setContextClassLoader(CrowdConfigurationService.class.getClassLoader());
        }
        try {
            return crowdHttpAuthenticator.authenticate(httpServletRequest, httpServletResponse, name, credentials);
        } finally {
            if (currentThread != null) {
                currentThread.setContextClassLoader(orgContextClassLoader);
            }
        }
    }

    public boolean isAuthenticated(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws OperationFailedException {
        LOG.log(Level.FINEST, "CrowdHttpAuthenticator.isAuthenticated()");
        ClassLoader orgContextClassLoader = null;
        Thread currentThread = null;
        if (IS_MIN_JAVA_11) {
            currentThread = Thread.currentThread();
            orgContextClassLoader = currentThread.getContextClassLoader();
            currentThread.setContextClassLoader(CrowdConfigurationService.class.getClassLoader());
        }
        try {
            return crowdHttpAuthenticator.checkAuthenticated(httpServletRequest, httpServletResponse).isAuthenticated();
        } finally {
            if (currentThread != null) {
                currentThread.setContextClassLoader(orgContextClassLoader);
            }
        }
    }

    /**
     * Checks whether the user is a member of the given Crowd group.
     *
     * @param username The name of the user to check. May not be null
     *                 or
     *                 empty.
     * @param group    The name of the group to check the user against. May not be
     *                 null.
     * @return true if and only if the group exists, is active and
     *         the user is either a direct group member or, if nested groups may
     *         be used, a nested group member. false else.
     * @throws ApplicationPermissionException If the application is not permitted to
     *                                        perform the requested
     *                                        operation on the server.
     * @throws InvalidAuthenticationException If the application and password are
     *                                        not valid.
     * @throws OperationFailedException       If the operation has failed for any
     *                                        other reason, including
     *                                        invalid arguments and the operation
     *                                        not being supported on
     *                                        the server.
     */
    private boolean isGroupMember(String username, String group)
            throws ApplicationPermissionException,
            InvalidAuthenticationException, OperationFailedException {
        boolean retval = false;
        if (isGroupActive(group)) {
            LOG.log(Level.FINE, "Checking group membership for user '" + username + "' and group '" + group + "'...");

            if (this.nestedGroups) {
                if (isUserNestedGroupMember(username, group)) {
                    retval = true;
                    LOG.log(Level.FINER, "=> user is a nested group member");
                }
            } else {
                if (isUserDirectGroupMember(username, group)) {
                    retval = true;
                    LOG.log(Level.FINER, "=> user is a direct group member");
                }
            }
        }
        return retval;
    }

    private Properties getProperties(String url, String applicationName, String password,
            int sessionValidationInterval, boolean useSSO,
            String cookieDomain, String cookieTokenkey, Boolean useProxy,
            String httpProxyHost, String httpProxyPort, String httpProxyUsername,
            String httpProxyPassword, String socketTimeout,
            String httpTimeout, String httpMaxConnections) {
        // for
        // https://docs.atlassian.com/crowd/2.7.1/com/atlassian/crowd/service/client/ClientPropertiesImpl.html
        Properties props = new Properties();

        String crowdUrl = url;
        if (!crowdUrl.endsWith("/")) {
            crowdUrl += "/";
        }
        props.setProperty("application.name", applicationName);
        props.setProperty("application.password", password);
        props.setProperty("crowd.base.url", crowdUrl);
        props.setProperty("application.login.url", crowdUrl + "console/");
        props.setProperty("crowd.server.url", crowdUrl + "services/");
        props.setProperty("session.validationinterval", String.valueOf(sessionValidationInterval));
        // TODO move other values to jenkins web configuration
        props.setProperty("session.isauthenticated", "session.isauthenticated");
        props.setProperty("session.tokenkey", "session.tokenkey");
        props.setProperty("session.lastvalidation", "session.lastvalidation");

        if (useSSO) {
            if (cookieDomain != null && !cookieDomain.equals(""))
                props.setProperty("cookie.domain", cookieDomain);
            if (cookieTokenkey != null && !cookieTokenkey.equals(""))
                props.setProperty("cookie.tokenkey", cookieTokenkey);
        }

        if (useProxy != null && useProxy) {
            if (httpProxyHost != null && !httpProxyHost.equals(""))
                props.setProperty("http.proxy.host", httpProxyHost);
            if (httpProxyPort != null && !httpProxyPort.equals(""))
                props.setProperty("http.proxy.port", httpProxyPort);
            if (httpProxyUsername != null && !httpProxyUsername.equals(""))
                props.setProperty("http.proxy.username", httpProxyUsername);
            if (httpProxyPassword != null && !httpProxyPassword.equals(""))
                props.setProperty("http.proxy.password", httpProxyPassword);
        }

        if (socketTimeout != null && !socketTimeout.equals(""))
            props.setProperty("socket.timeout", socketTimeout);
        if (httpMaxConnections != null && !httpMaxConnections.equals(""))
            props.setProperty("http.max.connections", httpMaxConnections);
        if (httpTimeout != null && !httpTimeout.equals(""))
            props.setProperty("http.timeout", httpTimeout);

        return props;
    }

    private static class CacheEntry<T> {
        private final long expires;
        private final T value;

        CacheEntry(int ttlSeconds, T value) {
            this.expires = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(ttlSeconds);
            this.value = value;
        }

        public T getValue() {
            return value;
        }

        public boolean isValid() {
            return System.currentTimeMillis() < expires;
        }
    }

    /**
     * While we could use Guava's CacheBuilder the method signature changes make
     * using it problematic. Safer to roll our own and ensure compatibility across
     * as wide a range of Jenkins versions as possible.
     *
     * @param <K> Key type
     * @param <V> Cache entry type
     */
    private static class CacheMap<K, V> extends LinkedHashMap<K, CacheEntry<V>> {

        private static final long serialVersionUID = 1L;
        private final int cacheSize;

        CacheMap(int cacheSize) {
            super(cacheSize + 1); // prevent realloc when hitting cache size limit
            this.cacheSize = cacheSize;
        }

        @Override
        protected boolean removeEldestEntry(Map.Entry<K, CacheEntry<V>> eldest) {
            return size() > cacheSize || eldest.getValue() == null || !eldest.getValue().isValid();
        }
    }

    private <T> T getValidValueFromCache(String key, CacheMap<String, T> cacheObj) {
        if (!useCache || cacheObj == null) {
            return null;
        }

        final CacheEntry<T> cached;
        synchronized (this) {
            cached = cacheObj.get(key);
        }

        if (cached != null && cached.isValid()) {
            return cached.getValue();
        } else {
            return null;
        }
    }

    private <T> void setValueToCache(String key, T value, CacheMap<String, T> cacheObj) {
        // Let's save the entry in the cache if necessary
        if (!useCache || value == null) {
            return;
        }

        synchronized (this) {
            if (cacheObj == null) {
                cacheObj = new CacheMap<>(cacheSize);
            }
            cacheObj.put(key, new CacheEntry<>(cacheTTL, value));
        }
    }
}


text:
package com.rhcloud.gmn.tm.timer;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author GMNProjects
 */
public class BackGroundTimer implements Runnable {

    private static volatile Timer currentTimer;
    private Updater updater;

    public BackGroundTimer(Updater updater) {
        this.updater = updater;
        currentTimer = new Timer();
    }

    @Override
    public void run() {
        currentTimer.schedule(new TTask(), 0, 1000);
    }

    class TTask extends TimerTask {

        @Override
        public void run() {
            updater.update();
        }
    }

    public Calendar cancel() {
        currentTimer.cancel();
        return Calendar.getInstance();
    }

}

redpajama_set_name: RedPajamaGithub


text:
/**
 * Lei Pipe
 *
 * @author Zongmin Lei <leizongmin@gmail.com>
 */

var uuid = require('uuid');
var autoFill = require('./fill');
var sortPipes = require('./sort');
var debug = require('debug')('lei:pipe');

module.exports = Pipe;

function Pipe () {
  if (!(this instanceof Pipe)) return new Pipe();
  debug('new');
  this._pipes = [];
  this._inited = false;
}

/**
 * Init
 */
Pipe.prototype.init = function () {
  debug('init');
  this._pipes = sortPipes(autoFill(this._pipes));
  this._inited = true;
};

/**
 * Add
 *
 * @param {String} name
 * @param {Object} options
 *   - {Array} before
 *   - {Array} after
 * @param {Function} handler
 */
Pipe.prototype.add = function () {
  var args = parseAddArgs(arguments);
  debug('add %s', args.name);
  this._pipes.push(args);
};

/**
 * Start
 *
 * @param {Object} data
 * @param {Function} callback
 * @param {Object} data2
 */
Pipe.prototype.start = function (data, callback, data2) {
  debug('start %s', data);
  if (!this._inited) {
    try {
      this.init();
    } catch (err) {
      return callback(err);
    }
  }
  startPipe(this._pipes.slice(0), data, callback, data2);
};

function parseAddArgs (args) {
  var name, options, handler;

  if (args.length >= 3) {
    name = args[0];
    options = args[1];
    handler = args[2];
  } else if (args.length === 1) {
    name = uuid.v4();
    options = {};
    handler = args[0];
  } else if (args.length === 2) {
    if (typeof args[0] === 'string') {
      name = args[0];
      options = {};
    } else {
      name = uuid.v4();
      options = args[0];
    }
    handler = args[1];
  } else {
    throw new TypeError('Wrong arguments number');
  }

  options.name = name;
  options.handler = handler;
  options.before = options.before || [];
  options.after = options.after || [];

  return options;
}

function startPipe (pipes, data, callback, data2) {
  var i = 0;
  var len = pipes.length;
  next(null, data);

  function next (err, d) {
    debug('startPipe next [%s/%s] (%s, %s)', i, len, err, d);
    if (arguments.length >= 2) data = d;
    if (err) return end(err, data);
    if (i < len) {
      var item = pipes[i++];
      try {
        item.handler(data, next, end, data2);
      } catch (err) {
        return end(err, data);
      }
    } else {
      end(err, data);
    }
  }

  function end (err, d) {
    debug('startPipe end (%s, %s)', err, d);
    err = err || null;
    if (arguments.length >= 2) data = d;
    callback(err, data, data2);
  }
}


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">

    <parent>
        <artifactId>fuchsia-bases</artifactId>
        <groupId>org.ow2.chameleon.fuchsia.base</groupId>
        <version>0.0.5-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <modelVersion>4.0.0</modelVersion>

    <artifactId>push</artifactId>
    <packaging>pom</packaging>
    <name>OW2 Chameleon - Fuchsia Base PuSH Implementation</name>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.jabsorb</groupId>
                <artifactId>jabsorb</artifactId>
                <version>1.3.1</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>2.5</version>
            </dependency>
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient-osgi</artifactId>
                <version>4.1.1</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <modules>
        <module>hub</module>
        <module>publisher</module>
    </modules>
</project>


text:
const http = require("http");
const { pipeline } = require("stream");
const debug = require("debug")("proxy-supervisor:proxy:http");

module.exports = (url, options, clientReq, clientRes, callback) => {
  let finished = false;
  const targetReq = http.request({ ...options, path: url.href });

  targetReq.once("timeout", () => {
    debug("timeout triggered");
    targetReq.destroy(new Error("TIMEOUT"));
  });

  targetReq.once("response", targetRes => {
    debug("response triggered with %d status code", targetRes.statusCode);

    clientRes.writeHead(
      targetRes.statusCode,
      targetRes.statusMessage,
      targetRes.headers
    );

    return pipeline(targetRes, clientRes, () => {
      debug("response pipeline finished");

      if (finished) return;
      return callback(null, targetRes);
    });
  });

  targetReq.once("error", err => {
    debug("error triggered %s", err.message);

    finished = true;
    const writableEnded =
      clientRes.writableEnded === undefined
        ? clientRes.finished
        : clientRes.writableEnded;

    if (!writableEnded) {
      clientRes.writeHead(502);
      clientRes.end();
    }

    return callback(err);
  });

  pipeline(clientReq, targetReq, () => {
    debug("client payload sent to target");
  });
};


text:
import { FunctionComponent } from 'react';
import { Row } from 'react-bootstrap';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { reduxForm, formValueSelector } from 'redux-form';
import { createSelector } from 'reselect';

import { AccountingPeriodFilter } from '@waldur/customer/list/AccountingPeriodFilter';
import { PeriodOption } from '@waldur/form/types';
import { makeLastTwelveMonthsFilterPeriods } from '@waldur/form/utils';
import { OfferingAutocomplete } from '@waldur/marketplace/offerings/details/OfferingAutocomplete';
import { OrganizationAutocomplete } from '@waldur/marketplace/orders/OrganizationAutocomplete';
import { ProjectFilter } from '@waldur/marketplace/resources/list/ProjectFilter';
import { RootState } from '@waldur/store/reducers';
import { Customer, ORGANIZATION_WORKSPACE } from '@waldur/workspace/types';

interface SupportUsageFilterProps {
  options: PeriodOption[];
  customer: Customer;
}

const PureSupportUsageFilter: FunctionComponent<SupportUsageFilterProps> = (
  props,
) => (
  <Row>
    <AccountingPeriodFilter options={props.options} />
    <OrganizationAutocomplete />
    <ProjectFilter
      customer_uuid={props.customer ? props.customer.uuid : null}
    />
    <OfferingAutocomplete offeringFilter={{ shared: true }} />
  </Row>
);

export const FORM_ID = 'SupportUsageFilter';

const selector = formValueSelector(FORM_ID);

const mapStateToProps = createSelector(
  (state: RootState) => selector(state, ORGANIZATION_WORKSPACE),
  (customer) => ({
    customer,
    options: makeLastTwelveMonthsFilterPeriods(),
  }),
);

const enhance = compose(
  reduxForm({
    form: FORM_ID,
    initialValues: {
      accounting_period: makeLastTwelveMonthsFilterPeriods()[0],
    },
  }),
  connect(mapStateToProps),
);

export const SupportUsageFilter = enhance(PureSupportUsageFilter);


text:
package restly.exceptions.clienterror;

import restly.HttpStatus;

/**
 * 403 Forbidden
 *
 *

 * The server understood the request, but is refusing to fulfill it.
 * Authorization will not help and the request SHOULD NOT be repeated.
 * If the request method was not HEAD and the server wishes to make
 * public why the request has not been fulfilled, it SHOULD describe the
 * reason for the refusal in the entity. If the server does not wish to
 * make this information available to the client, the status code 404
 * (Not Found) can be used instead.
 *

 *
 * @see https://tools.ietf.org/html/rfc2616#section-10.4.4
 * @author Erik Beeson
 */
public class ForbiddenException extends HttpClientErrorException {
	public static final HttpStatus HTTP_STATUS = HttpStatus.FORBIDDEN;

	public ForbiddenException() {
		this(null);
	}

	public ForbiddenException(Object data) {
		super(HTTP_STATUS, data);
	}
}


text:
package com.gtris.models;

import java.awt.Image;
import com.gtris.enums.ColorFigure;
import com.gtris.enums.ControlAlignment;

/**
 * Class represent a block in the screen
 * @author Pablo
 *
 */
public class Figure extends BlockBase implements Comparable<Figure>{

	private Integer id;
	private ControlAlignment origin;

	public Figure(){

	}

	public Figure(Integer id, Image image, int height, int width, int x, int y,
			boolean ground, ColorFigure color, ControlAlignment origin) {
		super();
		this.id = id;
		super.image = image;
		this.height = height;
		this.width = width;
		this.x = x;
		this.y = y;
		this.ground = ground;
		this.color = color;
		this.origin = origin;
	}

	public Figure(Integer id, int height, int width, int x, int y) {
		super();
		this.id = id;
		this.height = height;
		this.width = width;
		this.x = x;
		this.y = y;
	}

	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}

	public void setOrigin(ControlAlignment origin) {
		this.origin = origin;
	}
	public ControlAlignment getOrigin() {
		return origin;
	}
	@Override
	public int compareTo(Figure arg0) {
		return this.getId().compareTo(arg0.getId());
	}
}


text:
package com.citelic.game.entity.npc.impl.soulwars;

import com.citelic.game.engine.Engine;
import com.citelic.game.entity.Entity;
import com.citelic.game.entity.npc.NPC;
import com.citelic.game.entity.player.content.controllers.impl.distractions.soulwars.GameTask;
import com.citelic.game.entity.player.content.controllers.impl.distractions.soulwars.SoulWarsManager.PlayerType;
import com.citelic.game.map.tile.Tile;

public class Barricade extends NPC {

	private static final long serialVersionUID = 4304917643056790264L;

	private int team;

	public Barricade(Tile tile, int team) {
		super(1532, tile, -1, true, true);
		team = this.team;
		setCantFollowUnderCombat(true);
	}

	@Override
	public void processNPC() {
		if (isDead())
			return;
		cancelFaceEntityNoCheck();
	}

	public void litFire() {
		transformIntoNPC(1533);
		sendDeath(this);
	}

	public void explode() {
		sendDeath(this);
	}

	@Override
	public void sendDeath(Entity killer) {
		resetWalkSteps();
		getCombat().removeTarget();
		if (this.getId() != 1533) {
			setNextAnimation(null);
			reset();
			setLocation(getRespawnTile());
			finish();
		} else {
			super.sendDeath(killer);
		}
		((GameTask) Engine.soulWars.getTasks().get(PlayerType.IN_GAME))
				.removeBarricade(this, team);
	}
}


text:
layout: post
title: Getting started with matplotlib
date: 2013-11-06 23:47:35.000000000 -06:00
---
Bear with me; this is my first blog post.

I want to write about something that I care about.  I care about software and I care about science.  More importantly, I care about how these two interact and how software can help the scientific community.  Presentation of science to the public in an understandable fashion is difficult.  It's always hard to gauge at what level a scientist should pitch their presentation, and that's where pictures come in handy.

Most people abosrb information best visually.  Auditory and kinematic learners also exist, but most people are visual learners.  To that end, I decided to write about [matplotlib](http://matplotlib.org), a plotting library written in Python.  This should be fairly introductory.

## Installing

For some reason, installing python packages is notoriously hard if you're not exposed to the various different approaches already out there.  I'm not going to go through all of them.  Instead, I recommend you install matplotlib through your operating system's package manager.  If you're on Ubuntu, it's `aptitude`.  If you're on RHEL, it's `yum`.  If you're on OS X, you don't have a package manager by default and you should install one.  I recommend [macports](http://www.macports.org), but others speak volumes about [homebrew](http://mxcl.github.io/homebrew).

Personally, I like to install software from source by hand.  If you're scared of doing it you should give it a try.  It's super educational.  I will go through the installation from source procedure on a Mac in another blog post, since I don't want to bloat this one.  In what remains, I'll assume you have it installed.

To check you have installed matplotlib correctly, you can execute the following
in a terminal:

```
$ python -c "import matplotlib"
$ echo $?
0
```

The command `echo $?` just prints out the exit status of the previous command.  If you get a `0` then the previous command was successful.  If you get a `1`, or anything nonzero, then matplotlib is not installed correctly.

## Your first plot

Now that matplotlib is installed correctly, you can create your first plot.

From now on, I'll be using the IPython prompt, but you don't need that to along.  All the commands are the same and will work in the regular python prompt.

First, we boot up the `ipython` console:

```
$ ipython
Python 2.7.3 (default, Nov 29 2012, 11:01:29)
Type "copyright", "credits" or "license" for more information.

IPython 0.13.2 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]:
```

Now we import `pyplot`, a set of convenience methods that interface well with matplotlib's internals:

```
In [1]: import matplotlib.pyplot as plt
```

Next, we create a `Figure` object:

```
In [2]: fig = plt.figure()
```

The `Figure` is the object that holds the axes, which we create now:

```
In [3]: ax = fig.add_subplot(1, 1, 1)
```

The `Axes` [1] object is where most of the magic happens.  This is the object you will interface with the most to do all of your plotting.  Here is a simple plotting command that creates a line plot:

```
In [4]: ax.plot([1, 2, 3], [1, 4, 9])
Out[4]: [<matplotlib.lines.Line2D at 0x10860ad50>]
```

The `plot` function takes a list of `x`-coordinates and a list of
`y`-coordinates and returns a list of objects called `Line2D` objects.  A ``Line2D`` object is a matplotlib object that represents the lines in the figure that join the coordinates together.  We will explore `Line2D` objects, and other objects, in a different post.  For now, just take it for granted that `ax.plot` connects the passed coordinates with lines to create a line plot.  We can save the figure with the following:

```
In [5]: fig.savefig('plot.pdf')
```

This will save the figure in `pdf` format.  Open it and take a look.  It should look a little like this:

![](/content/images/2013/Nov/lineplot.png)

There are lots of file types that matplotlib supports.  The ones I use most commonly are ``pdf`` and ``png``.  In fact, the image above is an ``svg`` file.  It is common in the scientific community to produce scalable vector graphics, and matplotlib allows this.  It also supports ``ps`` and ``eps``.  For a full list of supported file types see [here](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig).

[1] It's actually an `AxesSubplot` object, not an ``Axes`` object.  An `AxesSubplot` is just an `Axes` object with some extra functions to allow manipulation of its position within a `Figure`.  The reason for this is that there may be more than one set of axes in a figure.

### Another example

You can stop here, or you can follow along with a more complicated line plot using `numpy`, a high performance python library for dealing with array objects.  Carrying on from within the same ipython session:

```
In [6]: ax.cla()
```

This clears the axes of the old plot ready to plot something new.

```
In [7]: import numpy as np
```

Here we import `numpy` so we can use it below:

```
In [8]: x = np.linspace(0, 5, num=1000, endpoint=True)
```

This creates an array, `x`, of 1000 equally spaced points between `0` and `1`, inclusive.

```
In [9]: y = x * x * np.sin(2.0 * np.pi * x)
```

This line takes advantage of some of `numpy`'s machinery.  The multiplication of `numpy` arrays is done component-wise.

```
In [10]: ax.plot(x, y)
Out[10]: [<matplotlib.lines.Line2D at 0x108a728d0>]
```

Again, we pass in the `x`- and `y`-coordinates to `plot`.  This draws lines between the passed coordinates.  Go ahead and save your creation.  It should look something like this:

![](/content/images/2013/Nov/sineplot.png)


text:
插入链接

	<form name="LinkForm" class="margin-bottom-0">

				地址

						<input ng-enter="ok()" ng-model="params.url" type="text" required="required" class="form-control input-lg" placeholder="输入url地址">

				</form>

	<button class="btn btn-success" type="button" ng-click="ok()">确定</button>
	<button class="btn btn-danger" type="button" ng-click="cancel()">退出</button>


text:
import React, { Component } from 'react';
import { Meteor } from 'meteor/meteor';
import { createContainer } from 'meteor/react-meteor-data';

class Header extends Component {

  constructor(props) {
    super(props);
    this.handleSubmitLogout = this.handleSubmitLogout.bind(this);
  }

  handleSubmitLogout(event) {
    event.preventDefault();
    Meteor.logout();
    window.location.href = '/r/login';
  }

  render() {
    return (

        {/* Logo */}

          {/* mini logo for sidebar mini 50x50 pixels */}

          {/* logo for regular state and mobile devices */}

        {/* Header Navbar */}

          {/* Sidebar toggle button*/}

            Toggle navigation

          {/* Navbar Right Menu */}

              {/* Tasks Menu */}

                {/* Menu Toggle Button */}

                  9

You have 9 tasks

                    {/* Inner menu: contains the tasks */}

{/* Task item */}

                          {/* Task title and progress text */}

                            Design some buttons
                            20%

                          {/* The progress bar */}

                            {/* Change the css width attribute to simulate progress */}

                              20% Complete

                      {/* end task item */}

                    View all tasks

              {/* User Account Menu */}

                {/* Menu Toggle Button */}

                  {/* The user image in the navbar*/}
                  {/* hidden-xs hides the username on small devices so only the image appears. */}
                  {this.props.user.username}

                  {/* Menu Body */}
                  {/* Menu Footer*/}

                      Profile

                      <button onClick={this.handleSubmitLogout} className="btn btn-default btn-flat">Sign out</button>

              {/* Control Sidebar Toggle Button */}

    );
  }
}

export default createContainer(() => {
  return {
    user: Meteor.user() || {}
  };
}, Header);


text:
<TITLE>
[Chapter 2] 2.6 Testing the Samba Daemons</title><META NAME="DC.title" CONTENT=""><META NAME="DC.creator" CONTENT=""><META NAME="DC.publisher" CONTENT="O'Reilly & Associates, Inc."><META NAME="DC.date" CONTENT="1999-11-05T21:29:12Z"><META NAME="DC.type" CONTENT="Text.Monograph"><META NAME="DC.format" CONTENT="text/html" SCHEME="MIME"><META NAME="DC.source" CONTENT="" SCHEME="ISBN"><META NAME="DC.language" CONTENT="en-US"><META NAME="generator" CONTENT="Jade 1.1/O'Reilly DocBook 3.0 to HTML 4.0">

Using Samba

Robert Eckstein, David Collier-Brown, Peter Kelly

1st Edition November 1999

1-56592-449-5, Order Number: 4495

416 pages, $34.95

 Buy the hardcopy

Table of Contents

Chapter 2

Installing Samba on a Unix System

2.6 Testing the Samba Daemons

It's hard to believe, but we're nearly done with the Samba server setup. All that's left to do is to make sure that everything is working as we think it should. A convenient way to do this is to use the  smbclient program to examine what the server is offering to the network. If everything is set up properly, you should be able to do the following:

# smbclient -U% -L localhost

Added interface ip=192.168.220.100 bcast=192.168.220.255 nmask=255.255.255.0
Domain=[SIMPLE] OS=[Unix] Server=[Samba 2.0.5a]

        Sharename      Type      Comment
        ---------      ----      -------
        test           Disk      For testing only, please
        IPC$           IPC       IPC Service (Samba 2.0.5a)

        Server               	    Comment
        ---------            	    -------
        HYDRA                	    Samba 2.0.5a

        Workgroup            	    Master
        ---------            	    -------
        SIMPLE               	    HYDRA

If there is a problem, don't panic! Try to start the daemons manually, and check the system output or the debug files at
/usr/local/samba/var/log.smb to see if you can determine what happened. If you think it may be a more serious problem, skip to Chapter 7,  Printing and Name Resolution, for help on troubleshooting the Samba daemons.

If it worked, congratulations! You now have successfully set up the Samba server with a disk share. It's a simple one, but we can use it to set up and test the Windows 95 and NT clients in the next chapter. Then we will start making it more interesting by adding services such as home directories, printers, and security, and seeing how to integrate the server into a larger Windows domain.

2.5 Starting the Samba Daemons

3. Configuring Windows Clients

O'Reilly Home  |

O'Reilly Bookstores  |

How to Order  |

O'Reilly Contacts

International  |

About O'Reilly  |

Affiliated Companies

© 1999, O'Reilly & Associates, Inc.


text:
package relationships

import (
	"errors"
	"github.com/bor3ham/reja/schema"
)

type Pointer struct {
	Provided bool                    `json:"-"`
	Data     *schema.InstancePointer `json:"data"`
}

func (p Pointer) Equal(op Pointer) bool {
	if p.Data == nil {
		return (op.Data == nil)
	} else if op.Data == nil {
		return false
	}
	return p.Data.Equal(*op.Data)
}

func pointerFromResult(val interface{}) Pointer {
	asResult, ok := val.(schema.Result)
	if !ok {
		panic("Bad result value")
	}
	if asResult.Data == nil {
		return Pointer{}
	}
	asPointer, ok := asResult.Data.(schema.InstancePointer)
	if !ok {
		panic("Bad pointer value in result value")
	}
	return Pointer{Data: &asPointer}
}

type PointerSet struct {
	Provided bool                     `json:"-"`
	Data     []schema.InstancePointer `json:"data"`
}

func (ps PointerSet) Counts() map[string]int {
	counts := map[string]int{}
	if ps.Data == nil {
		return counts
	}
	for _, pointer := range ps.Data {
		key := pointer.Type + ":"
		if pointer.ID == nil {
			key += "nil"
		} else {
			key += *pointer.ID
		}
		_, exists := counts[key]
		if exists {
			counts[key] += 1
		} else {
			counts[key] = 1
		}
	}
	return counts
}
func (ps PointerSet) Equal(ops PointerSet) bool {
	if ps.Data == nil {
		return (ops.Data == nil)
	} else if ops.Data == nil {
		return false
	}
	psCounts := ps.Counts()
	opsCounts := ops.Counts()
	for key, count := range psCounts {
		oCount, exists := opsCounts[key]
		if !exists || oCount != count {
			return false
		}
	}
	for key, count := range opsCounts {
		oCount, exists := psCounts[key]
		if !exists || oCount != count {
			return false
		}
	}
	return true
}

func pointerSetFromPage(val interface{}) PointerSet {
	asPage, ok := val.(schema.Page)
	if !ok {
		panic("Bad page value")
	}
	dataSet := []schema.InstancePointer{}
	if asPage.Data != nil {
		for _, item := range asPage.Data {
			asInstance, ok := item.(schema.InstancePointer)
			if !ok {
				panic("Bad instance value in page value")
			}
			dataSet = append(dataSet, asInstance)
		}
	}
	return PointerSet{Data: dataSet}
}

type RelationshipStub struct{}

func (stub RelationshipStub) GetSelectExtra() ([]string, []interface{}) {
	return []string{}, []interface{}{}
}
func (stub RelationshipStub) AvailableFilters() []interface{} {
	return []interface{}{}
}
func (stub RelationshipStub) ValidateFilters(map[string][]string) ([]schema.Filter, error) {
	return []schema.Filter{}, nil
}
func (stub RelationshipStub) GetFilterWhere(int, map[string][]string) ([]string, []interface{}) {
	return []string{}, []interface{}{}
}
func (stub RelationshipStub) DefaultFallback(
	c schema.Context,
	val interface{},
	instance interface{},
) (
	interface{},
	error,
) {
	return val, nil
}
func (stub RelationshipStub) Validate(c schema.Context, val interface{}) (interface{}, error) {
	return val, nil
}
func (stub RelationshipStub) ValidateUpdate(
	c schema.Context,
	newVal interface{},
	oldVal interface{},
) (
	interface{},
	error,
) {
	return nil, nil
}
func (stub RelationshipStub) GetInsert(val interface{}) ([]string, []interface{}) {
	return []string{}, []interface{}{}
}
func (stub RelationshipStub) GetInsertQueries(newId string, val interface{}) []schema.Query {
	return []schema.Query{}
}
func (stub RelationshipStub) GetUpdateQueries(id string, oldVal interface{}, newVal interface{}) []schema.Query {
	return []schema.Query{}
}

func AssertPointer(val interface{}) Pointer {
	pointerVal, ok := val.(Pointer)
	if !ok {
		panic("Bad pointer value")
	}
	return pointerVal
}

func AssertPointerSet(val interface{}) PointerSet {
	pageVal, ok := val.(PointerSet)
	if !ok {
		panic("Bad pointer set value")
	}
	return pageVal
}

func ParseStringInstancePointer(stringPointer interface{}) (schema.InstancePointer, error) {
	pointer, ok := stringPointer.(map[string]interface{})
	if !ok {
		return schema.InstancePointer{}, errors.New("Invalid pointer.")
	}

	// parse the id
	pointerId, exists := pointer["id"]
	if !exists {
		return schema.InstancePointer{}, errors.New("Invalid pointer (missing ID).")
	}
	parsedId, ok := pointerId.(string)
	if !ok {
		return schema.InstancePointer{}, errors.New("Invalid pointer (bad ID).")
	}

	// parse the type
	pointerType, exists := pointer["type"]
	if !exists {
		return schema.InstancePointer{}, errors.New("Invalid pointer (missing Type).")
	}
	parsedType, ok := pointerType.(string)
	if !ok {
		return schema.InstancePointer{}, errors.New("Invalid pointer (bad Type).")
	}

	return schema.InstancePointer{
		Type: parsedType,
		ID:   &parsedId,
	}, nil
}

func ParseResultPointer(val interface{}) (Pointer, error) {
	resultVal, ok := val.(schema.Result)
	if !ok {
		panic("Invalid result")
	}

	if resultVal.Provided {
		if resultVal.Data == nil {
			return Pointer{
				Provided: true,
				Data:     nil,
			}, nil
		} else {
			pointer, err := ParseStringInstancePointer(resultVal.Data)
			if err != nil {
				return Pointer{}, err
			}
			return Pointer{
				Provided: true,
				Data:     &pointer,
			}, nil
		}
	}

	return Pointer{
		Provided: false,
		Data:     nil,
	}, nil
}

func ParsePagePointerSet(val interface{}) (PointerSet, error) {
	pageVal, ok := val.(schema.Page)
	if !ok {
		panic("Invalid page")
	}
	pointersVal := PointerSet{
		Provided: pageVal.Provided,
	}
	for _, stringPointer := range pageVal.Data {
		pointer, err := ParseStringInstancePointer(stringPointer)
		if err != nil {
			return PointerSet{}, err
		}
		pointersVal.Data = append(pointersVal.Data, pointer)
	}
	return pointersVal, nil
}


text:
<?php
use models\scriptureforge\typesetting\SettingModel;

use models\scriptureforge\typesetting\SettingModelLayout;

use models\scriptureforge\typesetting\commands\TypesettingSettingsCommands;

use models\ProjectModel;

use models\scriptureforge\typesetting\RapumaSettingListModel;
use models\scriptureforge\typesetting\RapumaSettingModel;
use models\scriptureforge\typesetting\commands\TypesettingSettingCommands;
use models\mapper\JsonDecoder;
use models\mapper\JsonEncoder;

require_once dirname(__FILE__) . '/../../../TestConfig.php';
require_once SimpleTestPath . 'autorun.php';

require_once TestPath . 'common/MongoTestEnvironment.php';

require_once SourcePath . "models/ProjectModel.php";
// require_once SourcePath . "models/RapumaSettingModel.php";

class TypesettingSettingCommands_Test extends UnitTestCase
{
    public function testUpdateLayoutSetting_currentSetting_layoutUpdated() {
        $e = new MongoTestEnvironment();
        $e->clean();

        $projectModel = $e->createProject(SF_TESTPROJECT, SF_TESTPROJECTCODE);
        $projectId = $projectModel->id->asString();

        $userId = $e->createUser('me', 'me', 'me@me.com');

        $layoutSetting = array();
        $layoutSetting['docInfoText'] = 'my text';

        $currentSetting = SettingModel::getCurrent($projectModel);
        $this->assertEqual($currentSetting->layout->docInfoText, "");

        TypesettingSettingsCommands::updateLayoutSettings($projectId, $userId, $layoutSetting);

        $currentSetting = SettingModel::getCurrent($projectModel);
        $this->assertEqual($currentSetting->layout->docInfoText, "my text");

    }

    /* cjh disabled since it's using the wrong models (should use SettingsModel)
    public function testCRUD_Works() {
        $e = new MongoTestEnvironment();
        $projectModel = $e->createProject(SF_TESTPROJECT, SF_TESTPROJECTCODE);
        $projectId = $projectModel->id->asString();

        $testSetting = new RapumaSettingModel($projectModel);
        $testSettingData = JsonEncoder::encode($testSetting);
        //var_dump($testSettingData);

        // List
        $list = TypesettingSettingCommands::listTypesettingSetting($projectId);
        $list->read();
        $this->assertEqual(0, $list->count);

        // Create
        $settingId = TypesettingSettingCommands::updateLayoutSettings($projectId, $testSettingData);
        $setting = new RapumaSettingModel($projectModel, $settingId);
        $this->assertNotNull($setting->layout);
        foreach(get_object_vars($setting->layout) as $attribute){
            $this->assertEqual('',$attribute);
        }

        // Read back
        $differentSetting = TypesettingSettingCommands::readTypesettingSetting($projectId, $settingId);
        $newSetting = JsonDecoder::decode($setting, $differentSetting);
        $this->assertNotEqual('',$differentSetting['id']);
        $newSetting = new RapumaSettingModel($projectModel,$differentSetting['id']);
        //test if differentSetting is read properly from database
        //testing if contents of RapumaSettingModels are the same
        $this->assertTrue($setting == $newSetting);

        // Update
        $newTestSettingData = $testSettingData;
        //make sure newTestSettingData reffers to previous setting created earlier
        $newTestSettingData['id'] = $settingId;
        $newTestSettingData['layout']['insideMargin'] = 50;
        $newTestSettingData['layout']['outsideMargin'] = 50;
        $settingId = TypesettingSettingCommands::updateLayoutSettings($projectId, $newTestSettingData);

        // Read back
        $differentSetting = TypesettingSettingCommands::readTypesettingSetting($projectId, $settingId);
        $newSetting = JsonDecoder::decode($setting, $differentSetting);
        $this->assertEqual(50,$differentSetting['layout']['insideMargin']);
        $this->assertEqual(50,$differentSetting['layout']['outsideMargin']);
        $newSetting = new RapumaSettingModel($projectModel,$differentSetting['id']);
        //test if differentSetting is read properly from database
        //testing if contents of RapumaSettingModels are the same
        $this->assertTrue($setting == $newSetting);

        // List
        $list = TypesettingSettingCommands::listTypesettingSetting($projectId);
        $list->read();
        $this->assertEqual(1, $list->count);

        // Delete
        $totalDeleted = TypesettingSettingCommands::deleteTypesettingSetting($projectId, $settingId);
        $this->assertEqual(1,$totalDeleted);

        // List
        $list->read();
        $this->assertEqual(0, $list->count);

    }
    */
}


text:
import cornerstone from 'cornerstone-core';
import { MeasurementApi } from '../classes';
import log from '../../log';

export default function({ eventData, tool, toolGroupId, toolGroup }) {
  const measurementApi = MeasurementApi.Instance;
  if (!measurementApi) {
    log.warn('Measurement API is not initialized');
  }

  const { measurementData, toolType } = eventData;

  const collection = measurementApi.tools[toolType];

  // Stop here if the tool data shall not be persisted (e.g. temp tools)
  if (!collection) return;

  log.info('CornerstoneToolsMeasurementModified');
  let measurement = collection.find(t => t._id === measurementData._id);

  // Stop here if the measurement is already deleted
  if (!measurement) return;

  measurement = Object.assign(measurement, measurementData);
  measurement.viewport = cornerstone.getViewport(eventData.element);

  measurementApi.updateMeasurement(toolType, measurement);

  // TODO: Notify about the last activated measurement

  if (MeasurementApi.isToolIncluded(tool)) {
    // TODO: Notify that viewer suffered changes
  }
}


text:
import ShareYourSystem as SYS

#Definition a structure of Grouper
MyGrouper=SYS.GrouperClass().hdformat(
	_FileKeyStr='Groupers.hdf5',
	**{
		'FolderingPathStr':SYS.Grouper.LocalFolderPathStr
	}
		).update(
			[
				(
					'<Tree>FirstChildGrouper',
					SYS.GrouperClass().update(
						[
							('<Tree>GrandChildGrouper',
							SYS.GrouperClass())
						]
					)
				),
				(
					'<Tree>SecondChildGrouper',
					SYS.GrouperClass()
				)
			]
		)

#Walk to set the same structure in the hdf5
MyGrouper.walk(
		{
				'BeforeUpdateList':
				[
					('parent',{'LiargVariablesList':[['HdformatedFileVariable']]}),
					('group',{'LiargVariablesList':[]})
				],
				'GatherVariablesList':['<Tree>']
		}
).hdfclose()

#Definition the AttestedStr
SYS._attest(
	[
		'MyGrouper is '+SYS._str(
		MyGrouper,
		**{
			'RepresentingBaseKeyStrsListBool':False,
			'RepresentingAlineaIsBool':False
			}
		),
		'MyGrouper.hdfview().HdformatedConsoleStr is '+MyGrouper.hdfview().HdformatedConsoleStr
	]
)

#Print


text:
version: '3.1.6'
---

- Make CacheKey class extendible (#604)
- Remove support for spring 1.5.x (#628)
- Fix for older Android versions (#585 #581 #580)


text:
extern NSString *WebKitErrorDomain;

extern NSString * const WebKitErrorMIMETypeKey;
extern NSString * const WebKitErrorPlugInNameKey;
extern NSString * const WebKitErrorPlugInPageURLStringKey;

/*!
    @enum
    @abstract Policy errors
    @constant WebKitErrorCannotShowMIMEType
    @constant WebKitErrorCannotShowURL
    @constant WebKitErrorFrameLoadInterruptedByPolicyChange
*/
enum {
    WebKitErrorCannotShowMIMEType =                             100,
    WebKitErrorCannotShowURL =                                  101,
    WebKitErrorFrameLoadInterruptedByPolicyChange =             102,
};

/*!
    @enum
    @abstract Plug-in and java errors
    @constant WebKitErrorCannotFindPlugIn
    @constant WebKitErrorCannotLoadPlugIn
    @constant WebKitErrorJavaUnavailable
    @constant WebKitErrorBlockedPlugInVersion
*/
enum {
    WebKitErrorCannotFindPlugIn =                               200,
    WebKitErrorCannotLoadPlugIn =                               201,
    WebKitErrorJavaUnavailable =                                202,
    WebKitErrorBlockedPlugInVersion =                           203,
};


text:
grid-for-chrome
===============

Overlay the 960 Grid system over any website. Add on for chrome. Customizable.


text:
package controllers

import connectors.HmrcTierConnectorWrapped
import controllers.utils.{ControllerUtils, URIInformation}
import helper.MockURIInformation
import models.{HeaderTags, PbikCredentials}
import org.mockito.Matchers._
import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar
import org.scalatestplus.play.PlaySpec
import play.api.Application
import play.api.http.HttpEntity.Strict
import play.api.inject._
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.json.{JsValue, Json, OFormat}
import play.api.mvc.{AnyContent, Request}
import play.api.test.FakeRequest
import play.api.test.Helpers._
import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class ControllerUtilsSpec extends PlaySpec with MockitoSugar with FakePBIKApplication {

  implicit lazy override val app: Application = new GuiceApplicationBuilder()
    .configure(config)
    .overrides(bind(classOf[URIInformation]).to(classOf[MockURIInformation]))
    .build()

  val testRequestBody: JsValue = Json.toJson(List.empty[String])
  implicit val request: Request[AnyContent] = FakeRequest().withJsonBody(testRequestBody)
  implicit val formats: OFormat[PbikCredentials] = Json.format[PbikCredentials]

  val year = 2014
  val employer_number_code = "Mock-Employer-Number-Code"
  val paye_scheme_type = 1000
  val mockedBaseUrl = "baseUrl"
  val urlExtension = "urlExtension"

  val mockCredentials: PbikCredentials = PbikCredentials(1, 2, 3, "aoReference", "payeSchemeOperatorName")
  class FakeResponse extends HttpResponse {
    override val allHeaders: Map[String, Seq[String]] = Map[scala.Predef.String, scala.Seq[scala.Predef.String]]()
    override def status = 200
    override val json: JsValue = Json.toJson(mockCredentials)
    override val body: String = Json.toJson(mockCredentials).toString()
  }
  //TODO refine when more info about statuses is available
  val mockWsResponseStatus200: HttpResponse = mock[HttpResponse]
  val mockWsResponseStatus404: HttpResponse = mock[HttpResponse]

  when(mockWsResponseStatus200.status).thenReturn(200)
  when(mockWsResponseStatus200.body).thenReturn("Body of response with status 200")
  when(mockWsResponseStatus404.status).thenReturn(404)
  when(mockWsResponseStatus404.body).thenReturn("Body of response with status 404")

  val mockHmrcTierConnectorWrapped: HmrcTierConnectorWrapped = mock[HmrcTierConnectorWrapped]

  val mockWSResponse: HttpResponse = mock[HttpResponse]
  when(mockHmrcTierConnectorWrapped.retrieveDataGet(anyString())(anyObject()))
    .thenReturn(Future.successful(mockWSResponse))

  when(mockWSResponse.json) thenReturn Json.toJson(mockCredentials)

  def mockControllerUtils: ControllerUtils = app.injector.instanceOf[ControllerUtils]

  val mockTierConnector: HmrcTierConnectorWrapped = mock[HmrcTierConnectorWrapped]
  when(mockTierConnector.retrieveDataGet(anyString)(any[HeaderCarrier])).thenReturn(Future.successful(new FakeResponse))

  "The valid Credential check" should {
    "Return valid credentials from NPS" in {
      running(app) {
        val result = await(
          mockControllerUtils
            .retrieveCrendtialsFromNPS(mockHmrcTierConnectorWrapped, year, employer_number_code, paye_scheme_type))
        result must be(mockCredentials)
      }
    }
  }

  "The status to response map" should {
    "Successfully return a response with status 200" in {
      val result = await(mockControllerUtils.generateResultBasedOnStatus(Future { mockWsResponseStatus200 }))
      result.body.asInstanceOf[Strict].data.utf8String must be("Body of response with status 200")

    }
  }

  "The status to response map" should {
    "Successfully return a response with status 404" in {

      val result = await(mockControllerUtils.generateResultBasedOnStatus(Future { mockWsResponseStatus404 }))
      result.body.asInstanceOf[Strict].data.utf8String must be("Body of response with status 404")

    }
  }

  "The controller utils " should {
    "return valid credentials when a valid empref is supplied " in {
      val result = await(mockControllerUtils.retrieveNPSCredentials(mockTierConnector, 2015, "123/TEST1"))
      assert(result.aoReference == "aoReference")
    }
  }

  "The controller utils " should {
    "return a tuple splitting the empref correctly into 2 parts " in {
      val result = mockControllerUtils.extractEmployerRefParts("123/TEST1")
      assert(result._1 == "TEST1")
      assert(result._2 == 123)
    }
  }

  "The controller utils " should {
    "return valid credentials when parsing a marshalled Pbikcredentials object from json " in {
      val result = await(mockControllerUtils.retrieveCrendtialsFromNPS(mockTierConnector, 2015, "TEST1", 123))
      assert(result.aoReference == "aoReference")
    }
  }

  "The controller utils" should {
    "return error code when upstream error 63092" in {
      val failedResponse =
        "{\"message\":\"Internal Server Error\",\"statusCode\":500,\"appStatusMessage\":\";63092\",\"requestUri\":\"\"}"
      val result = mockControllerUtils.extractUpstreamError(failedResponse)
      result must be("63092")
    }

    "return error code when upstream error 64989" in {
      val failedResponse =
        "{\"message\":\"Internal Server Error\",\"statusCode\":500,\"appStatusMessage\":\";64989\",\"requestUri\":\"\"}"
      val result = mockControllerUtils.extractUpstreamError(failedResponse)
      result must be("64989")
    }

    "return default error code when upstream error not found" in {
      val failedResponse =
        "{\"message\":\"Internal Server Error\",\"statusCode\":500,\"appStatusMessage\":\";Invalid version number\",\"requestUri\":\"\"}"
      val result = mockControllerUtils.extractUpstreamError(failedResponse)
      result must be("")
    }

  }

  "When NPS returns response " should {
    "with headers return the ETAG and TXID headers" in {

      val npsRequestBody = Json.toJson(List.empty[String])
      implicit val request: Request[AnyContent] = FakeRequest()
        .withJsonBody(npsRequestBody)
        .withHeaders(HeaderTags.ETAG -> "10", HeaderTags.X_TXID -> "1")

      val result = await(mockControllerUtils.getNPSMutatorSessionHeader(request))
      result must be(Some(Map("ETag" -> "10", "X-TXID" -> "1")))
    }

    "return None when there is no ETAG value" in {

      val npsRequestBody = Json.toJson(List.empty[String])
      implicit val request: Request[AnyContent] = FakeRequest()
        .withJsonBody(npsRequestBody)
        .withHeaders()

      val result = await(mockControllerUtils.getNPSMutatorSessionHeader(request))
      result must be(None)
    }
  }

}


text:
class StaticController < ApplicationController

	skip_before_action :authenticate_user!

	def index
    render :layout => false
	end

end