text:
/**
 * Init the variable
 */
Roles = {}

Roles.debug = false

/**
 * Initialize variables
 */
Roles._roles = {}
Roles._actions = []
Roles._helpers = []
Roles._usersCollection = Meteor.users
Roles._specialRoles = ['__loggedIn__', '__notAdmin__', '__notLoggedIn__', '__all__']

/**
 * Old collection
 */
Roles._oldCollection = new Mongo.Collection('roles')

/**
 * Get the list of roles
 */
Roles.availableRoles = function () {
  return _.difference(_.keys(this._roles), this._specialRoles)
}

/**
 * Check if a user has a role
 */
Roles.userHasRole = function (userId, role) {
  if (role == '__all__') return true
  if (role == '__notLoggedIn__' && !userId) return true
  if (role == '__default__' && userId) return true
  if (
    role == '__notAdmin__' &&
    Roles._usersCollection.find({ _id: userId, roles: 'admin' }).count() === 0
  ) return true
  return Roles._usersCollection.find({ _id: userId, roles: role }).count() > 0
}

/**
 * Creates a new action
 */
Roles.registerAction = function (name, adminAllow, adminDeny) {
  check(name, String)
  check(adminAllow, Match.Optional(Match.Any))
  check(adminDeny, Match.Optional(Match.Any))

  if (!_.contains(this._actions, name)) {
    this._actions.push(name)
  }

  if (adminAllow) {
    Roles.adminRole.allow(name, adminAllow)
  }

  if (adminDeny) {
    Roles.adminRole.deny(name, adminDeny)
  }
}

/**
 * Creates a new helper
 */
Roles.registerHelper = function (name, adminHelper) {
  check(name, String)
  check(adminHelper, Match.Any)

  if (!_.contains(this._helpers, name)) {
    this._helpers.push(name)
  }

  if (adminHelper) {
    Roles.adminRole.helper(name, adminHelper)
  }
}

/**
 * Constructs a new role
 */
Roles.Role = function (name) {
  check(name, String)

  if (!(this instanceof Roles.Role))
    throw new Error('use "new" to construct a role')

  if (_.has(Roles._roles, name))
    throw new Error('"' + name + '" role is already defined')

  this.name = name
  this.allowRules = {}
  this.denyRules = {}
  this.helpers = {}

  Roles._roles[name] = this
}

/**
 * Adds allow properties to a role
 */
Roles.Role.prototype.allow = function (action, allow) {
  check(action, String)
  check(allow, Match.Any)

  if (!_.contains(Roles._actions, action)) {
    Roles.registerAction(action)
  }

  if (!_.isFunction(allow)) {
    var clone = _.clone(allow)
    allow = function () {
      return clone
    }
  }

  this.allowRules[action] = this.allowRules[action] || []
  this.allowRules[action].push(allow)
}

/**
 * Adds deny properties to a role
 */
Roles.Role.prototype.deny = function (action, deny) {
  check(action, String)
  check(deny, Match.Any)

  if (!_.contains(Roles._actions, action)) {
    Roles.registerAction(action)
  }

  if (!_.isFunction(deny)) {
    var clone = _.clone(deny)
    deny = function () {
      return clone
    }
  }

  this.denyRules[action] = this.denyRules[action] || []
  this.denyRules[action].push(deny)
}

/**
 * Adds a helper to a role
 */
Roles.Role.prototype.helper = function (helper, func) {
  check(helper, String)
  check(func, Match.Any)

  if (!_.contains(Roles._helpers, helper)) {
    Roles.registerHelper(helper)
  }

  if (!_.isFunction(func)) {
    var value = _.clone(func)
    func = function () {
      return value
    }
  }

  if (!this.helpers[helper]) {
    this.helpers[helper] = []
  }

  this.helpers[helper].push(func)
}

/**
 * Get user roles
 */
Roles.getUserRoles = function (userId, includeSpecial) {
  check(userId, Match.OneOf(String, null, undefined))
  check(includeSpecial, Match.Optional(Boolean))
  var object = Roles._usersCollection.findOne({ _id: userId }, { fields: { roles: 1 } })
  var roles = (object && object.roles) || []
  if (includeSpecial) {
    roles.push('__all__')
    if (!userId) {
      roles.push('__notLoggedIn__')
    } else {
      roles.push('__loggedIn__')
      if (!_.contains(roles, 'admin')) {
        roles.push('__notAdmin__')
      }
    }
  }

  return roles
}

/**
 * Calls a helper
 */
Roles.helper = function (userId, helper) {
  check(userId, Match.OneOf(String, null, undefined))
  check(helper, String)
  if (!_.contains(this._helpers, helper)) throw 'Helper "' + helper + '" is not defined'

  var args = _.toArray(arguments).slice(2)
  var context = { userId: userId }
  var responses = []
  var roles = Roles.getUserRoles(userId, true)

  _.each(roles, (role) => {
    if (this._roles[role] && this._roles[role].helpers && this._roles[role].helpers[helper]) {
      var helpers = this._roles[role].helpers[helper]
      _.each(helpers, (helper) => {
        responses.push(helper.apply(context, args))
      })
    }
  })

  return responses
}

/**
 * Returns if the user passes the allow check
 */
Roles.allow = function (userId, action) {
  check(userId, Match.OneOf(String, null, undefined))
  check(action, String)

  var args = _.toArray(arguments).slice(2)
  var self = this
  var context = { userId: userId }
  var allowed = false
  var roles = Roles.getUserRoles(userId, true)

  _.each(roles, function (role) {
    if (!allowed && self._roles[role] && self._roles[role].allowRules && self._roles[role].allowRules[action]) {
      _.each(self._roles[role].allowRules[action], function (func) {
        var allow = func.apply(context, args)
        if (allow === true) {
          allowed = true
        }
      })
    }
  })

  return allowed
}

/**
 * Returns if the user has permission using deny and deny
 */
Roles.deny = function (userId, action) {
  check(userId, Match.OneOf(String, null, undefined))
  check(action, String)

  var args = _.toArray(arguments).slice(2)
  var context = { userId: userId }
  var denied = false
  var roles = Roles.getUserRoles(userId, true)

  _.each(roles, (role) => {
    if (
      !denied &&
      this._roles[role] &&
      this._roles[role].denyRules &&
      this._roles[role].denyRules[action]
    ) {
      _.each(this._roles[role].denyRules[action], (func) => {
        var denies = func.apply(context, args)
        if (denies === true) {
          denied = true
          if (Roles.debug) {
            console.log(`[${action}] denied for ${userId} with role ${role}`)
          }
        }
      })
    }
  })

  return denied
}

/**
 * To check if a user has permisisons to execute an action
 */
Roles.userHasPermission = function () {
  var allows = this.allow.apply(this, arguments)
  var denies = this.deny.apply(this, arguments)
  return allows === true && denies === false
}

/**
 * If the user doesn't has permission it will throw a error
 */
Roles.checkPermission = function () {
  if (!this.userHasPermission.apply(this, arguments)) {
    throw new Meteor.Error('unauthorized', 'The user has no permission to perform this action')
  }
}

/**
 * Adds helpers to users
 */
Roles.setUsersHelpers = function () {
  Roles._usersCollection.helpers({
    /**
     * Returns the user roles
     */
    getRoles: function (includeSpecial) {
      return Roles.getUserRoles(this._id, includeSpecial)
    },
    /**
     * To check if the user has a role
     */
    hasRole: function (role) {
      return Roles.userHasRole(this._id, role)
    },
  })
}

Roles.setUsersHelpers()

/**
 * The admin role, who recives the default actions.
 */
Roles.adminRole = new Roles.Role('admin'); Roles._adminRole = Roles.adminRole // Backwards compatibility
/**
 * All the logged in users users
 */
Roles.loggedInRole = new Roles.Role('__loggedIn__'); Roles.defaultRole = Roles.loggedInRole // Backwards compatibility
/**
 * The users that are not admins
 */
Roles.notAdminRole = new Roles.Role('__notAdmin__')
/**
 * The users that are not logged in
 */
Roles.notLoggedInRole = new Roles.Role('__notLoggedIn__')
/**
 * Always, no exception
 */
Roles.allRole = new Roles.Role('__all__')

/**
 * A Helper to attach actions to collections easily
 */
Mongo.Collection.prototype.attachRoles = function (name, dontAllow) {
  Roles.registerAction(name + '.insert', !dontAllow)
  Roles.registerAction(name + '.update', !dontAllow)
  Roles.registerAction(name + '.remove', !dontAllow)
  Roles.registerHelper(name + '.forbiddenFields', [])

  this.allow({
    insert: function (userId, doc) {
      var allows = Roles.allow(userId, name + '.insert', userId, doc)
      if (Roles.debug && !allows) {
        console.log(`[${name}.insert] not allowed for ${userId}`)
      }

      return allows
    },

    update: function (userId, doc, fields, modifier) {
      var allows = Roles.allow(userId, name + '.update', userId, doc, fields, modifier)
      if (Roles.debug && !allows) {
        console.log(`[${name}.update] not allowed for ${userId}`)
      }

      return allows
    },

    remove: function (userId, doc) {
      var allows = Roles.allow(userId, name + '.remove', userId, doc)
      if (Roles.debug && !allows) {
        console.log(`[${name}.remove] not allowed for ${userId}`)
      }

      return allows
    }
  })

  this.deny({
    insert: function (userId, doc) {
      return Roles.deny(userId, name + '.insert', userId, doc)
    },

    update: function (userId, doc, fields, modifier) {
      return Roles.deny(userId, name + '.update', userId, doc, fields, modifier)
    },

    remove: function (userId, doc) {
      return Roles.deny(userId, name + '.remove', userId, doc)
    },
  })

  this.deny({
    insert: function (userId, doc) {
      var forbiddenFields = _.union.apply(this, Roles.helper(userId, name + '.forbiddenFields'))

      for (var i in forbiddenFields) {
        var field = forbiddenFields[i]
        if (objectHasKey(doc, field)) {
          if (Roles.debug) {
            console.log(`[${name}.forbiddenField] Field ${field} is forbidden for ${userId}`)
          }

          return true
        }
      }
    },

    update: function (userId, doc, fields, modifier) {
      var forbiddenFields = _.union.apply(this, Roles.helper(userId, name + '.forbiddenFields', doc._id))
      var types = ['$inc', '$mul', '$rename', '$setOnInsert', '$set', '$unset', '$min', '$max', '$currentDate']

      // By some reason following for will itterate even through empty array. This will prevent unwanted habbit.
      if (forbiddenFields.length === 0) {
        return false
      }

      for (var i in forbiddenFields) {
        var field = forbiddenFields[i]
        for (var j in types) {
          var type = types[j]
          if (objectHasKey(modifier[type], field)) {
            if (Roles.debug) {
              console.log(`[${name}.forbiddenField] Field ${field} is forbidden for ${userId}`)
            }

            return true
          }

          if (willChangeWithParent(modifier[type], field)) {
            if (Roles.debug) {
              console.log(`[${name}.forbiddenField] Field ${field} is forbidden for ${userId} is been changed by a parent object`)
            }

            return true
          }
        }
      }
    },
  })
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SolidEdgeCommunity.Reader.Draft
{
    [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
    internal class SheetPaperSizeAttribute : Attribute
    {
        private double _width;
        private double _height;
        private string _description;

        public SheetPaperSizeAttribute(double width, double height, string description)
        {
            _width = width;
            _height = height;
            _description = description;
        }

        public double Width { get { return _width; } }
        public double Height { get { return _height; } }
        public string Description { get { return _description; } }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.ambari.server.controller;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.HostNotFoundException;
import org.apache.ambari.server.controller.RootServiceResponseFactory.Services;
import org.apache.ambari.server.controller.internal.RequestOperationLevel;
import org.apache.ambari.server.controller.internal.RequestResourceFilter;
import org.apache.ambari.server.controller.spi.Resource;
import org.apache.ambari.server.state.Alert;
import org.apache.ambari.server.state.Cluster;
import org.apache.ambari.server.state.Clusters;
import org.apache.ambari.server.state.Host;
import org.apache.ambari.server.state.MaintenanceState;
import org.apache.ambari.server.state.Service;
import org.apache.ambari.server.state.ServiceComponent;
import org.apache.ambari.server.state.ServiceComponentHost;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;

/**
 * Used to help manage maintenance state checks.
 */
@Singleton
public class MaintenanceStateHelper {
  private static final Logger LOG = LoggerFactory.getLogger(MaintenanceStateHelper.class);

  @Inject
  private Clusters clusters;

  @Inject
  public MaintenanceStateHelper(Injector injector) {
    injector.injectMembers(this);
  }

  /**
   * @param cluster
   *          cluster for request
   * @param levelObj
   *          operation level (can be null)
   * @param reqFilter
   *          request resource filter for operation (can't be null)
   * @param serviceName
   *          service name (can be null)
   * @param componentName
   *          component name (can be null)
   * @param hostname
   *          host name (can't be null)
   * @return true if operation may be performed on a given target (based on
   *         target's maintenance status).
   */
  public boolean isOperationAllowed(Cluster cluster,
      RequestOperationLevel levelObj, RequestResourceFilter reqFilter,
      String serviceName, String componentName, String hostname)
      throws AmbariException {
    Resource.Type level;
    if (levelObj == null) {
      level = guessOperationLevel(reqFilter);
    } else {
      level = levelObj.getLevel();
    }
    return isOperationAllowed(cluster, level, serviceName, componentName,
        hostname);
  }

  /**
   * @param cluster
   *          cluster for request
   * @param level
   *          operation level (can't be null)
   * @param serviceName
   *          service name (can be null)
   * @param componentName
   *          component name (can be null)
   * @param hostname
   *          host name (can't be null)
   * @return true if operation may be performed on a given target (based on
   *         target's maintenance status).
   */
  boolean isOperationAllowed(Cluster cluster, Resource.Type level,
      String serviceName, String componentName, String hostname)
      throws AmbariException {
    if (serviceName != null && !serviceName.isEmpty()) {
      Service service = cluster.getService(serviceName);
      if (componentName != null && !componentName.isEmpty()) {
        ServiceComponentHost sch = service.getServiceComponent(componentName).getServiceComponentHost(
            hostname);
        return isOperationAllowed(level, sch);
      } else { // Only service name is defined
        return isOperationAllowed(level, service);
      }
    } else { // Service is not defined, using host
      Host host = clusters.getHost(hostname);
      return isOperationAllowed(host, cluster.getClusterId(), level);
    }
  }

  /**
   * @param level
   *          operation level
   * @param service
   *          the service
   * @return true if operation may be performed on a given target (based on
   *         target's maintenance status).
   */
  public boolean isOperationAllowed(Resource.Type level, Service service)
      throws AmbariException {
    if (level == Resource.Type.Cluster) {
      return service.getMaintenanceState() == MaintenanceState.OFF;
    } else {
      return true;
    }
  }

  /**
   * @param host
   *          the service
   * @param clusterId
   *          cluster the host belongs to
   * @param level
   *          operation level for request
   * @return true if operation may be performed on a given target (based on
   *         target's maintenance status).
   */
  public boolean isOperationAllowed(Host host, long clusterId,
      Resource.Type level) throws AmbariException {
    if (level == Resource.Type.Cluster) {
      return host.getMaintenanceState(clusterId) == MaintenanceState.OFF;
    } else {
      return true;
    }
  }

  /**
   * Get effective state of HostComponent
   *
   * @param sch
   *          the host component
   * @param host
   *          the host
   * @return the maintenance state
   * @throws AmbariException
   */
  public MaintenanceState getEffectiveState(ServiceComponentHost sch, Host host)
      throws AmbariException {
    Cluster cluster = clusters.getCluster(sch.getClusterName());
    Service service = cluster.getService(sch.getServiceName());

    if (null == host) {
      throw new HostNotFoundException(cluster.getClusterName(),
          sch.getHostName());
    }

    return getEffectiveState(cluster.getClusterId(), service, host, sch);
  }

  /**
   * Gets the effective state for a HostComponent
   *
   * @param sch
   *          the host component
   * @return the maintenance state
   * @throws AmbariException
   */
  public MaintenanceState getEffectiveState(ServiceComponentHost sch)
      throws AmbariException {
    Host host = clusters.getHost(sch.getHostName());
    return getEffectiveState(sch, host);
  }

  /**
   * @param clusterId
   *          the cluster id
   * @param service
   *          the service
   * @param host
   *          the host
   * @param sch
   *          the host component
   * @return the effective maintenance state
   */
  private MaintenanceState getEffectiveState(long clusterId, Service service,
      Host host, ServiceComponentHost sch) {

    MaintenanceState schState = sch.getMaintenanceState();
    if (MaintenanceState.ON == schState) {
      return MaintenanceState.ON;
    }

    MaintenanceState serviceState = service.getMaintenanceState();
    MaintenanceState hostState = host.getMaintenanceState(clusterId);

    if (MaintenanceState.OFF != serviceState
        && MaintenanceState.OFF != hostState) {
      return MaintenanceState.IMPLIED_FROM_SERVICE_AND_HOST;
    }

    if (MaintenanceState.OFF != serviceState) {
      return MaintenanceState.IMPLIED_FROM_SERVICE;
    }

    if (MaintenanceState.OFF != hostState) {
      return MaintenanceState.IMPLIED_FROM_HOST;
    }

    return schState;
  }

  /**
   * Gets the effective maintenance state for a given alert. This will determine
   * whether the alert needs to report that it is in maintenance mode.
   *
   * @param clusterId
   *          the ID of the cluster for the alert.
   * @param alert
   *          the alert (not {@code null}).
   * @return {@link MaintenanceState#OFF} if the host/service/component all
   *         report they are not in maintenance mode;
   *         {@link MaintenanceState#ON} otherwise.
   * @throws AmbariException
   */
  public MaintenanceState getEffectiveState(long clusterId, Alert alert) throws AmbariException {
    String serviceName = alert.getService();
    String componentName = alert.getComponent();
    String hostName = alert.getHostName();

    if (null == serviceName && null == hostName) {
      LOG.warn("Unable to determine maintenance state for an alert without a service or host");
      return MaintenanceState.OFF;
    }

    // always start with the host first; we always have a host unless this is an
    // aggregate alert (service-level alert)
    if (StringUtils.isNotBlank(hostName)) {
      Host host = clusters.getHost(hostName);
      if (host.getMaintenanceState(clusterId) != MaintenanceState.OFF) {
        return MaintenanceState.ON;
      }
    }

    // the AMBARI service is not a real service; it's never in MM
    if( StringUtils.equals(Services.AMBARI.name(), serviceName)){
      return MaintenanceState.OFF;
    }

    // the host is not in MM, move onto the service
    Cluster cluster = clusters.getClusterById(clusterId);
    Service service = cluster.getService(serviceName);
    if( service.getMaintenanceState() != MaintenanceState.OFF ){
      return MaintenanceState.ON;
    }

    if( StringUtils.isNotBlank(componentName)){
      ServiceComponent serviceComponent = service.getServiceComponent(componentName);
      ServiceComponentHost serviceComponentHost = serviceComponent.getServiceComponentHost(hostName);

      if (serviceComponentHost.getMaintenanceState() != MaintenanceState.OFF) {
        return MaintenanceState.ON;
      }
    }

    // MM is off at the host, service, and component level; return OFF
    return MaintenanceState.OFF;
  }

  /**
   * @param clusters
   *          the collection of clusters
   * @param cluster
   *          the specific cluster to check
   * @return a property map of all host components that are in a maintenance
   *         state (either {@link MaintenanceState#ON} or
   *         {@link MaintenanceState#IMPLIED_FROM_HOST} or
   *         {@link MaintenanceState#IMPLIED_FROM_SERVICE} or
   *         {@link MaintenanceState#IMPLIED_FROM_SERVICE_AND_HOST})
   */
  public Set<Map<String, String>> getMaintenanceHostComponents(
      Clusters clusters, Cluster cluster) throws AmbariException {
    Set<Map<String, String>> set = new HashSet<Map<String, String>>();

    Map<String, Host> hosts = clusters.getHostsForCluster(cluster.getClusterName());

    for (Service service : cluster.getServices().values()) {
      for (ServiceComponent sc : service.getServiceComponents().values()) {
        if (sc.isClientComponent()) {
          continue;
        }

        for (ServiceComponentHost sch : sc.getServiceComponentHosts().values()) {
          Host host = hosts.get(sch.getHostName());

          if (MaintenanceState.OFF != getEffectiveState(cluster.getClusterId(),
              service, host, sch)) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("host", sch.getHostName());
            map.put("service", sch.getServiceName());
            map.put("component", sch.getServiceComponentName());
            set.add(map);
          }
        }
      }
    }

    return set;
  }

  /**
   * Determine based on the requesting Resource level and the state of the
   * operand whether to allow operations on it.
   *
   * @param operationLevel
   *          Request Source: {CLUSTER, SERVICE, HOSTCOMPONENT, HOST}
   * @param sch
   *          HostComponent which is the operand of the operation
   * @return
   * @throws AmbariException
   */
  public boolean isOperationAllowed(Resource.Type operationLevel,
      ServiceComponentHost sch) throws AmbariException {
    MaintenanceState maintenanceState = getEffectiveState(sch);

    switch (operationLevel.getInternalType()) {
      case Cluster:
        if (maintenanceState.equals(MaintenanceState.OFF)) {
          return true;
        }
        break;
      case Service:
        if (maintenanceState.equals(MaintenanceState.IMPLIED_FROM_SERVICE)
            || maintenanceState.equals(MaintenanceState.OFF)) {
          return true;
        }
        break;
      case Host:
        if (maintenanceState.equals(MaintenanceState.IMPLIED_FROM_HOST)
            || maintenanceState.equals(MaintenanceState.OFF)) {
          return true;
        }
        break;
      case HostComponent: {
        return true;
      }
      default:
        LOG.warn("Unsupported Resource type, type = " + operationLevel);
        break;
    }
    return false;
  }

  /**
   * Fallback logic for guessing operation level from request resource filter.
   * It is used when operation level is not defined explicitly.
   */
  public Resource.Type guessOperationLevel(RequestResourceFilter filter) {
    Resource.Type result;
    if (filter == null) {
      // CLUSTER can be assumed to be the default level if no ResourceFilter
      // is specified, because for any other resource operation
      // a ResourceFilter is mandatory.
      result = Resource.Type.Cluster;
    } else {
      boolean serviceDefined = filter.getServiceName() != null;
      boolean componentDefined = filter.getComponentName() != null;
      boolean hostsDefined = filter.getHostNames() != null
          && filter.getHostNames().size() > 0;

      if (hostsDefined & componentDefined) {
        result = Resource.Type.HostComponent;
      } else if (!serviceDefined & hostsDefined) {
        result = Resource.Type.Host;
      } else if (serviceDefined & !hostsDefined) {
        // This option also includes resource filters
        // that target service on few hosts
        result = Resource.Type.Service;
      } else { // Absolute fallback
        // Cluster level should be a good option for any unsure cases
        // Cluster-level actions only
        result = Resource.Type.Cluster;
      }
    }
    return result;
  }

  /**
   * Removes from a set all hosts that match a given condition.
   *
   * @param candidateHosts
   *          source set that should to be modified
   * @param condition
   *          condition
   * @return all hosts that have been removed from a candidateHosts
   */
  public Set<String> filterHostsInMaintenanceState(Set<String> candidateHosts,
      HostPredicate condition) throws AmbariException {
    // Filter hosts that are in MS
    Set<String> removedHosts = new HashSet<String>();
    for (String hostname : candidateHosts) {
      if (condition.shouldHostBeRemoved(hostname)) {
        removedHosts.add(hostname);
      }
    }
    candidateHosts.removeAll(removedHosts);
    return removedHosts;
  }

  /**
   * The {@link HostPredicate} interaface is used as a way to pass a custom
   * implementation into one of the many
   * {@link MaintenanceStateHelper#isOperationAllowed(org.apache.ambari.server.controller.spi.Resource.Type, Service)}
   * methods.
   */
  public static interface HostPredicate {
    /**
     * Gets whether the specified host should not be included in a result set.
     *
     * @param hostname
     *          the host (not {@code null}).
     * @return {@code true} to indicate that the specified host is not a valid
     *         choice, {@code false} otherwise.
     * @throws AmbariException
     */
    public boolean shouldHostBeRemoved(String hostname) throws AmbariException;
  }
}


text:
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

namespace WPFDesign.Core
{
    /// <summary>
    /// Describes how a placement is done.
    /// </summary>
    public sealed class PlacementType
    {
        /// <summary>
        /// Placement is done by Moving a inner Point (for Example on Path, Line, ...)
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security",
            "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly PlacementType MovePoint =
            Register("MovePoint");

        /// <summary>
        /// Placement is done by resizing an element in a drag'n'drop operation.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security",
            "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly PlacementType Resize =
            Register("Resize");

        /// <summary>
        /// Placement is done by moving an element in a drag'n'drop operation.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security",
            "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly PlacementType Move =
            Register("Move");

        /// <summary>
        /// Placement is done by moving an element for Example via Keyboard!
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security",
            "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
        public static readonly PlacementType MoveAndIgnoreOtherContainers = Register("MoveAndIgnoreOtherContainers");

        /// <summary>
        /// Adding an element to a specified position in the container.
        /// AddItem is used when dragging a toolbox item to the design surface.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security",
            "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly PlacementType AddItem =
            Register("AddItem");

        /// <summary>
        /// Not a "real" placement, but deleting the element.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security",
            "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly PlacementType Delete =
            Register("Delete");

        /// <summary>
        /// Inserting from Cliboard
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security",
            "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly PlacementType PasteItem =
            Register("PasteItem");

        readonly string name;

        private PlacementType(string name)
        {
            this.name = name;
        }

        /// <summary>
        /// Creates a new unique PlacementKind.
        /// </summary>
        /// <param name="name">The name to return from a ToString() call.
        /// Note that two PlacementTypes with the same name are NOT equal!</param>
        public static PlacementType Register(string name)
        {
            return new PlacementType(name);
        }

        /// <summary>
        /// Gets the name used to register this PlacementType.
        /// </summary>
        public override string ToString()
        {
            return name;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="copyright" content="(C) Copyright 2005"/>
<meta name="DC.rights.owner" content="(C) Copyright 2005"/>
<meta name="DC.Type" content="reference"/>
<meta name="DC.Title" content="SPL File TestShellSourceBasic3.spl"/>
<meta name="DC.Format" content="XHTML"/>
<meta name="DC.Identifier" content="spldoc_compilationunit"/>
<link rel="stylesheet" type="text/css" href="../../html/commonltr.css"/>
<link rel="stylesheet" type="text/css" href="../../html/spldoc.css"/>
<title>SPL File TestShellSourceBasic3.spl</title>

SPL File <tt class="ph tt">TestShellSourceBasic3.spl</tt>

Toolkits > SampleShellSource 1.1.0 > sample > TestShellSourceBasic3.spl

Content

Operators

TestShellSourceBasic3: This sample application tries to execute a non-existant shell command with a ShellSource operator, and writes the shell's error code into a file.

Composites

public composite TestShellSourceBasic3

  <embed class="image" src="../../image/tk$SampleShellSource/op$sample$TestShellSourceBasic3.svg" width="232" height="200"/>

This sample application tries to execute a non-existant shell command with a ShellSource operator, and writes the shell's error code into a file.

SPL Source Code

 composite TestShellSourceBasic3 {

 	type ShellStatus =
 		rstring command,
 		int32 exitCode,
 		rstring exitReason,
 		list<uint64> counters ;

 	graph

     // execute a non-existant command and produce a status tuple containing the shell's exit code
     ( stream<rstring line> A_STDOUTStream ;
       stream<rstring line> A_STDERRStream ;
       stream<ShellStatus>  A_StatusStream ) = ShellSource() {
     param command: "no-such-command";
     output A_StatusStream:
       	command = commandLine(),
       	exitCode = exitCode(),
       	exitReason = exitReason(),
       	counters = lineCounters(); }
     () as DebugA_STDOUTStream = FileSink(A_STDOUTStream) { param file: "debug.TestShellSourceBasic3.A_STDOUTStream.out"; format: txt; hasDelayField: true; flush: 1u; writePunctuations: true; }
     () as DebugA_STDERRStream = FileSink(A_STDERRStream) { param file: "debug.TestShellSourceBasic3.A_STDERRStream.out"; format: txt; hasDelayField: true; flush: 1u; writePunctuations: true; }
     () as DebugA_StatusStream = FileSink(A_StatusStream) { param file: "debug.TestShellSourceBasic3.A_StatusStream.out"; format: txt; hasDelayField: true; flush: 1u; writePunctuations: true; }

 }


text:
package org.bubblecloud.zigbee.api.cluster.general;

/**
 * @author Stefano "Kismet" Lenzi
 * @version $LastChangedRevision: 799 $ ($LastChangedDate: 2013-08-06 19:00:05 +0300 (Tue, 06 Aug 2013) $)
 * @since 0.7.0
 */
public enum LocationType {
    AbsoluteLocation(1,0),
    MeasuredLocation(0,0),
    TwoDimensional(1,1),
    ThreeDimensional(0,1),
    Rectangular(0,2);

    public final byte value;
    public final byte bit;

    private LocationType(int value, int bit){
        this.value = (byte) value;
        this.bit = (byte) bit;
    }
}


text:
'''
'''

try:
    import markdown
except:
    print ("You need to install Python markdown module.")

def embed_value(name):
    return "{%s}" % name

class SectionCounter(object):
    '''
    Count the chapter and sessions.
    '''

    def __init__(self):
        self.section_ids = ['0']
        self.next_chapter = None

    def next_section(self, level):
        if level == 1 and self.next_chapter:
            self.section_ids = [self.next_chapter]
            self.next_chapter = None
            return
        self.section_ids.extend(['0'] * (level - len(self.section_ids)))
        self.section_ids = self.section_ids[:level]
        self.section_ids[level - 1] = self._get_next_id(self.section_ids[level - 1])

    def _get_next_id(self, next_chapter_id):
        try:
            return str(int(next_chapter_id) + 1)
        except ValueError:
            return chr(ord(next_chapter_id) + 1)

    def get_id(self, level):
        return '.'.join(self.section_ids[:level])

    def set_next_chapter(self, next_chapter):
        self.next_chapter = next_chapter

class ChapterTreeprocessor(markdown.treeprocessors.Treeprocessor):

    def __init__(self):
        self.chapter_prefix = None
        self.section_level = 0
        self.section_counter = SectionCounter()

    def run(self, doc):
        self.chapter_prefix = self._get_meta("chapter_prefix", self.chapter_prefix)
        self.section_counter.set_next_chapter(self._get_meta("next_chapter_id", None))
        self.section_level = int(self._get_meta("section_level", self.section_level))
        for elem in doc.getiterator():
            if elem.tag in ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']:
                level = int(elem.tag[-1])
                self.section_counter.next_section(level)
                if level == 1 and self.chapter_prefix:
                    elem.text = "%s %s" % (
                                           self.chapter_prefix.replace(embed_value('chapter_id'),
                                                                       self.section_counter.get_id(1)), elem.text)
                elif self.section_level >= level:
                    elem.text = "%s %s" % (self.section_counter.get_id(level), elem.text)

    def _get_meta(self, name, default = None):
        if hasattr(self.md, 'Meta'):
            if name in self.md.Meta:
                return self.md.Meta[name][0]
        return default

class PybookMarkdownExtension(markdown.Extension):

    def extendMarkdown(self, md, md_globals):
        md.registerExtension(self)
        self.processor = ChapterTreeprocessor()
        self.processor.md = md
        self.processor.config = self.getConfigs()
        md.treeprocessors.add('chapters', self.processor, '_end')


text:
package io.undertow.security.api;

import io.undertow.server.HttpServerExchange;

/**
 * The interface to be implemented by a single authentication mechanism.
 *

 * The implementation of this interface are assumed to be stateless, if there is a need to share state between the authenticate
 * and handleComplete calls then it should be held in the HttpServerExchange.
 *

 * As an in-bound request is received the authenticate method is called on each mechanism in turn until one of the following
 * occurs: - - A mechanism successfully authenticates the incoming request. - A mechanism attempts but fails to authenticate the
 * request. - The list of mechanisms is exhausted.
 *

 * This means that if the authenticate method is called on a mechanism it should assume it is required to check if it can
 * actually authenticate the incoming request, anything that would prevent it from performing the check would have already
 * stopped the authenticate method from being called.
 *

 * Authentication is allowed to proceed if either authentication was required AND one handler authenticated the request or it is
 * allowed to proceed if it is not required AND no handler failed to authenticate the request.
 *

 * The handleComplete methods are used as the request processing is returning up the chain, primarily these are used to
 * challenge the client to authenticate but where supported by the mechanism they could also be used to send mechanism specific
 * updates back with a request.
 *

 * If a mechanism successfully authenticated the incoming request then only the handleComplete method on that mechanism is
 * called.
 *

 * If any mechanism failed or if authentication was required and no mechanism succeeded in authenticating the request then
 * handleComplete will be called for all mechanisms.
 *

 * Finally if authentication was not required handleComplete will not be called for any of the mechanisms.
 *

 * The mechanisms will need to double check why handleComplete is being called, if the request was authenticated then they
 * should do nothing unless the mechanism has intermediate state to send back. If the request was not authenticated then a
 * challenge should be sent.
 *
 * @author Stuart Douglas
 * @author Darran Lofthouse
 */
public interface AuthenticationMechanism {

    /**
     * Perform authentication of the request. Any potentially blocking work should be performed in the handoff executor provided
     *
     * @param exchange The exchange
     * @return
     */
    AuthenticationMechanismOutcome authenticate(final HttpServerExchange exchange,
                                                final SecurityContext securityContext);

    /**
     * Send an authentication challenge to the remote client.
     *

     * The individual mechanisms should update the response headers and body of the message as appropriate however they should
     * not set the response code, instead that should be indicated in the {@link ChallengeResult} and the most appropriate
     * overall response code will be selected.
     *
     * @param exchange        The exchange
     * @param securityContext The security context
     * @return A {@link ChallengeResult} indicating if a challenge was sent and the desired response code.
     */
    ChallengeResult sendChallenge(final HttpServerExchange exchange, final SecurityContext securityContext);

    /**
     * The AuthenticationOutcome is used by an AuthenticationMechanism to indicate the outcome of the call to authenticate, the
     * overall authentication process will then used this along with the current AuthenticationState to decide how to proceed
     * with the current request.
     */
    public enum AuthenticationMechanismOutcome {
        /**
         * Based on the current request the mechanism has successfully performed authentication.
         */
        AUTHENTICATED,

        /**
         * The mechanism did not attempt authentication on this request, most likely due to not discovering any applicable
         * security tokens for this mechanisms in the request.
         */
        NOT_ATTEMPTED,

        /**
         * The mechanism attempted authentication but it did not complete, this could either be due to a failure validating the
         * tokens from the client or it could be due to the mechanism requiring at least one additional round trip with the
         * client - either way the request will return challenges to the client.
         */
        NOT_AUTHENTICATED;
    }

    /**
     * Simple class to wrap the result of requesting a mechanism sends it's challenge.
     */
    public class ChallengeResult {

        private final boolean challengeSent;
        private final Integer statusCode;

        public ChallengeResult(final boolean challengeSent, final Integer statusCode) {
            this.statusCode = statusCode;
            this.challengeSent = challengeSent;
        }

        public ChallengeResult(final boolean challengeSent) {
            this(challengeSent, null);
        }

        /**
         * Obtain the response code desired by this mechanism for the challenge.
         *

         * Where multiple mechanisms are in use concurrently all of the requested response codes will be checked and the most
         * suitable one selected. If no specific response code is required any value less than 0 can be set.
         *
         * @return The desired response code or null if no code specified.
         */
        public Integer getDesiredResponseCode() {
            return statusCode;
        }

        /**
         * Check if the mechanism did send a challenge.
         *

         * Some mechanisms do not send a challenge and just rely on the correct information to authenticate a user being
         * available in the request, in that case it would be normal for the mechanism to set this to false.
         *
         * @return true if a challenge was sent, false otherwise.
         */
        public boolean isChallengeSent() {
            return challengeSent;
        }

    }

}


text:
<?php

namespace Faker\Provider\tr_TR;

class PhoneNumber extends \Faker\Provider\PhoneNumber
{
    protected static $formats = array(
        '0##########',
        '05#########'
    );
}


text:
package eagle.jfaster.org.service;

/**
 * Created by fangyanpeng1 on 2017/8/9.
 */
public interface Calculate {

    int add(int a, int b);

    int sub(int a, int b);

    int div(int a, int b);
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>tclap: ValuesConstraint.h Source File</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">

Main Page | Namespace List | Class Hierarchy | Class List | Directories | File List | Namespace Members | Class Members | File Members

include / tclap

ValuesConstraint.h
Go to the documentation of this file.

00001
00002
00003
00022
00023 #ifndef TCLAP_VALUESCONSTRAINT_H
00024 #define TCLAP_VALUESCONSTRAINT_H
00025
00026 #include <string>
00027 #include <vector>
00028 #include <tclap/Constraint.h>
00029
00030 #ifdef HAVE_CONFIG_H
00031 #include <config.h>
00032 #else
00033 #define HAVE_SSTREAM
00034 #endif
00035
00036 #if defined(HAVE_SSTREAM)
00037 #include <sstream>
00038 #elif defined(HAVE_STRSTREAM)
00039 #include <strstream>
00040 #else
00041 #error "Need a stringstream (sstream or strstream) to compile!"
00042 #endif
00043
00044 namespace TCLAP {
00045
00050 template<class T>
00051 class ValuesConstraint : public Constraint<T>
00052 {
00053
00054     public:
00055
00060         ValuesConstraint(std::vector<T>& allowed);
00061
00065         virtual ~ValuesConstraint() {}
00066
00070         virtual std::string description() const;
00071
00075         virtual std::string shortID() const;
00076
00082         virtual bool check(const T& value) const;
00083
00084     protected:
00085
00089         std::vector<T> _allowed;
00090
00094         std::string _typeDesc;
00095
00096 };
00097
00098 template<class T>
00099 ValuesConstraint<T>::ValuesConstraint(std::vector<T>& allowed)
00100 : _allowed(allowed)
00101 {
00102     for ( unsigned int i = 0; i < _allowed.size(); i++ )
00103     {
00104
00105 #if defined(HAVE_SSTREAM)
00106         std::ostringstream os;
00107 #elif defined(HAVE_STRSTREAM)
00108         std::ostrstream os;
00109 #else
00110 #error "Need a stringstream (sstream or strstream) to compile!"
00111 #endif
00112
00113         os << _allowed[i];
00114
00115         std::string temp( os.str() );
00116
00117         if ( i > 0 )
00118             _typeDesc += "|";
00119         _typeDesc += temp;
00120     }
00121 }
00122
00123 template<class T>
00124 bool ValuesConstraint<T>::check( const T& val ) const
00125 {
00126     if ( std::find(_allowed.begin(),_allowed.end(),val) == _allowed.end() )
00127         return false;
00128     else
00129         return true;
00130 }
00131
00132 template<class T>
00133 std::string ValuesConstraint<T>::shortID() const
00134 {
00135     return _typeDesc;
00136 }
00137
00138 template<class T>
00139 std::string ValuesConstraint<T>::description() const
00140 {
00141     return _typeDesc;
00142 }
00143
00144
00145 } //namespace TCLAP
00146 #endif
00147

<address style="align: right;">Generated on Mon Sep 28 11:31:43 2009 for tclap by

 1.3.9.1 </address>


text: "${SRCROOT}/Pods/Target Support Files/Pods-YWTestInputField/Pods-YWTestInputField-resources.sh"


text:
class SessionController < ApplicationController
  def new
  end

  def create
    user = User.find_by(username: params[:session][:username])
    if user && user.authenticate(params[:session][:password])
      log_in(user)
    else
      flash[:danger] = "Invalid username/password combo"
      render 'new'
    end
  end

  def destroy
  end

end


text:
package com.facebook.buck.features.apple.projectV2;

import com.facebook.buck.apple.AppleBuildRules;
import com.facebook.buck.apple.AppleBuildRules.RecursiveDependenciesMode;
import com.facebook.buck.apple.AppleBundleDescriptionArg;
import com.facebook.buck.apple.AppleConfig;
import com.facebook.buck.apple.AppleDependenciesCache;
import com.facebook.buck.apple.AppleNativeTargetDescriptionArg;
import com.facebook.buck.apple.AppleTestDescriptionArg;
import com.facebook.buck.apple.XCodeDescriptions;
import com.facebook.buck.apple.xcode.XCScheme;
import com.facebook.buck.apple.xcode.xcodeproj.PBXProject;
import com.facebook.buck.apple.xcode.xcodeproj.PBXTarget;
import com.facebook.buck.apple.xcode.xcodeproj.ProductType;
import com.facebook.buck.apple.xcode.xcodeproj.ProductTypes;
import com.facebook.buck.core.cell.Cell;
import com.facebook.buck.core.description.arg.HasTests;
import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.Flavor;
import com.facebook.buck.core.model.targetgraph.TargetGraph;
import com.facebook.buck.core.model.targetgraph.TargetNode;
import com.facebook.buck.core.model.targetgraph.impl.TargetNodes;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.util.graph.TopologicalSort;
import com.facebook.buck.core.util.log.Logger;
import com.facebook.buck.cxx.config.CxxBuckConfig;
import com.facebook.buck.cxx.toolchain.CxxPlatform;
import com.facebook.buck.cxx.toolchain.HeaderMode;
import com.facebook.buck.event.BuckEventBus;
import com.facebook.buck.event.ConsoleEvent;
import com.facebook.buck.features.apple.common.CopyInXcode;
import com.facebook.buck.features.apple.common.SchemeActionType;
import com.facebook.buck.features.apple.common.WorkspaceMetadataWriter;
import com.facebook.buck.features.apple.common.XcodeWorkspaceConfigDescription;
import com.facebook.buck.features.apple.common.XcodeWorkspaceConfigDescriptionArg;
import com.facebook.buck.features.halide.HalideBuckConfig;
import com.facebook.buck.rules.keys.config.RuleKeyConfiguration;
import com.facebook.buck.swift.SwiftBuckConfig;
import com.facebook.buck.util.stream.RichStream;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class WorkspaceAndProjectGenerator {
  private static final Logger LOG = Logger.get(WorkspaceAndProjectGenerator.class);

  private final XCodeDescriptions xcodeDescriptions;
  private final Cell rootCell;
  private final TargetGraph projectGraph;
  private final AppleDependenciesCache dependenciesCache;
  private final ProjectGenerationStateCache projGenerationStateCache;
  private final XcodeWorkspaceConfigDescriptionArg workspaceArguments;
  private final BuildTarget workspaceBuildTarget;
  private final FocusedTargetMatcher focusedTargetMatcher; // @audited (chatatap)
  private final ProjectGeneratorOptions projectGeneratorOptions;
  private final boolean parallelizeBuild;
  private final CxxPlatform defaultCxxPlatform;
  private final ImmutableSet<Flavor> appleCxxFlavors;

  private Optional<ProjectGenerator> combinedProjectGenerator;
  private final Map<String, SchemeGenerator> schemeGenerators = new HashMap<>();
  private final String buildFileName;
  private final Function<TargetNode<?>, ActionGraphBuilder> graphBuilderForNode;
  private final BuckEventBus buckEventBus;
  private final RuleKeyConfiguration ruleKeyConfiguration;

  private final ImmutableSet.Builder<BuildTarget> requiredBuildTargetsBuilder =
      ImmutableSet.builder();
  private final ImmutableSortedSet.Builder<Path> xcconfigPathsBuilder =
      ImmutableSortedSet.naturalOrder();
  private final ImmutableList.Builder<CopyInXcode> filesToCopyInXcodeBuilder =
      ImmutableList.builder();
  private final HalideBuckConfig halideBuckConfig;
  private final CxxBuckConfig cxxBuckConfig;
  private final AppleConfig appleConfig;
  private final SwiftBuckConfig swiftBuckConfig;
  private final Optional<ImmutableMap<BuildTarget, TargetNode<?>>> sharedLibraryToBundle;

  /** The result of generating a workspace project. */
  public static class Result {
    private final Path workspacePath;
    private final PBXProject project;

    public Result(Path workspacePath, PBXProject project) {
      this.workspacePath = workspacePath;
      this.project = project;
    }

    public Path getWorkspacePath() {
      return this.workspacePath;
    }

    public PBXProject getProject() {
      return this.project;
    }
  }

  public WorkspaceAndProjectGenerator(
      XCodeDescriptions xcodeDescriptions,
      Cell cell,
      TargetGraph projectGraph,
      XcodeWorkspaceConfigDescriptionArg workspaceArguments,
      BuildTarget workspaceBuildTarget,
      ProjectGeneratorOptions projectGeneratorOptions,
      FocusedTargetMatcher focusedTargetMatcher,
      boolean parallelizeBuild,
      CxxPlatform defaultCxxPlatform,
      ImmutableSet<Flavor> appleCxxFlavors,
      String buildFileName,
      Function<TargetNode<?>, ActionGraphBuilder> graphBuilderForNode,
      BuckEventBus buckEventBus,
      RuleKeyConfiguration ruleKeyConfiguration,
      HalideBuckConfig halideBuckConfig,
      CxxBuckConfig cxxBuckConfig,
      AppleConfig appleConfig,
      SwiftBuckConfig swiftBuckConfig,
      Optional<ImmutableMap<BuildTarget, TargetNode<?>>> sharedLibraryToBundle) {
    this.xcodeDescriptions = xcodeDescriptions;
    this.rootCell = cell;
    this.projectGraph = projectGraph;
    this.dependenciesCache = new AppleDependenciesCache(projectGraph);
    this.ruleKeyConfiguration = ruleKeyConfiguration;
    this.projGenerationStateCache = new ProjectGenerationStateCache();
    this.workspaceArguments = workspaceArguments;
    this.workspaceBuildTarget = workspaceBuildTarget;
    this.projectGeneratorOptions = projectGeneratorOptions;
    this.parallelizeBuild = parallelizeBuild;
    this.defaultCxxPlatform = defaultCxxPlatform;
    this.appleCxxFlavors = appleCxxFlavors;
    this.buildFileName = buildFileName;
    this.graphBuilderForNode = graphBuilderForNode;
    this.buckEventBus = buckEventBus;
    this.swiftBuckConfig = swiftBuckConfig;
    this.combinedProjectGenerator = Optional.empty();
    this.halideBuckConfig = halideBuckConfig;
    this.cxxBuckConfig = cxxBuckConfig;
    this.appleConfig = appleConfig;
    this.sharedLibraryToBundle = sharedLibraryToBundle;

    this.focusedTargetMatcher = focusedTargetMatcher;
    // Add the workspace target to the focused target matcher.
    workspaceArguments
        .getSrcTarget()
        .ifPresent(buildTarget -> this.focusedTargetMatcher.addTarget(buildTarget));
  }

  @VisibleForTesting
  Optional<ProjectGenerator> getCombinedProjectGenerator() {
    return combinedProjectGenerator;
  }

  @VisibleForTesting
  Map<String, SchemeGenerator> getSchemeGenerators() {
    return schemeGenerators;
  }

  public ImmutableSet<BuildTarget> getRequiredBuildTargets() {
    return requiredBuildTargetsBuilder.build();
  }

  private ImmutableSet<Path> getXcconfigPaths() {
    return xcconfigPathsBuilder.build();
  }

  private ImmutableList<CopyInXcode> getFilesToCopyInXcode() {
    return filesToCopyInXcodeBuilder.build();
  }

  /**
   * Generates a workspace and all projects
   *
   * @return A result indicating the output of the generation
   * @throws IOException
   */
  public Result generateWorkspaceAndDependentProjects() throws IOException {
    LOG.debug("Generating workspace for target %s", workspaceBuildTarget);

    String workspaceName =
        XcodeWorkspaceConfigDescription.getWorkspaceNameFromArg(workspaceArguments);
    Path outputDirectory =
        workspaceBuildTarget
            .getCellRelativeBasePath()
            .getPath()
            .toPath(rootCell.getFilesystem().getFileSystem());

    WorkspaceGenerator workspaceGenerator =
        new WorkspaceGenerator(rootCell.getFilesystem(), workspaceName, outputDirectory);

    ImmutableMap.Builder<String, XcodeWorkspaceConfigDescriptionArg> schemeConfigsBuilder =
        ImmutableMap.builder();
    ImmutableSetMultimap.Builder<String, Optional<TargetNode<?>>> schemeNameToSrcTargetNodeBuilder =
        ImmutableSetMultimap.builder();
    ImmutableSetMultimap.Builder<String, TargetNode<?>> buildForTestNodesBuilder =
        ImmutableSetMultimap.builder();
    ImmutableSetMultimap.Builder<String, TargetNode<AppleTestDescriptionArg>> testsBuilder =
        ImmutableSetMultimap.builder();

    buildWorkspaceSchemes(
        projectGraph,
        projectGeneratorOptions.shouldIncludeTests(),
        projectGeneratorOptions.shouldIncludeDependenciesTests(),
        workspaceName,
        workspaceArguments,
        schemeConfigsBuilder,
        schemeNameToSrcTargetNodeBuilder,
        buildForTestNodesBuilder,
        testsBuilder);

    ImmutableMap<String, XcodeWorkspaceConfigDescriptionArg> schemeConfigs =
        schemeConfigsBuilder.build();
    ImmutableSetMultimap<String, Optional<TargetNode<?>>> schemeNameToSrcTargetNode =
        schemeNameToSrcTargetNodeBuilder.build();
    ImmutableSetMultimap<String, TargetNode<?>> buildForTestNodes =
        buildForTestNodesBuilder.build();
    ImmutableSetMultimap<String, TargetNode<AppleTestDescriptionArg>> tests = testsBuilder.build();

    ImmutableSet<BuildTarget> targetsInRequiredProjects =
        Stream.concat(
                schemeNameToSrcTargetNode.values().stream().flatMap(RichStream::from),
                buildForTestNodes.values().stream())
            .map(TargetNode::getBuildTarget)
            .collect(ImmutableSet.toImmutableSet());
    ImmutableMap.Builder<BuildTarget, PBXTarget> buildTargetToPbxTargetMapBuilder =
        ImmutableMap.builder();
    ImmutableMap.Builder<PBXTarget, Path> targetToProjectPathMapBuilder = ImmutableMap.builder();

    XcodeProjectWriteOptions xcodeProjectWriteOptions =
        XcodeProjectWriteOptions.of(new PBXProject(workspaceName), outputDirectory);

    generateProject(
        xcodeProjectWriteOptions,
        workspaceGenerator,
        targetsInRequiredProjects,
        buildTargetToPbxTargetMapBuilder,
        targetToProjectPathMapBuilder);

    writeWorkspaceMetaData(outputDirectory, workspaceName);

    ImmutableMap<BuildTarget, PBXTarget> buildTargetToPBXTarget =
        buildTargetToPbxTargetMapBuilder.build();
    ImmutableMap<PBXTarget, Path> targetToProjectPathMap = targetToProjectPathMapBuilder.build();

    ImmutableSetMultimap<String, PBXTarget> schemeBuildForTestNodeTargets =
        WorkspaceAndProjectGenerator.mapFromSchemeToPBXProject(
            buildForTestNodes, buildTargetToPBXTarget);
    ImmutableSetMultimap<String, PBXTarget> schemeUngroupedTestTargets =
        WorkspaceAndProjectGenerator.mapFromSchemeToPBXProject(tests, buildTargetToPBXTarget);

    LOG.debug("Generating schemes for all sub-projects.");

    writeWorkspaceSchemes(
        workspaceName,
        outputDirectory,
        schemeConfigs,
        schemeNameToSrcTargetNode,
        schemeBuildForTestNodeTargets,
        schemeUngroupedTestTargets,
        targetToProjectPathMap,
        buildTargetToPBXTarget);

    requiredBuildTargetsBuilder.addAll(getModularNodesToGenerate());

    Path workspacePath = workspaceGenerator.writeWorkspace();
    return new Result(workspacePath, xcodeProjectWriteOptions.project());
  }

  /**
   * Transform a map from scheme name to `TargetNode` to scheme name to the associated `PBXProject`.
   *
   * @param schemeToTargetNodes Map to transform.
   * @return Map of scheme name to associated `PXBProject`s.
   */
  private static ImmutableSetMultimap<String, PBXTarget> mapFromSchemeToPBXProject(
      ImmutableSetMultimap<String, ? extends TargetNode<?>> schemeToTargetNodes,
      ImmutableMap<BuildTarget, PBXTarget> buildTargetToPBXTarget) {
    ImmutableSetMultimap<String, PBXTarget> schemeToPBXProject =
        ImmutableSetMultimap.copyOf(
            schemeToTargetNodes.entries().stream()
                .map(
                    stringTargetNodeEntry ->
                        Maps.immutableEntry(
                            stringTargetNodeEntry.getKey(),
                            buildTargetToPBXTarget.get(
                                stringTargetNodeEntry.getValue().getBuildTarget())))
                .filter(
                    stringPBXTargetEntry -> {
                      return stringPBXTargetEntry.getValue() != null;
                    })
                .collect(Collectors.toList()));
    return schemeToPBXProject;
  }

  private void writeWorkspaceMetaData(Path outputDirectory, String workspaceName)
      throws IOException {

    WorkspaceMetadataWriter workspaceMetadataWriter =
        new WorkspaceMetadataWriter(
            "2",
            getRequiredBuildTargets(),
            getXcconfigPaths(),
            getFilesToCopyInXcode(),
            rootCell.getFilesystem());
    workspaceMetadataWriter.writeToWorkspaceAtPath(
        outputDirectory.resolve(workspaceName + ".xcworkspace"));
  }

  private void generateProject(
      XcodeProjectWriteOptions xcodeProjectWriteOptions,
      WorkspaceGenerator workspaceGenerator,
      ImmutableSet<BuildTarget> targetsInRequiredProjects,
      ImmutableMap.Builder<BuildTarget, PBXTarget> buildTargetToPbxTargetMapBuilder,
      ImmutableMap.Builder<PBXTarget, Path> targetToProjectPathMapBuilder)
      throws IOException {
    ImmutableSet.Builder<BuildTarget> buildTargets = ImmutableSet.builder();
    for (TargetNode<?> targetNode : projectGraph.getNodes()) {
      BuildTarget buildTarget = targetNode.getBuildTarget();
      if (focusedTargetMatcher.matches(targetNode.getBuildTarget())) {
        buildTargets.add(buildTarget);
      }
    }

    GenerationResult generationResult =
        generateProjectForDirectory(
            xcodeProjectWriteOptions, rootCell, buildTargets.build(), targetsInRequiredProjects);

    processGenerationResult(
        buildTargetToPbxTargetMapBuilder, targetToProjectPathMapBuilder, generationResult);
    workspaceGenerator.addFilePath(xcodeProjectWriteOptions.xcodeProjPath(), Optional.empty());
  }

  private void processGenerationResult(
      ImmutableMap.Builder<BuildTarget, PBXTarget> buildTargetToPbxTargetMapBuilder,
      ImmutableMap.Builder<PBXTarget, Path> targetToProjectPathMapBuilder,
      GenerationResult result) {
    requiredBuildTargetsBuilder.addAll(result.getRequiredBuildTargets());
    ImmutableSortedSet<Path> relativeXcconfigPaths =
        result.getXcconfigPaths().stream()
            .map((Path p) -> rootCell.getFilesystem().relativize(p))
            .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural()));
    xcconfigPathsBuilder.addAll(relativeXcconfigPaths);
    filesToCopyInXcodeBuilder.addAll(result.getFilesToCopyInXcode());
    buildTargetToPbxTargetMapBuilder.putAll(result.getBuildTargetToGeneratedTargetMap());
    for (PBXTarget target : result.getBuildTargetToGeneratedTargetMap().values()) {
      targetToProjectPathMapBuilder.put(target, result.getProjectPath());
    }
  }

  private GenerationResult generateProjectForDirectory(
      XcodeProjectWriteOptions xcodeProjectWriteOptions,
      Cell projectCell,
      ImmutableSet<BuildTarget> rules,
      ImmutableSet<BuildTarget> targetsInRequiredProjects)
      throws IOException {
    ProjectGenerator generator =
        new ProjectGenerator(
            xcodeDescriptions,
            projectGraph,
            dependenciesCache,
            projGenerationStateCache,
            rules,
            projectCell,
            buildFileName,
            xcodeProjectWriteOptions,
            projectGeneratorOptions,
            ruleKeyConfiguration,
            workspaceArguments.getSrcTarget().get(),
            targetsInRequiredProjects,
            defaultCxxPlatform,
            appleCxxFlavors,
            graphBuilderForNode,
            buckEventBus,
            halideBuckConfig,
            cxxBuckConfig,
            appleConfig,
            swiftBuckConfig,
            sharedLibraryToBundle);

    ProjectGenerator.Result result = generator.createXcodeProjects();

    ImmutableMap<BuildTarget, PBXTarget> buildTargetToGeneratedTargetMap =
        result.buildTargetsToGeneratedTargetMap;

    ImmutableSetMultimap.Builder<PBXProject, PBXTarget> targetMapBuilder =
        ImmutableSetMultimap.builder();
    targetMapBuilder.putAll(
        xcodeProjectWriteOptions.project(), buildTargetToGeneratedTargetMap.values());

    return GenerationResult.of(
        generator.getXcodeProjPath(),
        true,
        result.requiredBuildTargets,
        result.xcconfigPaths,
        ImmutableList.of(),
        buildTargetToGeneratedTargetMap,
        targetMapBuilder.build());
  }

  private void buildWorkspaceSchemes(
      TargetGraph projectGraph,
      boolean includeProjectTests,
      boolean includeDependenciesTests,
      String workspaceName,
      XcodeWorkspaceConfigDescriptionArg workspaceArguments,
      ImmutableMap.Builder<String, XcodeWorkspaceConfigDescriptionArg> schemeConfigsBuilder,
      ImmutableSetMultimap.Builder<String, Optional<TargetNode<?>>>
          schemeNameToSrcTargetNodeBuilder,
      ImmutableSetMultimap.Builder<String, TargetNode<?>> buildForTestNodesBuilder,
      ImmutableSetMultimap.Builder<String, TargetNode<AppleTestDescriptionArg>> testsBuilder) {
    ImmutableSetMultimap.Builder<String, TargetNode<AppleTestDescriptionArg>>
        extraTestNodesBuilder = ImmutableSetMultimap.builder();
    addWorkspaceScheme(
        xcodeDescriptions,
        projectGraph,
        dependenciesCache,
        workspaceName,
        workspaceArguments,
        schemeConfigsBuilder,
        schemeNameToSrcTargetNodeBuilder,
        extraTestNodesBuilder);
    addWorkspaceExtensionSchemes(
        projectGraph,
        workspaceName,
        workspaceArguments,
        schemeConfigsBuilder,
        schemeNameToSrcTargetNodeBuilder);
    addExtraWorkspaceSchemes(
        xcodeDescriptions,
        projectGraph,
        dependenciesCache,
        workspaceArguments.getExtraSchemes(),
        schemeConfigsBuilder,
        schemeNameToSrcTargetNodeBuilder,
        extraTestNodesBuilder);
    ImmutableSetMultimap<String, Optional<TargetNode<?>>> schemeNameToSrcTargetNode =
        schemeNameToSrcTargetNodeBuilder.build();
    ImmutableSetMultimap<String, TargetNode<AppleTestDescriptionArg>> extraTestNodes =
        extraTestNodesBuilder.build();

    buildWorkspaceSchemeTests(
        workspaceArguments.getSrcTarget(),
        projectGraph,
        includeProjectTests,
        includeDependenciesTests,
        schemeNameToSrcTargetNode,
        extraTestNodes,
        testsBuilder,
        buildForTestNodesBuilder);
  }

  private static void addWorkspaceScheme(
      XCodeDescriptions xcodeDescriptions,
      TargetGraph projectGraph,
      AppleDependenciesCache dependenciesCache,
      String schemeName,
      XcodeWorkspaceConfigDescriptionArg schemeArguments,
      ImmutableMap.Builder<String, XcodeWorkspaceConfigDescriptionArg> schemeConfigsBuilder,
      ImmutableSetMultimap.Builder<String, Optional<TargetNode<?>>>
          schemeNameToSrcTargetNodeBuilder,
      ImmutableSetMultimap.Builder<String, TargetNode<AppleTestDescriptionArg>>
          extraTestNodesBuilder) {
    LOG.debug("Adding scheme %s", schemeName);
    schemeConfigsBuilder.put(schemeName, schemeArguments);
    if (schemeArguments.getSrcTarget().isPresent()) {
      schemeNameToSrcTargetNodeBuilder.putAll(
          schemeName,
          Iterables.transform(
              AppleBuildRules.getSchemeBuildableTargetNodes(
                  xcodeDescriptions,
                  projectGraph,
                  Optional.of(dependenciesCache),
                  projectGraph.get(schemeArguments.getSrcTarget().get())),
              Optional::of));
    } else {
      schemeNameToSrcTargetNodeBuilder.put(
          XcodeWorkspaceConfigDescription.getWorkspaceNameFromArg(schemeArguments),
          Optional.empty());
    }

    for (BuildTarget extraTarget : schemeArguments.getExtraTargets()) {
      schemeNameToSrcTargetNodeBuilder.putAll(
          schemeName,
          Iterables.transform(
              AppleBuildRules.getSchemeBuildableTargetNodes(
                  xcodeDescriptions,
                  projectGraph,
                  Optional.of(dependenciesCache),
                  Objects.requireNonNull(projectGraph.get(extraTarget))),
              Optional::of));
    }

    for (BuildTarget extraShallowTarget : schemeArguments.getExtraShallowTargets()) {
      schemeNameToSrcTargetNodeBuilder.put(
          schemeName, Optional.of(projectGraph.get(extraShallowTarget)));
    }

    extraTestNodesBuilder.putAll(
        schemeName, getExtraTestTargetNodes(projectGraph, schemeArguments.getExtraTests()));
  }

  /**
   * Add a workspace scheme for each extension bundled with the source target of the workspace.
   *
   * @param projectGraph
   * @param schemeName
   * @param schemeArguments
   * @param schemeConfigsBuilder
   * @param schemeNameToSrcTargetNodeBuilder
   */
  private static void addWorkspaceExtensionSchemes(
      TargetGraph projectGraph,
      String schemeName,
      XcodeWorkspaceConfigDescriptionArg schemeArguments,
      ImmutableMap.Builder<String, XcodeWorkspaceConfigDescriptionArg> schemeConfigsBuilder,
      ImmutableSetMultimap.Builder<String, Optional<TargetNode<?>>>
          schemeNameToSrcTargetNodeBuilder) {
    if (!schemeArguments.getSrcTarget().isPresent()) {
      return;
    }

    LOG.debug("Potentially adding extension schemes for %s", schemeName);

    BuildTarget sourceBuildTarget = schemeArguments.getSrcTarget().get();
    TargetNode<?> sourceTargetNode = projectGraph.get(sourceBuildTarget);
    Set<BuildTarget> sourceTargetBuildDeps = sourceTargetNode.getBuildDeps();

    // Filter all of the source target's deps to find the bundled extensions that get an implicit
    // scheme.
    ImmutableSet<BuildTarget> implicitSchemeBuildTargets =
        sourceTargetBuildDeps.stream()
            .filter(t -> shouldIncludeImplicitExtensionSchemeForTargetNode(projectGraph.get(t)))
            .collect(ImmutableSet.toImmutableSet());

    // Create scheme for each bundled extension to allow Xcode to automatically begin debugging them
    // when this scheme it selected.
    implicitSchemeBuildTargets.forEach(
        (buildTarget -> {
          String extensionSchemeName = schemeName + "+" + buildTarget.getShortName();
          TargetNode<?> targetNode = projectGraph.get(buildTarget);

          schemeConfigsBuilder.put(
              extensionSchemeName, createImplicitExtensionWorkspaceArgs(buildTarget));

          schemeNameToSrcTargetNodeBuilder.put(extensionSchemeName, Optional.of(sourceTargetNode));
          schemeNameToSrcTargetNodeBuilder.put(extensionSchemeName, Optional.of(targetNode));
        }));
  }

  /**
   * @param targetNode `TargetNode` for potential implicit scheme.
   * @return True if implicit scheme should be included for `targetNode`, currently includes all app
   *     extensions to make debugging easier. Otherwise, false.
   */
  private static boolean shouldIncludeImplicitExtensionSchemeForTargetNode(
      TargetNode<?> targetNode) {
    // Bundle description required to determine product type for target node.
    if (!(targetNode.getConstructorArg() instanceof AppleBundleDescriptionArg)) {
      return false;
    }

    // Product type required to determine if product type matches.
    AppleBundleDescriptionArg bundleArg =
        (AppleBundleDescriptionArg) targetNode.getConstructorArg();
    if (!bundleArg.getXcodeProductType().isPresent()) {
      return false;
    }

    // Only create schemes for APP_EXTENSION.
    ProductType productType = ProductType.of(bundleArg.getXcodeProductType().get());
    return productType.equals(ProductTypes.APP_EXTENSION);
  }

  /**
   * @param sourceBuildTarget - The BuildTarget which will act as our fake workspace's `src_target`.
   * @return Workspace Args that describe a generic extension Xcode workspace containing
   *     `src_target` and one of its extensions.
   */
  private static XcodeWorkspaceConfigDescriptionArg createImplicitExtensionWorkspaceArgs(
      BuildTarget sourceBuildTarget) {
    return XcodeWorkspaceConfigDescriptionArg.builder()
        .setName("extension-dummy")
        .setSrcTarget(sourceBuildTarget)
        .setWasCreatedForAppExtension(true)
        .build();
  }

  private static void addExtraWorkspaceSchemes(
      XCodeDescriptions xcodeDescriptions,
      TargetGraph projectGraph,
      AppleDependenciesCache dependenciesCache,
      ImmutableSortedMap<String, BuildTarget> extraSchemes,
      ImmutableMap.Builder<String, XcodeWorkspaceConfigDescriptionArg> schemeConfigsBuilder,
      ImmutableSetMultimap.Builder<String, Optional<TargetNode<?>>>
          schemeNameToSrcTargetNodeBuilder,
      ImmutableSetMultimap.Builder<String, TargetNode<AppleTestDescriptionArg>>
          extraTestNodesBuilder) {
    for (Map.Entry<String, BuildTarget> extraSchemeEntry : extraSchemes.entrySet()) {
      BuildTarget extraSchemeTarget = extraSchemeEntry.getValue();
      Optional<TargetNode<?>> extraSchemeNode = projectGraph.getOptional(extraSchemeTarget);
      if (!extraSchemeNode.isPresent()
          || !(extraSchemeNode.get().getDescription() instanceof XcodeWorkspaceConfigDescription)) {
        throw new HumanReadableException(
            "Extra scheme target '%s' should be of type 'xcode_workspace_config'",
            extraSchemeTarget);
      }
      XcodeWorkspaceConfigDescriptionArg extraSchemeArg =
          (XcodeWorkspaceConfigDescriptionArg) extraSchemeNode.get().getConstructorArg();
      String schemeName = extraSchemeEntry.getKey();
      addWorkspaceScheme(
          xcodeDescriptions,
          projectGraph,
          dependenciesCache,
          schemeName,
          extraSchemeArg,
          schemeConfigsBuilder,
          schemeNameToSrcTargetNodeBuilder,
          extraTestNodesBuilder);
    }
  }

  /**
   * Find tests to run.
   *
   * @param targetGraph input target graph
   * @param includeProjectTests whether to include tests of nodes in the project
   * @param orderedTargetNodes target nodes for which to fetch tests for
   * @param extraTestBundleTargets extra tests to include
   * @return test targets that should be run.
   */
  private ImmutableSet<TargetNode<AppleTestDescriptionArg>> getOrderedTestNodes(
      Optional<BuildTarget> mainTarget,
      TargetGraph targetGraph,
      boolean includeProjectTests,
      boolean includeDependenciesTests,
      ImmutableSet<TargetNode<?>> orderedTargetNodes,
      ImmutableSet<TargetNode<AppleTestDescriptionArg>> extraTestBundleTargets) {
    LOG.debug("Getting ordered test target nodes for %s", orderedTargetNodes);
    ImmutableSet.Builder<TargetNode<AppleTestDescriptionArg>> testsBuilder = ImmutableSet.builder();
    if (includeProjectTests) {
      Optional<TargetNode<?>> mainTargetNode = Optional.empty();
      if (mainTarget.isPresent()) {
        mainTargetNode = targetGraph.getOptional(mainTarget.get());
      }
      for (TargetNode<?> node : orderedTargetNodes) {
        if (includeDependenciesTests
            || (mainTargetNode.isPresent() && node.equals(mainTargetNode.get()))) {
          if (!(node.getConstructorArg() instanceof HasTests)) {
            continue;
          }
          ImmutableList<BuildTarget> focusedTests =
              ((HasTests) node.getConstructorArg())
                  .getTests().stream()
                      .filter(t -> focusedTargetMatcher.matches(t))
                      .collect(ImmutableList.toImmutableList());
          // Show a warning if the target is not focused but the tests are.
          if (focusedTests.size() > 0 && !focusedTargetMatcher.matches(node.getBuildTarget())) {
            buckEventBus.post(
                ConsoleEvent.warning(
                    "Skipping tests of %s since it's not focused", node.getBuildTarget()));
            continue;
          }
          for (BuildTarget explicitTestTarget : focusedTests) {
            Optional<TargetNode<?>> explicitTestNode = targetGraph.getOptional(explicitTestTarget);
            if (explicitTestNode.isPresent()) {
              Optional<TargetNode<AppleTestDescriptionArg>> castedNode =
                  TargetNodes.castArg(explicitTestNode.get(), AppleTestDescriptionArg.class);
              if (castedNode.isPresent()) {
                testsBuilder.add(castedNode.get());
              } else {
                LOG.debug(
                    "Test target specified in '%s' is not a apple_test;"
                        + " not including in project: '%s'",
                    node.getBuildTarget(), explicitTestTarget);
              }
            } else {
              throw new HumanReadableException(
                  "Test target specified in '%s' is not in the target graph: '%s'",
                  node.getBuildTarget(), explicitTestTarget);
            }
          }
        }
      }
    }
    for (TargetNode<AppleTestDescriptionArg> extraTestTarget : extraTestBundleTargets) {
      testsBuilder.add(extraTestTarget);
    }
    return testsBuilder.build();
  }

  @SuppressWarnings("unchecked")
  private ImmutableSet<BuildTarget> getModularNodesToGenerate() {
    return projectGraph.getNodes().stream()
        .filter(
            modularNode ->
                modularNode.getConstructorArg() instanceof AppleNativeTargetDescriptionArg)
        .filter(NodeHelper::isModularAppleLibrary)
        .map(
            nativeTargetNode -> {
              TargetNode<AppleNativeTargetDescriptionArg> modularNode =
                  (TargetNode<AppleNativeTargetDescriptionArg>) nativeTargetNode;
              HeaderMode headerMode =
                  HeaderMode.forModuleMapMode(
                      modularNode
                          .getConstructorArg()
                          .getModulemapMode()
                          .orElse(appleConfig.moduleMapMode()));
              return NodeHelper.getModularMapTarget(modularNode, headerMode, defaultCxxPlatform);
            })
        .collect(ImmutableSet.toImmutableSet());
  }

  /**
   * Find transitive dependencies of inputs for building.
   *
   * @param projectGraph {@link TargetGraph} containing nodes
   * @param nodes Nodes to fetch dependencies for.
   * @param excludes Nodes to exclude from dependencies list.
   * @return targets and their dependencies that should be build.
   */
  private static ImmutableSet<TargetNode<?>> getTransitiveDepsAndInputs(
      XCodeDescriptions xcodeDescriptions,
      TargetGraph projectGraph,
      AppleDependenciesCache dependenciesCache,
      Iterable<? extends TargetNode<?>> nodes,
      ImmutableSet<TargetNode<?>> excludes) {
    return FluentIterable.from(nodes)
        .transformAndConcat(
            input ->
                AppleBuildRules.getRecursiveTargetNodeDependenciesOfTypes(
                    xcodeDescriptions,
                    projectGraph,
                    Optional.of(dependenciesCache),
                    RecursiveDependenciesMode.BUILDING,
                    input,
                    Optional.empty()))
        .append(nodes)
        .filter(
            input ->
                !excludes.contains(input)
                    && xcodeDescriptions.isXcodeDescription(input.getDescription()))
        .toSet();
  }

  private static ImmutableSet<TargetNode<AppleTestDescriptionArg>> getExtraTestTargetNodes(
      TargetGraph graph, Iterable<BuildTarget> targets) {
    ImmutableSet.Builder<TargetNode<AppleTestDescriptionArg>> builder = ImmutableSet.builder();
    for (TargetNode<?> node : graph.getAll(targets)) {
      Optional<TargetNode<AppleTestDescriptionArg>> castedNode =
          TargetNodes.castArg(node, AppleTestDescriptionArg.class);
      if (castedNode.isPresent()) {
        builder.add(castedNode.get());
      } else {
        throw new HumanReadableException(
            "Extra test target is not a test: '%s'", node.getBuildTarget());
      }
    }
    return builder.build();
  }

  private void buildWorkspaceSchemeTests(
      Optional<BuildTarget> mainTarget,
      TargetGraph projectGraph,
      boolean includeProjectTests,
      boolean includeDependenciesTests,
      ImmutableSetMultimap<String, Optional<TargetNode<?>>> schemeNameToSrcTargetNode,
      ImmutableSetMultimap<String, TargetNode<AppleTestDescriptionArg>> extraTestNodes,
      ImmutableSetMultimap.Builder<String, TargetNode<AppleTestDescriptionArg>>
          selectedTestsBuilder,
      ImmutableSetMultimap.Builder<String, TargetNode<?>> buildForTestNodesBuilder) {
    for (String schemeName : schemeNameToSrcTargetNode.keySet()) {
      ImmutableSet<TargetNode<?>> targetNodes =
          schemeNameToSrcTargetNode.get(schemeName).stream()
              .flatMap(RichStream::from)
              .collect(ImmutableSet.toImmutableSet());
      ImmutableSet<TargetNode<AppleTestDescriptionArg>> testNodes =
          getOrderedTestNodes(
              mainTarget,
              projectGraph,
              includeProjectTests,
              includeDependenciesTests,
              targetNodes,
              extraTestNodes.get(schemeName));
      selectedTestsBuilder.putAll(schemeName, testNodes);
      buildForTestNodesBuilder.putAll(
          schemeName,
          Iterables.filter(
              TopologicalSort.sort(projectGraph),
              getTransitiveDepsAndInputs(
                      xcodeDescriptions, projectGraph, dependenciesCache, testNodes, targetNodes)
                  ::contains));
    }
  }

  private void writeWorkspaceSchemes(
      String workspaceName,
      Path outputDirectory,
      ImmutableMap<String, XcodeWorkspaceConfigDescriptionArg> schemeConfigs,
      ImmutableSetMultimap<String, Optional<TargetNode<?>>> schemeNameToSrcTargetNode,
      ImmutableSetMultimap<String, PBXTarget> buildForTestTargets,
      ImmutableSetMultimap<String, PBXTarget> ungroupedTestTargets,
      ImmutableMap<PBXTarget, Path> targetToProjectPathMap,
      ImmutableMap<BuildTarget, PBXTarget> buildTargetToPBXTarget)
      throws IOException {
    for (Map.Entry<String, XcodeWorkspaceConfigDescriptionArg> schemeConfigEntry :
        schemeConfigs.entrySet()) {
      String schemeName = schemeConfigEntry.getKey();
      XcodeWorkspaceConfigDescriptionArg schemeConfigArg = schemeConfigEntry.getValue();
      if (schemeConfigArg.getSrcTarget().isPresent()
          && !focusedTargetMatcher.matches(schemeConfigArg.getSrcTarget().get())) {
        continue;
      }

      ImmutableSet<PBXTarget> orderedBuildTargets =
          schemeNameToSrcTargetNode.get(schemeName).stream()
              .distinct()
              .flatMap(RichStream::from)
              .map(TargetNode::getBuildTarget)
              .map(buildTargetToPBXTarget::get)
              .filter(Objects::nonNull)
              .collect(ImmutableSet.toImmutableSet());
      ImmutableSet<PBXTarget> orderedBuildTestTargets = buildForTestTargets.get(schemeName);
      ImmutableSet<PBXTarget> orderedRunTestTargets = ungroupedTestTargets.get(schemeName);

      Optional<String> runnablePath = schemeConfigArg.getExplicitRunnablePath();
      Optional<String> remoteRunnablePath;
      if (schemeConfigArg.getIsRemoteRunnable().orElse(false)) {
        // XXX TODO(beng): Figure out the actual name of the binary to launch
        remoteRunnablePath = Optional.of("/" + workspaceName);
      } else {
        remoteRunnablePath = Optional.empty();
      }

      Path schemeOutputDirectory = outputDirectory.resolve(workspaceName + ".xcworkspace");

      SchemeGenerator schemeGenerator =
          buildSchemeGenerator(
              targetToProjectPathMap,
              schemeOutputDirectory,
              schemeName,
              schemeConfigArg.getSrcTarget().map(buildTargetToPBXTarget::get),
              Optional.of(schemeConfigArg),
              orderedBuildTargets,
              orderedBuildTestTargets,
              orderedRunTestTargets,
              runnablePath,
              remoteRunnablePath);
      schemeGenerator.writeScheme();
      schemeGenerators.put(schemeName, schemeGenerator);
    }
  }

  private SchemeGenerator buildSchemeGenerator(
      ImmutableMap<PBXTarget, Path> targetToProjectPathMap,
      Path outputDirectory,
      String schemeName,
      Optional<PBXTarget> primaryTarget,
      Optional<XcodeWorkspaceConfigDescriptionArg> schemeConfigArg,
      ImmutableSet<PBXTarget> orderedBuildTargets,
      ImmutableSet<PBXTarget> orderedBuildTestTargets,
      ImmutableSet<PBXTarget> orderedRunTestTargets,
      Optional<String> runnablePath,
      Optional<String> remoteRunnablePath) {
    Optional<ImmutableMap<SchemeActionType, ImmutableMap<String, String>>> environmentVariables =
        Optional.empty();
    Optional<
            ImmutableMap<
                SchemeActionType, ImmutableMap<XCScheme.AdditionalActions, ImmutableList<String>>>>
        additionalSchemeActions = Optional.empty();
    XCScheme.LaunchAction.LaunchStyle launchStyle = XCScheme.LaunchAction.LaunchStyle.AUTO;
    Optional<XCScheme.LaunchAction.WatchInterface> watchInterface = Optional.empty();
    Optional<String> notificationPayloadFile = Optional.empty();
    Optional<Boolean> wasCreatedForAppExtension = Optional.empty();

    if (schemeConfigArg.isPresent()) {
      environmentVariables = schemeConfigArg.get().getEnvironmentVariables();
      additionalSchemeActions = schemeConfigArg.get().getAdditionalSchemeActions();
      launchStyle = schemeConfigArg.get().getLaunchStyle().orElse(launchStyle);
      watchInterface = schemeConfigArg.get().getWatchInterface();
      notificationPayloadFile = schemeConfigArg.get().getNotificationPayloadFile();
      wasCreatedForAppExtension = schemeConfigArg.get().getWasCreatedForAppExtension();
    }

    return new SchemeGenerator(
        rootCell.getFilesystem(),
        primaryTarget,
        orderedBuildTargets,
        orderedBuildTestTargets,
        orderedRunTestTargets,
        schemeName,
        outputDirectory,
        parallelizeBuild,
        wasCreatedForAppExtension,
        runnablePath,
        remoteRunnablePath,
        XcodeWorkspaceConfigDescription.getActionConfigNamesFromArg(workspaceArguments),
        targetToProjectPathMap,
        environmentVariables,
        additionalSchemeActions,
        launchStyle,
        watchInterface,
        notificationPayloadFile);
  }
}


text:
package org.kie.workbench.common.stunner.core.client.canvas.command;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.core.graph.Edge;
import org.kie.workbench.common.stunner.core.graph.Node;
import org.kie.workbench.common.stunner.core.graph.content.view.Connection;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.Silent.class)
public class SetConnectionSourceNodeCommandTest extends AbstractCanvasCommandTest {

    @Mock
    private Node node;
    @Mock
    private Edge edge;
    @Mock
    private Connection connection;

    private SetConnectionSourceNodeCommand tested;

    @Before
    @SuppressWarnings("unchecked")
    public void setUp() throws Exception {
        super.setUp();
        when(edge.getUUID()).thenReturn("e1");
        when(node.getUUID()).thenReturn("n1");
        this.tested = new SetConnectionSourceNodeCommand(node,
                                                         edge,
                                                         connection);
    }

    @Test
    public void testGetGraphCommand() {
        final org.kie.workbench.common.stunner.core.graph.command.impl.SetConnectionSourceNodeCommand graphCommand =
                (org.kie.workbench.common.stunner.core.graph.command.impl.SetConnectionSourceNodeCommand) tested.newGraphCommand(canvasHandler);
        assertNotNull(graphCommand);
        assertEquals(edge,
                     graphCommand.getEdge());
        assertEquals(node,
                     graphCommand.getSourceNode());
        assertEquals(connection,
                     graphCommand.getConnection());
    }

    @Test
    public void testGetCanvasCommand() {
        final SetCanvasConnectionCommand canvasCommand =
                (SetCanvasConnectionCommand) tested.newCanvasCommand(canvasHandler);
        assertNotNull(canvasCommand);
        assertEquals(edge,
                     canvasCommand.getEdge());
    }
}