Ejemplo n.º 1
0
  /**
   * Validates expected {@link org.terracotta.statistics.OperationStatistic} updates for the
   * indicated {@code Ehcache} instance. The statistics identified in {@code changed} are checked
   * for a value of {@code 1}; all other statistics in the same enumeration class are checked for a
   * value of {@code 0}.
   *
   * @param ehcache the {@code Ehcache} instance to check
   * @param changed the statistics values that should have updated values
   * @param <E> the statistics enumeration type
   */
  protected static <E extends Enum<E>> void validateStats(
      final Ehcache<?, ?> ehcache, final EnumSet<E> changed) {
    assert changed != null;
    final EnumSet<E> unchanged = EnumSet.complementOf(changed);

    @SuppressWarnings("unchecked")
    final List<EnumSet<E>> sets = Arrays.asList(changed, unchanged);
    Class<E> statsClass = null;
    for (final EnumSet<E> set : sets) {
      if (!set.isEmpty()) {
        statsClass = set.iterator().next().getDeclaringClass();
        break;
      }
    }
    assert statsClass != null;

    final OperationStatistic<E> operationStatistic = getOperationStatistic(ehcache, statsClass);
    for (final E statId : changed) {
      assertThat(
          String.format("Value for %s.%s", statId.getDeclaringClass().getName(), statId.name()),
          getStatistic(operationStatistic, statId),
          StatisticMatcher.equalTo(1L));
    }
    for (final E statId : unchanged) {
      assertThat(
          String.format("Value for %s.%s", statId.getDeclaringClass().getName(), statId.name()),
          getStatistic(operationStatistic, statId),
          StatisticMatcher.equalTo(0L));
    }
  }
  public void testHtmlDocumentWithRandomFields() throws Exception {
    // date is not present in the html doc
    ArrayList<AttachmentProcessor.Field> fieldsList =
        new ArrayList<>(EnumSet.complementOf(EnumSet.of(AttachmentProcessor.Field.DATE)));
    Set<AttachmentProcessor.Field> selectedFields = new HashSet<>();

    int numFields = randomIntBetween(1, fieldsList.size());
    String[] selectedFieldNames = new String[numFields];
    for (int i = 0; i < numFields; i++) {
      AttachmentProcessor.Field field;
      do {
        field = randomFrom(fieldsList);
      } while (selectedFields.add(field) == false);

      selectedFieldNames[i] = field.toLowerCase();
    }
    if (randomBoolean()) {
      selectedFields.add(AttachmentProcessor.Field.DATE);
    }
    processor =
        new AttachmentProcessor(
            randomAsciiOfLength(10), "source_field", "target_field", selectedFields, 10000);

    Map<String, Object> attachmentData = parseDocument("htmlWithEmptyDateMeta.html", processor);
    assertThat(attachmentData.keySet(), hasSize(selectedFieldNames.length));
    assertThat(attachmentData.keySet(), containsInAnyOrder(selectedFieldNames));
  }
Ejemplo n.º 3
0
  public ActMood mostSpecificGeneralization(CD that) {
    if (this == that || this.equals(that)) return this;
    if (!(that instanceof ActMood))
      throw new UnsupportedOperationException("cannot handle argument of class " + that.getClass());
    final ActMood thatActMood = (ActMood) that;

    // First build the intersection of the implied concepts
    // the remainder is a single path of which we have to
    // find the most specific concept, i.e., the one who
    // has all others as parents, i.e., the one with the
    // largest set of implied concepts.
    EnumSet<ActMood> intersection = EnumSet.copyOf(getImpliedConcepts());
    intersection.removeAll(EnumSet.complementOf(thatActMood.getImpliedConcepts()));
    intersection.remove(root);

    // XXX: this iterative search is likely to be least optimal because
    // we probably have to search the path from the root here.
    // I don't know of any better way to do it right now though.

    ActMood mostSpecificKnownGeneralization = root;
    int maxKnownSpecificity = 1;

    for (ActMood candidate : intersection) {
      int specificity = candidate.getImpliedConcepts().size();
      if (specificity > maxKnownSpecificity) {
        maxKnownSpecificity = specificity;
        mostSpecificKnownGeneralization = candidate;
      }
    }

    return mostSpecificKnownGeneralization;
  }
Ejemplo n.º 4
0
  public static Symbol findThird(Symbol first, Symbol second) {
    Symbol third = null;
    if (first.equals(second)) {
      third = first;

    } else {
      EnumSet<Symbol> twoShapes = EnumSet.of(first, second);
      third = (Symbol) EnumSet.complementOf(twoShapes).toArray()[0];
    }

    return third;
  }
Ejemplo n.º 5
0
 public void tickStart(EnumSet<TickType> ticks, Object... data) {
   sidedDelegate.profileStart("modTickStart$" + ticks);
   for (ITickHandler ticker : tickHandlers) {
     EnumSet<TickType> ticksToRun = EnumSet.copyOf(ticker.ticks());
     ticksToRun.removeAll(EnumSet.complementOf(ticks));
     if (!ticksToRun.isEmpty()) {
       sidedDelegate.profileStart(ticker.getLabel());
       ticker.tickStart(ticksToRun, data);
       sidedDelegate.profileEnd();
     }
   }
   sidedDelegate.profileEnd();
 }
Ejemplo n.º 6
0
  static {
    Relation.aRelationSet = EnumSet.range(Relation.EXPLICITLY_CALLS, Relation.REFERENCES);
    Relation.tRelationSet = EnumSet.complementOf(Relation.aRelationSet);
    // cRelationSet = EnumSet.range(Relation.T_EXPLICITLY_CALLS, Relation.T_REFERENCES);

    Relation.aRelationMap = new EnumMap<Type, Relation>(Type.class);
    Relation.tRelationMap = new EnumMap<Type, Relation>(Type.class);

    for (final Relation lRelation : Relation.aRelationSet)
      Relation.aRelationMap.put(lRelation.getType(), lRelation);
    for (final Relation lTransRelation : Relation.tRelationSet)
      Relation.tRelationMap.put(lTransRelation.getType(), lTransRelation);
  }
Ejemplo n.º 7
0
 public void write(Kryo kryo, Output output, EnumSet object) {
   Serializer serializer;
   if (object.isEmpty()) {
     EnumSet tmp = EnumSet.complementOf(object);
     if (tmp.isEmpty())
       throw new KryoException("An EnumSet must have a defined Enum to be serialized.");
     serializer = kryo.writeClass(output, tmp.iterator().next().getClass()).getSerializer();
   } else {
     serializer = kryo.writeClass(output, object.iterator().next().getClass()).getSerializer();
   }
   output.writeInt(object.size(), true);
   for (Object element : object) serializer.write(kryo, output, element);
 }
Ejemplo n.º 8
0
  public void tickStart(EnumSet<TickType> ticks, Side side, Object... data) {
    List<IScheduledTickHandler> scheduledTicks =
        side.isClient() ? scheduledClientTicks : scheduledServerTicks;

    if (scheduledTicks.size() == 0) {
      return;
    }
    for (IScheduledTickHandler ticker : scheduledTicks) {
      EnumSet<TickType> ticksToRun =
          EnumSet.copyOf(Objects.firstNonNull(ticker.ticks(), EnumSet.noneOf(TickType.class)));
      ticksToRun.removeAll(EnumSet.complementOf(ticks));
      if (!ticksToRun.isEmpty()) {
        ticker.tickStart(ticksToRun, data);
      }
    }
  }
Ejemplo n.º 9
0
 @Test
 public void testMarkLog_EnsureLogLevel() {
   for (LoggerLevel level : EnumSet.complementOf(EnumSet.of(LoggerLevel.DEFAULT))) {
     reset(logManager);
     when(logManager.getLoggerEffectiveLevel(LOG_NAME)).thenReturn(level);
     logMarker.markLog("test");
     try {
       if (EnumSet.of(LoggerLevel.OFF, LoggerLevel.ERROR, LoggerLevel.WARN).contains(level)) {
         verify(logManager).setLoggerLevel(LOG_NAME, LoggerLevel.INFO);
       } else {
         verify(logManager, never()).setLoggerLevel(anyObject(), anyObject());
       }
     } catch (AssertionError e) {
       throw new AssertionError("Mishandled log level " + level, e);
     }
   }
 }
 @Override
 public void writeObject(
     FSTObjectOutput out,
     Object toWrite,
     FSTClazzInfo clzInfo,
     FSTClazzInfo.FSTFieldInfo referencedBy,
     int streamPosition)
     throws IOException {
   EnumSet enset = (EnumSet) toWrite;
   int count = 0;
   out.writeInt(enset.size());
   if (enset.isEmpty()) { // WTF only way to determine enumtype ..
     EnumSet compl = EnumSet.complementOf(enset);
     out.writeClassTag(compl.iterator().next().getClass());
   } else {
     for (Object element : enset) {
       if (count == 0) {
         out.writeStringUTF(element.getClass().getName());
       }
       out.writeStringUTF(element.toString());
       count++;
     }
   }
 }
  @Override
  public JsonNode digest(final JsonNode schema) {
    final ObjectNode ret = FACTORY.objectNode();
    final ArrayNode simpleTypes = FACTORY.arrayNode();
    ret.put(keyword, simpleTypes);
    final ArrayNode schemas = FACTORY.arrayNode();
    ret.put("schemas", schemas);

    final JsonNode node = schema.get(keyword);

    final EnumSet<NodeType> set = EnumSet.noneOf(NodeType.class);

    if (node.isTextual()) // Single type
    putType(set, node.textValue());
    else { // More than one type, and possibly schemas
      final int size = node.size();
      JsonNode element;
      for (int index = 0; index < size; index++) {
        element = node.get(index);
        if (element.isTextual()) putType(set, element.textValue());
        else schemas.add(index);
      }
    }

    /*
     * If all types are there, no need to collect schemas
     */
    if (EnumSet.complementOf(set).isEmpty()) schemas.removeAll();

    /*
     * Note that as this is an enumset, order is guaranteed
     */
    for (final NodeType type : set) simpleTypes.add(type.toString());

    return ret;
  }
Ejemplo n.º 12
0
/**
 * Enumerates the possible types of {@link SqlNode}.
 *
 * <p>The values are immutable, canonical constants, so you can use Kinds to find particular types
 * of expressions quickly. To identity a call to a common operator such as '=', use {@link
 * org.eigenbase.sql.SqlNode#isA}:
 *
 * <blockquote>
 *
 * <pre>exp.{@link org.eigenbase.sql.SqlNode#isA isA}({@link #EQUALS})</pre>
 *
 * </blockquote>
 *
 * <p>Only commonly-used nodes have their own type; other nodes are of type {@link #OTHER}. Some of
 * the values, such as {@link #SET_QUERY}, represent aggregates.
 *
 * <p>To identify a category of expressions, you can use {@link org.eigenbase.sql.SqlNode#isA} with
 * an aggregate SqlKind. The following expression will return <code>true</code> for calls to '=' and
 * '&gt;=', but <code>false</code> for the constant '5', or a call to '+':
 *
 * <blockquote>
 *
 * <pre>exp.{@link org.eigenbase.sql.SqlNode#isA isA}({@link #COMPARISON SqlKind.Comparison})</pre>
 *
 * </blockquote>
 *
 * To quickly choose between a number of options, use a switch statement:
 *
 * <blockquote>
 *
 * <pre>switch (exp.getKind()) {
 * case {@link #EQUALS}:
 *     ...;
 * case {@link #NOT_EQUALS}:
 *     ...;
 * default:
 *     throw {@link org.eigenbase.util.Util#unexpected Util.unexpected}(exp.getKind());
 * }</pre>
 *
 * </blockquote>
 *
 * @author jhyde
 * @version $Id$
 * @since Dec 12, 2003
 */
public enum SqlKind {
  // ~ Static fields/initializers ---------------------------------------------

  // the basics

  /**
   * Expression not covered by any other {@link SqlKind} value.
   *
   * @see #OTHER_FUNCTION
   */
  OTHER,

  /** SELECT statement or sub-query. */
  SELECT,

  /**
   * JOIN operator or compound FROM clause.
   *
   * <p>A FROM clause with more than one table is represented as if it were a join. For example,
   * "FROM x, y, z" is represented as "JOIN(x, JOIN(x, y))".
   */
  JOIN,

  /** Identifier */
  IDENTIFIER,

  /** A literal. */
  LITERAL,

  /**
   * Function that is not a special function.
   *
   * @see #FUNCTION
   */
  OTHER_FUNCTION,

  /** EXPLAIN statement */
  EXPLAIN,

  /** INSERT statement */
  INSERT,

  /** DELETE statement */
  DELETE,

  /** UPDATE statement */
  UPDATE,

  /** A dynamic parameter. */
  DYNAMIC_PARAM,

  /**
   * ORDER BY clause.
   *
   * @see #DESCENDING
   * @see #NULLS_FIRST
   * @see #NULLS_LAST
   */
  ORDER_BY,

  /** Union */
  UNION,

  /** Except */
  EXCEPT,

  /** Intersect */
  INTERSECT,

  /** AS operator */
  AS,

  /** OVER operator */
  OVER,

  /** Window specification */
  WINDOW,

  /** MERGE statement */
  MERGE,

  /** TABLESAMPLE operator */
  TABLESAMPLE,

  // binary operators

  /** The arithmetic multiplication operator, "*". */
  TIMES,

  /** The arithmetic division operator, "/". */
  DIVIDE,

  /**
   * The arithmetic plus operator, "+".
   *
   * @see #PLUS_PREFIX
   */
  PLUS,

  /**
   * The arithmetic minus operator, "-".
   *
   * @see #MINUS_PREFIX
   */
  MINUS,

  // comparison operators

  /** The "IN" operator. */
  IN,

  /** The less-than operator, "&lt;". */
  LESS_THAN,

  /** The greater-than operator, "&gt;". */
  GREATER_THAN,

  /** The less-than-or-equal operator, "&lt;=". */
  LESS_THAN_OR_EQUAL,

  /** The greater-than-or-equal operator, "&gt;=". */
  GREATER_THAN_OR_EQUAL,

  /** The equals operator, "=". */
  EQUALS,

  /** The not-equals operator, "&#33;=" or "&lt;&gt;". */
  NOT_EQUALS,

  /** The is-distinct-from operator. */
  IS_DISTINCT_FROM,

  /** The is-not-distinct-from operator. */
  IS_NOT_DISTINCT_FROM,

  /** The logical "OR" operator. */
  OR,

  /** The logical "AND" operator. */
  AND,

  // other infix

  /** Dot */
  DOT,

  /** The "OVERLAPS" operator. */
  OVERLAPS,

  /** The "LIKE" operator. */
  LIKE,

  /** The "SIMILAR" operator. */
  SIMILAR,

  /** The "BETWEEN" operator. */
  BETWEEN,

  /** A "CASE" expression. */
  CASE,

  // prefix operators

  /** The logical "NOT" operator. */
  NOT,

  /**
   * The unary plus operator, as in "+1".
   *
   * @see #PLUS
   */
  PLUS_PREFIX,

  /**
   * The unary minus operator, as in "-1".
   *
   * @see #MINUS
   */
  MINUS_PREFIX,

  /** The "EXISTS" operator. */
  EXISTS,

  /** The "VALUES" operator. */
  VALUES,

  /**
   * Explicit table, e.g. <code>select * from (TABLE t)</code> or <code>TABLE
   * t</code>. See also {@link #COLLECTION_TABLE}.
   */
  EXPLICIT_TABLE,

  /**
   * Scalar query; that is, a subquery used in an expression context, and returning one row and one
   * column.
   */
  SCALAR_QUERY,

  /** ProcedureCall */
  PROCEDURE_CALL,

  /** NewSpecification */
  NEW_SPECIFICATION,

  // postfix operators

  /** DESC in ORDER BY. A parse tree, not a true expression. */
  DESCENDING,

  /** NULLS FIRST clause in ORDER BY. A parse tree, not a true expression. */
  NULLS_FIRST,

  /** NULLS LAST clause in ORDER BY. A parse tree, not a true expression. */
  NULLS_LAST,

  /** The "IS TRUE" operator. */
  IS_TRUE,

  /** The "IS FALSE" operator. */
  IS_FALSE,

  /** The "IS UNKNOWN" operator. */
  IS_UNKNOWN,

  /** The "IS NULL" operator. */
  IS_NULL,

  /** The "PRECEDING" qualifier of an interval end-point in a window specification. */
  PRECEDING,

  /** The "FOLLOWING" qualifier of an interval end-point in a window specification. */
  FOLLOWING,

  /**
   * The field access operator, ".".
   *
   * <p>(Only used at the RexNode level; at SqlNode level, a field-access is part of an identifier.)
   */
  FIELD_ACCESS,

  /**
   * Reference to an input field.
   *
   * <p>(Only used at the RexNode level.)
   */
  INPUT_REF,

  /**
   * Reference to a sub-expression computed within the current relational operator.
   *
   * <p>(Only used at the RexNode level.)
   */
  LOCAL_REF,

  /**
   * Reference to correlation variable.
   *
   * <p>(Only used at the RexNode level.)
   */
  CORREL_VARIABLE,

  // functions

  /** The row-constructor function. May be explicit or implicit: {@code VALUES 1, ROW (2)}. */
  ROW,

  /**
   * The non-standard constructor used to pass a COLUMN_LIST parameter to a user-defined transform.
   */
  COLUMN_LIST,

  /** The "CAST" operator. */
  CAST,

  /** The "TRIM" function. */
  TRIM,

  /** Call to a function using JDBC function syntax. */
  JDBC_FN,

  /** The MULTISET value constructor. */
  MULTISET_VALUE_CONSTRUCTOR,

  /** The MULTISET query constructor. */
  MULTISET_QUERY_CONSTRUCTOR,

  /** The "UNNEST" operator. */
  UNNEST,

  /** The "LATERAL" qualifier to relations in the FROM clause. */
  LATERAL,

  /**
   * Table operator which converts user-defined transform into a relation, for example, <code>
   * select * from TABLE(udx(x, y, z))</code>. See also the {@link #EXPLICIT_TABLE} prefix operator.
   */
  COLLECTION_TABLE,

  /** Array Value Constructor, e.g. {@code Array[1, 2, 3]}. */
  ARRAY_VALUE_CONSTRUCTOR,

  /** Array Query Constructor, e.g. {@code Array(select deptno from dept)}. */
  ARRAY_QUERY_CONSTRUCTOR,

  /** Map Value Constructor, e.g. {@code Map['washington', 1, 'obama', 44]}. */
  MAP_VALUE_CONSTRUCTOR,

  /** Map Query Constructor, e.g. {@code MAP (SELECT empno, deptno FROM emp)}. */
  MAP_QUERY_CONSTRUCTOR,

  /**
   * CURSOR constructor, for example, <code>select * from
   * TABLE(udx(CURSOR(select ...), x, y, z))</code>
   */
  CURSOR,

  // internal operators (evaluated in validator) 200-299

  /**
   * Literal chain operator (for composite string literals). An internal operator that does not
   * appear in SQL syntax.
   */
  LITERAL_CHAIN,

  /**
   * Escape operator (always part of LIKE or SIMILAR TO expression). An internal operator that does
   * not appear in SQL syntax.
   */
  ESCAPE,

  /**
   * The internal REINTERPRET operator (meaning a reinterpret cast). An internal operator that does
   * not appear in SQL syntax.
   */
  REINTERPRET;

  // ~ Static fields/initializers ---------------------------------------------

  // Most of the static fields are categories, aggregating several kinds into
  // a set.

  /**
   * Category consisting of set-query node types.
   *
   * <p>Consists of: {@link #EXCEPT}, {@link #INTERSECT}, {@link #UNION}.
   */
  public static final EnumSet<SqlKind> SET_QUERY = EnumSet.of(UNION, INTERSECT, EXCEPT);

  /**
   * Category consisting of all expression operators.
   *
   * <p>A node is an expression if it is NOT one of the following: {@link #AS}, {@link #DESCENDING},
   * {@link #SELECT}, {@link #JOIN}, {@link #OTHER_FUNCTION}, {@link #CAST}, {@link #TRIM}, {@link
   * #LITERAL_CHAIN}, {@link #JDBC_FN}, {@link #PRECEDING}, {@link #FOLLOWING}, {@link #ORDER_BY},
   * {@link #COLLECTION_TABLE}, {@link #TABLESAMPLE}.
   */
  public static final Set<SqlKind> EXPRESSION =
      EnumSet.complementOf(
          EnumSet.of(
              AS,
              DESCENDING,
              SELECT,
              JOIN,
              OTHER_FUNCTION,
              CAST,
              TRIM,
              LITERAL_CHAIN,
              JDBC_FN,
              PRECEDING,
              FOLLOWING,
              ORDER_BY,
              NULLS_FIRST,
              NULLS_LAST,
              COLLECTION_TABLE,
              TABLESAMPLE));

  /**
   * Category consisting of all DML operators.
   *
   * <p>Consists of: {@link #INSERT}, {@link #UPDATE}, {@link #DELETE}, {@link #MERGE}, {@link
   * #PROCEDURE_CALL}.
   *
   * <p>NOTE jvs 1-June-2006: For now we treat procedure calls as DML; this makes it easy for JDBC
   * clients to call execute or executeUpdate and not have to process dummy cursor results. If in
   * the future we support procedures which return results sets, we'll need to refine this.
   */
  public static final EnumSet<SqlKind> DML =
      EnumSet.of(INSERT, DELETE, UPDATE, MERGE, PROCEDURE_CALL);

  /**
   * Category consisting of query node types.
   *
   * <p>Consists of: {@link #SELECT}, {@link #EXCEPT}, {@link #INTERSECT}, {@link #UNION}, {@link
   * #VALUES}, {@link #ORDER_BY}, {@link #EXPLICIT_TABLE}.
   */
  public static final EnumSet<SqlKind> QUERY =
      EnumSet.of(SELECT, UNION, INTERSECT, EXCEPT, VALUES, ORDER_BY, EXPLICIT_TABLE);

  /**
   * Category of all SQL statement types.
   *
   * <p>Consists of all types in {@link #QUERY} and {@link #DML}.
   */
  public static final Set<SqlKind> TOP_LEVEL;

  static {
    TOP_LEVEL = EnumSet.copyOf(QUERY);
    TOP_LEVEL.addAll(DML);
  }

  /**
   * Category consisting of regular and special functions.
   *
   * <p>Consists of regular functions {@link #OTHER_FUNCTION} and special functions {@link #ROW},
   * {@link #TRIM}, {@link #CAST}, {@link #JDBC_FN}.
   */
  public static final Set<SqlKind> FUNCTION = EnumSet.of(OTHER_FUNCTION, ROW, TRIM, CAST, JDBC_FN);

  /**
   * Category of comparison operators.
   *
   * <p>Consists of: {@link #IN}, {@link #EQUALS}, {@link #NOT_EQUALS}, {@link #LESS_THAN}, {@link
   * #GREATER_THAN}, {@link #LESS_THAN_OR_EQUAL}, {@link #GREATER_THAN_OR_EQUAL}.
   */
  public static final Set<SqlKind> COMPARISON =
      EnumSet.of(
          IN,
          EQUALS,
          NOT_EQUALS,
          LESS_THAN,
          GREATER_THAN,
          GREATER_THAN_OR_EQUAL,
          LESS_THAN_OR_EQUAL);

  /**
   * Returns whether this {@code SqlKind} belongs to a given category.
   *
   * <p>A category is a collection of kinds, not necessarily disjoint. For example, QUERY is {
   * SELECT, UNION, INTERSECT, EXCEPT, VALUES, ORDER_BY, EXPLICIT_TABLE }.
   *
   * @param category Category
   * @return Whether this kind belongs to the given category
   */
  public final boolean belongsTo(Collection<SqlKind> category) {
    return category.contains(this);
  }
}
/**
 * An enumeration of the supported domain model namespaces.
 *
 * @author <a href="mailto:[email protected]">David M. Lloyd</a>
 */
public enum Namespace {
  // must be first
  UNKNOWN(null),
  NONE(null),

  // predefined standard
  XML_SCHEMA_INSTANCE("http://www.w3.org/2001/XMLSchema-instance"),

  // configuration versions, oldest to newest
  INFINISPAN_5_0("urn:infinispan:config:5.0"),
  INFINISPAN_5_1("urn:infinispan:config:5.1"),
  INFINISPAN_5_2("urn:infinispan:config:5.2");

  /** The current namespace version. */
  public static final Namespace CURRENT = INFINISPAN_5_2;

  private static final Namespace[] SUPPORTED_NAMESPACES =
      new Namespace[] {INFINISPAN_5_2, INFINISPAN_5_1, INFINISPAN_5_0, NONE};

  public boolean isSupported() {
    for (Namespace ns : SUPPORTED_NAMESPACES) if (this == ns) return true;
    return false;
  }

  private final String name;

  Namespace(final String name) {
    this.name = name;
  }

  /**
   * Get the URI of this namespace.
   *
   * @return the URI
   */
  public String getUriString() {
    return name;
  }

  /** Set of all namespaces, excluding the special {@link #UNKNOWN} value. */
  public static final EnumSet<Namespace> STANDARD_NAMESPACES =
      EnumSet.complementOf(EnumSet.of(UNKNOWN, XML_SCHEMA_INSTANCE));

  private static final Map<String, Namespace> MAP;

  static {
    final Map<String, Namespace> map = new HashMap<String, Namespace>();
    for (Namespace namespace : values()) {
      final String name = namespace.getUriString();
      if (name != null) map.put(name, namespace);
    }
    MAP = map;
  }

  public static Namespace forUri(String uri) {
    // FIXME when STXM-8 is done, remove the null check
    if (uri == null || XMLConstants.NULL_NS_URI.equals(uri)) return NONE;
    final Namespace element = MAP.get(uri);
    return element == null ? UNKNOWN : element;
  }
}
Ejemplo n.º 14
0
  @Override
  public boolean execute(CommandSender sender, String[] parameters) {
    if (!XWarp.permissions.permission(sender, PermissionTypes.CMD_LIST)) {
      sender.sendMessage(ChatColor.RED + "You have no permission to list warps.");
      return true;
    }

    // Special case
    if (parameters.length == 2 && parameters[1].equalsIgnoreCase("legend")) {
      if (!(sender instanceof Player)) {
        sender.sendMessage("Maybe no colors here, so this command could be useless here!");
      }
      for (String line : GenericLister.getLegend()) {
        sender.sendMessage(line);
      }
    } else {
      // Parse values here
      /*
       * c:<creator>
       * oc:<offline creator (won't be expanded)>
       * w:<world>
       * o:<owner>
       * oo:<offline owner (won't be expanded)>
       * v:<visibility>
       */

      // Whitelist
      Set<String> creators = new HashSet<String>();
      Set<String> owners = new HashSet<String>();
      Set<String> worlds = new HashSet<String>();
      Set<Visibility> visibilites = new HashSet<Visibility>();

      // Blacklist
      /* not implemented yet */

      // Column blacklist
      EnumSet<Column> blackColumns = EnumSet.noneOf(Column.class);

      Integer page = null; // Default page = 1
      // 0 = list/ls
      for (int i = 1; i < parameters.length; i++) {
        if (parameters[i].startsWith("c:")) {
          add(
              sender,
              creators,
              MinecraftUtil.expandName(parameters[i].substring(2), this.server).toLowerCase());
        } else if (parameters[i].startsWith("oc:")) {
          add(sender, creators, parameters[i].substring(2).toLowerCase());
        } else if (parameters[i].startsWith("w:")) {
          add(sender, worlds, parameters[i].substring(2).toLowerCase());
        } else if (parameters[i].startsWith("o:")) {
          add(
              sender,
              owners,
              MinecraftUtil.expandName(parameters[i].substring(2), this.server).toLowerCase());
        } else if (parameters[i].startsWith("oo:")) {
          add(sender, owners, parameters[i].substring(2).toLowerCase());
        } else if (parameters[i].startsWith("v:")) {
          Visibility v = Visibility.parseString(parameters[i].substring(2));
          if (v != null) {
            add(sender, visibilites, v);
          } else {
            sender.sendMessage(
                ChatColor.RED
                    + "Inputed an invalid visibility value: "
                    + parameters[i].substring(2));
          }
        } else if (parameters[i].startsWith("-col:")) {
          if (parameters[i].equalsIgnoreCase("-col:owner")) {
            add(sender, blackColumns, Column.OWNER);
          } else if (parameters[i].equalsIgnoreCase("-col:world")) {
            add(sender, blackColumns, Column.WORLD);
          } else if (parameters[i].equalsIgnoreCase("-col:loc")) {
            add(sender, blackColumns, Column.LOCATION);
          } else {
            sender.sendMessage(ChatColor.RED + "Unknown column: " + parameters[i].substring(5));
          }
        } else {
          Integer buffer = MinecraftUtil.tryAndGetInteger(parameters[i]);
          if (buffer != null) {
            if (page == null) {
              page = buffer;
            } else {
              sender.sendMessage(
                  ChatColor.RED
                      + "Found more than one page definition. Selecting first: "
                      + buffer);
            }
          } else {
            sender.sendMessage(ChatColor.RED + "Unknown parameter prefix: " + parameters[i]);
          }
        }
      }

      if (page == null) {
        page = 1;
      }

      final List<Warp> warps = this.manager.getWarps(sender, creators, owners, worlds, visibilites);

      final int maxPages = getNumberOfPages(warps.size(), sender);
      final int numLines = MinecraftUtil.getMaximumLines(sender) - 1;

      final ListSection section = new ListSection("", numLines);

      if (maxPages < 1) {
        sender.sendMessage(ChatColor.RED + "There are no warps to list");
      } else if (page < 1) {
        sender.sendMessage(ChatColor.RED + "Page number can't be below 1.");
      } else if (page > maxPages) {
        sender.sendMessage(ChatColor.RED + "There are only " + maxPages + " pages of warps");
      } else {
        // Get only those warps one the page
        final int offset = (page - 1) * numLines;
        final int lines = Math.min(warps.size() - offset, numLines);
        List<Warp> pageWarps = warps.subList(offset, offset + lines);

        section.addWarps(pageWarps);

        GenericLister.listPage(page, maxPages, sender, EnumSet.complementOf(blackColumns), section);
      }
    }
    return true;
  }
Ejemplo n.º 15
0
  @Test
  public void testAllFlags() throws Exception {
    // rely on 1 replica for this tests
    createIndex("test1");
    createIndex("test2");

    ClusterHealthResponse clusterHealthResponse =
        client()
            .admin()
            .cluster()
            .prepareHealth()
            .setWaitForEvents(Priority.LANGUID)
            .setWaitForGreenStatus()
            .execute()
            .actionGet();
    assertThat(clusterHealthResponse.isTimedOut(), equalTo(false));

    client()
        .prepareIndex("test1", "type1", Integer.toString(1))
        .setSource("field", "value")
        .execute()
        .actionGet();
    client()
        .prepareIndex("test1", "type2", Integer.toString(1))
        .setSource("field", "value")
        .execute()
        .actionGet();
    client()
        .prepareIndex("test2", "type", Integer.toString(1))
        .setSource("field", "value")
        .execute()
        .actionGet();

    client().admin().indices().prepareRefresh().execute().actionGet();
    IndicesStatsRequestBuilder builder = client().admin().indices().prepareStats();
    Flag[] values = CommonStatsFlags.Flag.values();
    for (Flag flag : values) {
      set(flag, builder, false);
    }

    IndicesStatsResponse stats = builder.execute().actionGet();
    for (Flag flag : values) {
      assertThat(isSet(flag, stats.getPrimaries()), equalTo(false));
      assertThat(isSet(flag, stats.getTotal()), equalTo(false));
    }

    for (Flag flag : values) {
      set(flag, builder, true);
    }
    stats = builder.execute().actionGet();
    for (Flag flag : values) {
      assertThat(isSet(flag, stats.getPrimaries()), equalTo(true));
      assertThat(isSet(flag, stats.getTotal()), equalTo(true));
    }
    Random random = getRandom();
    EnumSet<Flag> flags = EnumSet.noneOf(Flag.class);
    for (Flag flag : values) {
      if (random.nextBoolean()) {
        flags.add(flag);
      }
    }

    for (Flag flag : values) {
      set(flag, builder, false); // clear all
    }

    for (Flag flag : flags) { // set the flags
      set(flag, builder, true);
    }
    stats = builder.execute().actionGet();
    for (Flag flag : flags) { // check the flags
      assertThat(isSet(flag, stats.getPrimaries()), equalTo(true));
      assertThat(isSet(flag, stats.getTotal()), equalTo(true));
    }

    for (Flag flag : EnumSet.complementOf(flags)) { // check the complement
      assertThat(isSet(flag, stats.getPrimaries()), equalTo(false));
      assertThat(isSet(flag, stats.getTotal()), equalTo(false));
    }
  }
Ejemplo n.º 16
0
 public boolean canUnionWith(ContinuousRealInterval other) {
   return EnumSet.complementOf(
           EnumSet.of(IntervalRelations.PRECEDES, IntervalRelations.PRECEDED_BY))
       .contains(compare(other));
 }
Ejemplo n.º 17
0
public final class CableUtils {
  private static Set<ForgeDirection> allSides =
      EnumSet.complementOf(EnumSet.of(ForgeDirection.UNKNOWN));

  /**
   * Gets all the connected energy acceptors, whether IC2-based or BuildCraft-based, surrounding a
   * specific tile entity.
   *
   * @param tileEntity - center tile entity
   * @return TileEntity[] of connected acceptors
   */
  public static TileEntity[] getConnectedEnergyAcceptors(TileEntity tileEntity) {
    TileEntity[] acceptors = new TileEntity[] {null, null, null, null, null, null};

    for (ForgeDirection orientation : ForgeDirection.VALID_DIRECTIONS) {
      TileEntity acceptor =
          Coord4D.get(tileEntity).getFromSide(orientation).getTileEntity(tileEntity.getWorldObj());

      if (isEnergyAcceptor(acceptor)) {
        acceptors[orientation.ordinal()] = acceptor;
      }
    }

    return acceptors;
  }

  public static boolean isEnergyAcceptor(TileEntity tileEntity) {
    return (tileEntity instanceof IStrictEnergyAcceptor
        || (MekanismUtils.useIC2() && tileEntity instanceof IEnergySink)
        || (MekanismUtils.useBuildCraft()
            && MjAPI.getMjBattery(tileEntity) != null
            && !(tileEntity instanceof IGridTransmitter))
        || (MekanismUtils.useRF() && tileEntity instanceof IEnergyHandler));
  }

  /**
   * Gets all the connected cables around a specific tile entity.
   *
   * @param tileEntity - center tile entity
   * @return TileEntity[] of connected cables
   */
  public static TileEntity[] getConnectedCables(TileEntity tileEntity) {
    TileEntity[] cables = new TileEntity[] {null, null, null, null, null, null};

    for (ForgeDirection orientation : ForgeDirection.VALID_DIRECTIONS) {
      TileEntity cable =
          Coord4D.get(tileEntity).getFromSide(orientation).getTileEntity(tileEntity.getWorldObj());

      if (isCable(cable)) {
        cables[orientation.ordinal()] = cable;
      }
    }

    return cables;
  }

  public static boolean isCable(TileEntity tileEntity) {
    return TransmissionType.checkTransmissionType(tileEntity, TransmissionType.ENERGY);
  }

  /**
   * Gets all the adjacent connections to a TileEntity.
   *
   * @param tileEntity - center TileEntity
   * @return boolean[] of adjacent connections
   */
  public static boolean[] getConnections(TileEntity tileEntity) {
    return getConnections(tileEntity, allSides);
  }

  /**
   * Gets the adjacent connections to a TileEntity, from a subset of its sides.
   *
   * @param tileEntity - center TileEntity
   * @param sides - set of sides to check
   * @return boolean[] of adjacent connections
   */
  public static boolean[] getConnections(TileEntity tileEntity, Set<ForgeDirection> sides) {
    boolean[] connectable = new boolean[] {false, false, false, false, false, false};
    Coord4D coord = Coord4D.get(tileEntity);

    for (ForgeDirection side : sides) {
      TileEntity tile = coord.getFromSide(side).getTileEntity(tileEntity.getWorldObj());

      connectable[side.ordinal()] |=
          isEnergyAcceptor(tile) && isConnectable(tileEntity, tile, side);
      connectable[side.ordinal()] |= isCable(tile);
      connectable[side.ordinal()] |= isOutputter(tile, side);
    }

    return connectable;
  }

  /**
   * Gets all the connected cables around a specific tile entity.
   *
   * @param tileEntity - center tile entity
   * @return TileEntity[] of connected cables
   */
  public static TileEntity[] getConnectedOutputters(TileEntity tileEntity) {
    TileEntity[] outputters = new TileEntity[] {null, null, null, null, null, null};

    for (ForgeDirection orientation : ForgeDirection.VALID_DIRECTIONS) {
      TileEntity outputter =
          Coord4D.get(tileEntity).getFromSide(orientation).getTileEntity(tileEntity.getWorldObj());

      if (isOutputter(outputter, orientation)) {
        outputters[orientation.ordinal()] = outputter;
      }
    }

    return outputters;
  }

  public static boolean isOutputter(TileEntity tileEntity, ForgeDirection side) {
    return (tileEntity instanceof ICableOutputter
            && ((ICableOutputter) tileEntity).canOutputTo(side.getOpposite()))
        || (MekanismUtils.useIC2()
            && tileEntity instanceof IEnergySource
            && ((IEnergySource) tileEntity).emitsEnergyTo(null, side.getOpposite()))
        || (MekanismUtils.useRF()
            && tileEntity instanceof IEnergyHandler
            && ((IEnergyHandler) tileEntity).canConnectEnergy(side.getOpposite()))
        || (MekanismUtils.useRF()
            && tileEntity instanceof IEnergyConnection
            && ((IEnergyConnection) tileEntity).canConnectEnergy(side.getOpposite()))
        || (MekanismUtils.useBuildCraft()
            && tileEntity instanceof IPowerEmitter
            && ((IPowerEmitter) tileEntity).canEmitPowerFrom(side.getOpposite()));
  }

  /**
   * Whether or not a cable can connect to a specific acceptor.
   *
   * @param side - side to check
   * @param tile - cable TileEntity
   * @return whether or not the cable can connect to the specific side
   */
  public static boolean canConnectToAcceptor(ForgeDirection side, TileEntity tile) {
    if (tile == null) {
      return false;
    }

    TileEntity tileEntity = Coord4D.get(tile).getFromSide(side).getTileEntity(tile.getWorldObj());

    return isConnectable(tile, tileEntity, side);
  }

  public static boolean isConnectable(TileEntity orig, TileEntity tileEntity, ForgeDirection side) {
    if (tileEntity instanceof IGridTransmitter) {
      return false;
    }

    if (tileEntity instanceof IStrictEnergyAcceptor) {
      if (((IStrictEnergyAcceptor) tileEntity).canReceiveEnergy(side.getOpposite())) {
        return true;
      }
    } else if (MekanismUtils.useIC2() && tileEntity instanceof IEnergyAcceptor) {
      if (((IEnergyAcceptor) tileEntity).acceptsEnergyFrom(orig, side.getOpposite())) {
        return true;
      }
    } else if (tileEntity instanceof ICableOutputter) {
      if (((ICableOutputter) tileEntity).canOutputTo(side.getOpposite())) {
        return true;
      }
    } else if (MekanismUtils.useRF() && tileEntity instanceof IEnergyHandler) {
      if (((IEnergyHandler) tileEntity).canConnectEnergy(side.getOpposite())) {
        return true;
      }
    } else if (MekanismUtils.useBuildCraft()) {
      if (MjAPI.getMjBattery(tileEntity, MjAPI.DEFAULT_POWER_FRAMEWORK, side.getOpposite())
          != null) {
        return true;
      }
    }

    return false;
  }

  public static void emit(TileEntityElectricBlock emitter) {
    if (!emitter.getWorldObj().isRemote && MekanismUtils.canFunction(emitter)) {
      double energyToSend = Math.min(emitter.getEnergy(), emitter.getMaxOutput());

      if (energyToSend > 0) {
        List<ForgeDirection> outputtingSides = new ArrayList<ForgeDirection>();
        boolean[] connectable = getConnections(emitter, emitter.getOutputtingSides());

        for (ForgeDirection side : emitter.getOutputtingSides()) {
          if (connectable[side.ordinal()]) {
            outputtingSides.add(side);
          }
        }

        if (outputtingSides.size() > 0) {
          double sent = 0;
          boolean tryAgain = false;

          do {
            tryAgain = false;

            double prev = sent;
            sent += emit_do(emitter, outputtingSides, energyToSend - sent, tryAgain);

            if (energyToSend - sent > 0 && sent - prev > 0) {
              tryAgain = true;
            }
          } while (tryAgain);

          emitter.setEnergy(emitter.getEnergy() - sent);
        }
      }
    }
  }

  private static double emit_do(
      TileEntityElectricBlock emitter,
      List<ForgeDirection> outputtingSides,
      double totalToSend,
      boolean tryAgain) {
    double remains = totalToSend % outputtingSides.size();
    double splitSend = (totalToSend - remains) / outputtingSides.size();
    double sent = 0;

    List<ForgeDirection> toRemove = new ArrayList<ForgeDirection>();

    for (ForgeDirection side : outputtingSides) {
      TileEntity tileEntity =
          Coord4D.get(emitter).getFromSide(side).getTileEntity(emitter.getWorldObj());
      double toSend = splitSend + remains;
      remains = 0;

      double prev = sent;
      sent += emit_do_do(emitter, tileEntity, side, toSend, tryAgain);

      if (sent - prev == 0) {
        toRemove.add(side);
      }
    }

    for (ForgeDirection side : toRemove) {
      outputtingSides.remove(side);
    }

    return sent;
  }

  private static double emit_do_do(
      TileEntityElectricBlock from,
      TileEntity tileEntity,
      ForgeDirection side,
      double currentSending,
      boolean tryAgain) {
    double sent = 0;

    if (tileEntity instanceof IStrictEnergyAcceptor) {
      IStrictEnergyAcceptor acceptor = (IStrictEnergyAcceptor) tileEntity;

      if (acceptor.canReceiveEnergy(side.getOpposite())) {
        sent += acceptor.transferEnergyToAcceptor(side.getOpposite(), currentSending);
      }
    } else if (MekanismUtils.useRF() && tileEntity instanceof IEnergyHandler) {
      IEnergyHandler handler = (IEnergyHandler) tileEntity;

      if (handler.canConnectEnergy(side.getOpposite())) {
        int used =
            handler.receiveEnergy(
                side.getOpposite(), (int) Math.round(currentSending * Mekanism.TO_TE), false);
        sent += used * Mekanism.FROM_TE;
      }
    } else if (MekanismUtils.useIC2() && tileEntity instanceof IEnergySink) {
      if (((IEnergySink) tileEntity).acceptsEnergyFrom(from, side.getOpposite())) {
        double toSend =
            Math.min(
                currentSending,
                EnergyNet.instance.getPowerFromTier(((IEnergySink) tileEntity).getSinkTier())
                    * Mekanism.FROM_IC2);
        toSend =
            Math.min(toSend, ((IEnergySink) tileEntity).getDemandedEnergy() * Mekanism.FROM_IC2);
        sent +=
            (toSend
                - (((IEnergySink) tileEntity)
                        .injectEnergy(side.getOpposite(), toSend * Mekanism.TO_IC2, 0)
                    * Mekanism.FROM_IC2));
      }
    } else if (MekanismUtils.useBuildCraft()
        && MjAPI.getMjBattery(tileEntity, MjAPI.DEFAULT_POWER_FRAMEWORK, side.getOpposite()) != null
        && !tryAgain) {
      IBatteryObject battery =
          MjAPI.getMjBattery(tileEntity, MjAPI.DEFAULT_POWER_FRAMEWORK, side.getOpposite());
      double toSend =
          battery.addEnergy(
              Math.min(battery.getEnergyRequested(), currentSending * Mekanism.TO_BC));
      sent += toSend * Mekanism.FROM_BC;
    }

    return sent;
  }
}
public class TileEntityFluidicPlenisher extends TileEntityElectricBlock
    implements IComputerIntegration, IConfigurable, IFluidHandler, ISustainedTank {
  public Set<Coord4D> activeNodes = new HashSet<Coord4D>();
  public Set<Coord4D> usedNodes = new HashSet<Coord4D>();

  public boolean finishedCalc = false;

  public FluidTank fluidTank = new FluidTank(10000);

  private static EnumSet<ForgeDirection> dirs =
      EnumSet.complementOf(EnumSet.of(ForgeDirection.UP, ForgeDirection.UNKNOWN));
  private static int MAX_NODES = 4000;

  public TileEntityFluidicPlenisher() {
    super("FluidicPlenisher", MachineType.FLUIDIC_PLENISHER.baseEnergy);
    inventory = new ItemStack[3];
  }

  @Override
  public void onUpdate() {
    if (!worldObj.isRemote) {
      ChargeUtils.discharge(2, this);

      if (inventory[0] != null) {
        if (inventory[0].getItem() instanceof IFluidContainerItem
            && ((IFluidContainerItem) inventory[0].getItem()).getFluid(inventory[0]) != null) {
          if (((IFluidContainerItem) inventory[0].getItem())
              .getFluid(inventory[0])
              .getFluid()
              .canBePlacedInWorld()) {
            fluidTank.fill(FluidContainerUtils.extractFluid(fluidTank, inventory[0]), true);

            if (((IFluidContainerItem) inventory[0].getItem()).getFluid(inventory[0]) == null
                || fluidTank.getFluidAmount() == fluidTank.getCapacity()) {
              if (inventory[1] == null) {
                inventory[1] = inventory[0].copy();
                inventory[0] = null;

                markDirty();
              }
            }
          }
        } else if (FluidContainerRegistry.isFilledContainer(inventory[0])) {
          FluidStack itemFluid = FluidContainerRegistry.getFluidForFilledItem(inventory[0]);

          if ((fluidTank.getFluid() == null && itemFluid.amount <= fluidTank.getCapacity())
              || fluidTank.getFluid().amount + itemFluid.amount <= fluidTank.getCapacity()) {
            if ((fluidTank.getFluid() != null && !fluidTank.getFluid().isFluidEqual(itemFluid))
                || !itemFluid.getFluid().canBePlacedInWorld()) {
              return;
            }

            ItemStack containerItem = inventory[0].getItem().getContainerItem(inventory[0]);

            boolean filled = false;

            if (containerItem != null) {
              if (inventory[1] == null
                  || (inventory[1].isItemEqual(containerItem)
                      && inventory[1].stackSize + 1 <= containerItem.getMaxStackSize())) {
                inventory[0] = null;

                if (inventory[1] == null) {
                  inventory[1] = containerItem;
                } else {
                  inventory[1].stackSize++;
                }

                filled = true;
              }
            } else {
              inventory[0].stackSize--;

              if (inventory[0].stackSize == 0) {
                inventory[0] = null;
              }

              filled = true;
            }

            if (filled) {
              fluidTank.fill(itemFluid, true);
              markDirty();
            }
          }
        }
      }

      if (getEnergy() >= usage.fluidicPlenisherUsage
          && worldObj.getWorldTime() % 10 == 0
          && fluidTank.getFluidAmount() >= FluidContainerRegistry.BUCKET_VOLUME) {
        if (fluidTank.getFluid().getFluid().canBePlacedInWorld()) {
          if (!finishedCalc) {
            doPlenish();
          } else {
            Coord4D below = Coord4D.get(this).getFromSide(ForgeDirection.DOWN);

            if (canReplace(below, false, false)
                && getEnergy() >= usage.fluidicPlenisherUsage
                && fluidTank.getFluidAmount() >= FluidContainerRegistry.BUCKET_VOLUME) {
              if (fluidTank.getFluid().getFluid().canBePlacedInWorld()) {
                worldObj.setBlock(
                    below.xCoord,
                    below.yCoord,
                    below.zCoord,
                    MekanismUtils.getFlowingBlock(fluidTank.getFluid().getFluid()),
                    0,
                    3);

                setEnergy(getEnergy() - usage.fluidicPlenisherUsage);
                fluidTank.drain(FluidContainerRegistry.BUCKET_VOLUME, true);
              }
            }
          }
        }
      }
    }
  }

  private void doPlenish() {
    if (usedNodes.size() >= MAX_NODES) {
      finishedCalc = true;
      return;
    }

    if (activeNodes.isEmpty()) {
      if (usedNodes.isEmpty()) {
        Coord4D below = Coord4D.get(this).getFromSide(ForgeDirection.DOWN);

        if (!canReplace(below, true, true)) {
          finishedCalc = true;
          return;
        }

        activeNodes.add(below);
      } else {
        finishedCalc = true;
        return;
      }
    }

    Set<Coord4D> toRemove = new HashSet<Coord4D>();

    for (Coord4D coord : activeNodes) {
      if (coord.exists(worldObj)) {
        if (canReplace(coord, true, false)) {
          worldObj.setBlock(
              coord.xCoord,
              coord.yCoord,
              coord.zCoord,
              MekanismUtils.getFlowingBlock(fluidTank.getFluid().getFluid()),
              0,
              3);

          setEnergy(getEnergy() - usage.fluidicPlenisherUsage);
          fluidTank.drain(FluidContainerRegistry.BUCKET_VOLUME, true);
        }

        for (ForgeDirection dir : dirs) {
          Coord4D sideCoord = coord.getFromSide(dir);

          if (sideCoord.exists(worldObj) && canReplace(sideCoord, true, true)) {
            activeNodes.add(sideCoord);
          }
        }

        toRemove.add(coord);
        break;
      } else {
        toRemove.add(coord);
      }
    }

    for (Coord4D coord : toRemove) {
      activeNodes.remove(coord);
      usedNodes.add(coord);
    }
  }

  public int getActiveY() {
    return yCoord - 1;
  }

  public boolean canReplace(Coord4D coord, boolean checkNodes, boolean isPathfinding) {
    if (checkNodes && usedNodes.contains(coord)) {
      return false;
    }

    if (coord.isAirBlock(worldObj) || MekanismUtils.isDeadFluid(worldObj, coord)) {
      return true;
    }

    if (MekanismUtils.isFluid(worldObj, coord)) {
      return isPathfinding;
    }

    return coord
        .getBlock(worldObj)
        .isReplaceable(worldObj, coord.xCoord, coord.yCoord, coord.zCoord);
  }

  @Override
  public void handlePacketData(ByteBuf dataStream) {
    super.handlePacketData(dataStream);

    finishedCalc = dataStream.readBoolean();

    if (dataStream.readInt() == 1) {
      fluidTank.setFluid(new FluidStack(dataStream.readInt(), dataStream.readInt()));
    } else {
      fluidTank.setFluid(null);
    }

    MekanismUtils.updateBlock(worldObj, xCoord, yCoord, zCoord);
  }

  @Override
  public ArrayList getNetworkedData(ArrayList data) {
    super.getNetworkedData(data);

    data.add(finishedCalc);

    if (fluidTank.getFluid() != null) {
      data.add(1);
      data.add(fluidTank.getFluid().getFluidID());
      data.add(fluidTank.getFluid().amount);
    } else {
      data.add(0);
    }

    return data;
  }

  @Override
  public void writeToNBT(NBTTagCompound nbtTags) {
    super.writeToNBT(nbtTags);

    nbtTags.setBoolean("finishedCalc", finishedCalc);

    if (fluidTank.getFluid() != null) {
      nbtTags.setTag("fluidTank", fluidTank.writeToNBT(new NBTTagCompound()));
    }

    NBTTagList activeList = new NBTTagList();

    for (Coord4D wrapper : activeNodes) {
      NBTTagCompound tagCompound = new NBTTagCompound();
      wrapper.write(tagCompound);
      activeList.appendTag(tagCompound);
    }

    if (activeList.tagCount() != 0) {
      nbtTags.setTag("activeNodes", activeList);
    }

    NBTTagList usedList = new NBTTagList();

    for (Coord4D obj : usedNodes) {
      activeList.appendTag(obj.write(new NBTTagCompound()));
    }

    if (activeList.tagCount() != 0) {
      nbtTags.setTag("usedNodes", usedList);
    }
  }

  @Override
  public void readFromNBT(NBTTagCompound nbtTags) {
    super.readFromNBT(nbtTags);

    finishedCalc = nbtTags.getBoolean("finishedCalc");

    if (nbtTags.hasKey("fluidTank")) {
      fluidTank.readFromNBT(nbtTags.getCompoundTag("fluidTank"));
    }

    if (nbtTags.hasKey("activeNodes")) {
      NBTTagList tagList = nbtTags.getTagList("activeNodes", NBT.TAG_COMPOUND);

      for (int i = 0; i < tagList.tagCount(); i++) {
        activeNodes.add(Coord4D.read((NBTTagCompound) tagList.getCompoundTagAt(i)));
      }
    }

    if (nbtTags.hasKey("usedNodes")) {
      NBTTagList tagList = nbtTags.getTagList("usedNodes", NBT.TAG_COMPOUND);

      for (int i = 0; i < tagList.tagCount(); i++) {
        usedNodes.add(Coord4D.read((NBTTagCompound) tagList.getCompoundTagAt(i)));
      }
    }
  }

  @Override
  public boolean isItemValidForSlot(int slotID, ItemStack itemstack) {
    if (slotID == 1) {
      return false;
    } else if (slotID == 0) {
      return FluidContainerRegistry.isFilledContainer(itemstack);
    } else if (slotID == 2) {
      return ChargeUtils.canBeDischarged(itemstack);
    }

    return false;
  }

  @Override
  public boolean canExtractItem(int slotID, ItemStack itemstack, int side) {
    if (slotID == 2) {
      return ChargeUtils.canBeOutputted(itemstack, false);
    } else if (slotID == 1) {
      return true;
    }

    return false;
  }

  @Override
  public EnumSet<ForgeDirection> getConsumingSides() {
    return EnumSet.of(ForgeDirection.getOrientation(facing).getOpposite());
  }

  @Override
  public boolean canSetFacing(int side) {
    return side != 0 && side != 1;
  }

  @Override
  public int[] getAccessibleSlotsFromSide(int side) {
    if (side == 1) {
      return new int[] {0};
    } else if (side == 0) {
      return new int[] {1};
    } else {
      return new int[] {2};
    }
  }

  @Override
  public FluidTankInfo[] getTankInfo(ForgeDirection direction) {
    if (direction == ForgeDirection.UP) {
      return new FluidTankInfo[] {fluidTank.getInfo()};
    }

    return PipeUtils.EMPTY;
  }

  @Override
  public void setFluidStack(FluidStack fluidStack, Object... data) {
    fluidTank.setFluid(fluidStack);
  }

  @Override
  public FluidStack getFluidStack(Object... data) {
    return fluidTank.getFluid();
  }

  @Override
  public boolean hasTank(Object... data) {
    return true;
  }

  @Override
  public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) {
    if (fluidTank.getFluid() != null
        && fluidTank.getFluid().getFluid() == resource.getFluid()
        && from == ForgeDirection.UP) {
      return drain(from, resource.amount, doDrain);
    }

    return null;
  }

  @Override
  public int fill(ForgeDirection from, FluidStack resource, boolean doFill) {
    if (from == ForgeDirection.UP && resource.getFluid().canBePlacedInWorld()) {
      return fluidTank.fill(resource, true);
    }

    return 0;
  }

  @Override
  public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) {
    return null;
  }

  @Override
  public boolean canFill(ForgeDirection from, Fluid fluid) {
    return from == ForgeDirection.UP && fluid.canBePlacedInWorld();
  }

  @Override
  public boolean canDrain(ForgeDirection from, Fluid fluid) {
    return false;
  }

  @Override
  public boolean onSneakRightClick(EntityPlayer player, int side) {
    activeNodes.clear();
    usedNodes.clear();
    finishedCalc = false;

    player.addChatMessage(
        new ChatComponentText(
            EnumColor.DARK_BLUE
                + "[Mekanism] "
                + EnumColor.GREY
                + LangUtils.localize("tooltip.configurator.plenisherReset")));

    return true;
  }

  @Override
  public boolean onRightClick(EntityPlayer player, int side) {
    return false;
  }

  private static final String[] methods = new String[] {"reset"};

  @Override
  public String[] getMethods() {
    return methods;
  }

  @Override
  public Object[] invoke(int method, Object[] arguments) throws Exception {
    switch (method) {
      case 0:
        activeNodes.clear();
        usedNodes.clear();
        finishedCalc = false;

        return new Object[] {"Plenisher calculation reset."};
      default:
        throw new NoSuchMethodException();
    }
  }
}