示例#1
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);
 }
示例#2
0
  private boolean filterCard(AbstractCard abstractCard) {
    if (filterString != null && filterString.length() != 0) {
      if (!searchCardText(abstractCard, filterString)) {
        return false;
      }
    }
    if (cardTypes.size() != NUMBEROFCARDTYPES) {
      if (!match(abstractCard.cardType, cardTypes)) return false;
    }
    if (colors.size() != NUMBEROFCOLORS) {
      if (!match(abstractCard.colorFlags, colors)
          && (abstractCard.resourceThresholdGranted == null
              ? true
              : !match(abstractCard.resourceThresholdGranted[0].colorFlags, colors))) return false;
    }

    if (abstractCard instanceof Card) {

      Card card;
      card = (Card) abstractCard;

      if (card.resourceCost > maxCost || card.resourceCost < minCost) {
        return false;
      }
      if (!attributes.isEmpty()) {
        for (Attribute att : attributes) {
          if (!Arrays.asList(card.attributeFlags).contains(att)) {
            return false;
          }
        }
      }
    }
    return true;
  }
  /**
   * 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));
    }
  }
  private boolean veto(
      EnumSet<ExecutableType> classLevelExecutableTypes,
      EnumSet<ExecutableType> memberLevelExecutableType,
      ExecutableType currentExecutableType) {
    if (!memberLevelExecutableType.isEmpty()) {
      return !memberLevelExecutableType.contains(currentExecutableType)
          && !memberLevelExecutableType.contains(ExecutableType.IMPLICIT);
    }

    if (!classLevelExecutableTypes.isEmpty()) {
      return !classLevelExecutableTypes.contains(currentExecutableType)
          && !classLevelExecutableTypes.contains(ExecutableType.IMPLICIT);
    }

    return !globalExecutableTypes.contains(currentExecutableType);
  }
示例#5
0
 /**
  * Helper method that can be used to dynamically figure out enumeration type of given {@link
  * EnumSet}, without having access to its declaration. Code is needed to work around design flaw
  * in JDK.
  *
  * @since 1.5
  */
 public static Class<? extends Enum<?>> findEnumType(EnumSet<?> s) {
   // First things first: if not empty, easy to determine
   if (!s.isEmpty()) {
     return findEnumType(s.iterator().next());
   }
   // Otherwise need to locate using an internal field
   return EnumTypeLocator.instance.enumTypeFor(s);
 }
  /**
   * Redraws the sources on this layer, after first refreshing them based on the current state of
   * the {@link com.google.android.stardroid.control.AstronomerModel}.
   */
  protected synchronized void refreshSources(EnumSet<UpdateType> updateTypes) {
    for (AstronomicalSource astroSource : astroSources) {
      updateTypes.addAll(astroSource.update());
    }

    if (!updateTypes.isEmpty()) {
      redraw(updateTypes);
    }
  }
 private static void highlightIncorrectArguments(
     ProblemsHolder holder, CallArgumentsMapping result, @NotNull TypeEvalContext context) {
   for (Map.Entry<PyExpression, EnumSet<CallArgumentsMapping.ArgFlag>> argEntry :
       result.getArgumentFlags().entrySet()) {
     EnumSet<CallArgumentsMapping.ArgFlag> flags = argEntry.getValue();
     if (!flags.isEmpty()) { // something's wrong
       PyExpression arg = argEntry.getKey();
       if (flags.contains(CallArgumentsMapping.ArgFlag.IS_DUP)) {
         holder.registerProblem(arg, PyBundle.message("INSP.duplicate.argument"));
       }
       if (flags.contains(CallArgumentsMapping.ArgFlag.IS_DUP_KWD)) {
         holder.registerProblem(arg, PyBundle.message("INSP.duplicate.doublestar.arg"));
       }
       if (flags.contains(CallArgumentsMapping.ArgFlag.IS_DUP_TUPLE)) {
         holder.registerProblem(arg, PyBundle.message("INSP.duplicate.star.arg"));
       }
       if (flags.contains(CallArgumentsMapping.ArgFlag.IS_POS_PAST_KWD)) {
         holder.registerProblem(
             arg,
             PyBundle.message("INSP.cannot.appear.past.keyword.arg"),
             ProblemHighlightType.ERROR);
       }
       if (flags.contains(CallArgumentsMapping.ArgFlag.IS_UNMAPPED)) {
         holder.registerProblem(arg, PyBundle.message("INSP.unexpected.arg"));
       }
       if (flags.contains(CallArgumentsMapping.ArgFlag.IS_TOO_LONG)) {
         final PyCallExpression.PyMarkedCallee markedCallee = result.getMarkedCallee();
         String parameterName = null;
         if (markedCallee != null) {
           final List<PyParameter> parameters =
               PyUtil.getParameters(markedCallee.getCallable(), context);
           for (int i = parameters.size() - 1; i >= 0; --i) {
             final PyParameter param = parameters.get(i);
             if (param instanceof PyNamedParameter) {
               final List<PyNamedParameter> unmappedParams = result.getUnmappedParams();
               if (!((PyNamedParameter) param).isPositionalContainer()
                   && !((PyNamedParameter) param).isKeywordContainer()
                   && param.getDefaultValue() == null
                   && !unmappedParams.contains(param)) {
                 parameterName = param.getName();
                 break;
               }
             }
           }
           holder.registerProblem(
               arg,
               parameterName != null
                   ? PyBundle.message(
                       "INSP.multiple.values.resolve.to.positional.$0", parameterName)
                   : PyBundle.message("INSP.more.args.that.pos.params"));
         }
       }
     }
   }
 }
  /** Disable the "Clear" button if none of the options are selected. Otherwise, enable it. */
  private void updateButtonState() {
    Button clearButton = mDialog.getButton(AlertDialog.BUTTON_POSITIVE);
    if (clearButton == null) return;
    boolean isEnabled = !mSelectedOptions.isEmpty();
    clearButton.setEnabled(isEnabled);

    // Work around a bug in the app compat library where disabled buttons in alert dialogs
    // don't look disabled on pre-L devices. See: http://crbug.com/550784
    // TODO(newt): remove this workaround when the app compat library is fixed (b/26017217)
    clearButton.setTextColor(isEnabled ? 0xFF4285F4 : 0x335A5A5A);
  }
示例#9
0
  /**
   * Add a layer to the current MapView. The layer will be added at topmost position.
   *
   * @param layer The layer to add
   */
  public void addLayer(Layer layer) {
    boolean isOsmDataLayer = layer instanceof OsmDataLayer;
    layerLock.writeLock().lock();
    layerLock.readLock().lock();
    EnumSet<LayerListenerType> listenersToFire = EnumSet.noneOf(LayerListenerType.class);
    Layer oldActiveLayer = activeLayer;
    OsmDataLayer oldEditLayer = editLayer;
    try {
      try {
        if (layer instanceof MarkerLayer && playHeadMarker == null) {
          playHeadMarker = PlayHeadMarker.create();
        }

        if (layer instanceof GpxLayer) {
          addGpxLayer((GpxLayer) layer);
        } else if (layers.isEmpty()) {
          layers.add(layer);
        } else if (layer.isBackgroundLayer()) {
          int i = 0;
          for (; i < layers.size(); i++) {
            if (layers.get(i).isBackgroundLayer()) {
              break;
            }
          }
          layers.add(i, layer);
        } else {
          layers.add(0, layer);
        }

        if (isOsmDataLayer || oldActiveLayer == null) {
          // autoselect the new layer
          listenersToFire.addAll(setActiveLayer(layer, true));
        }
      } finally {
        layerLock.writeLock().unlock();
      }

      fireLayerAdded(layer);
      if (isOsmDataLayer) {
        ((OsmDataLayer) layer).addLayerStateChangeListener(this);
      }
      onActiveEditLayerChanged(oldActiveLayer, oldEditLayer, listenersToFire);
      layer.addPropertyChangeListener(this);
      Main.addProjectionChangeListener(layer);
      AudioPlayer.reset();
    } finally {
      layerLock.readLock().unlock();
    }
    if (!listenersToFire.isEmpty()) {
      repaint();
    }
  }
示例#10
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();
 }
 @Override
 public String toString() {
   StringBuffer sb = new StringBuffer();
   ToStringStyle style = ToStringStyle.SHORT_PREFIX_STYLE;
   style.appendStart(sb, this);
   if (hasException()) {
     style.append(sb, "exception", getExceptionClass(), null);
   }
   if (!_logLevels.isEmpty()) {
     style.append(sb, "logLevels", _logLevels, null);
   }
   style.appendEnd(sb, this);
   return sb.toString();
 }
示例#12
0
 /**
  * Creates a copy of a Flag Set removing instances of FAIL_SILENTLY. The copy might be the same
  * instance if no change is required, and should be considered immutable.
  *
  * @param flags
  * @return might return the same instance
  */
 public static Set<Flag> copyWithoutRemotableFlags(Set<Flag> flags) {
   // FAIL_SILENTLY should not be sent to remote nodes
   if (flags != null && flags.contains(Flag.FAIL_SILENTLY)) {
     EnumSet<Flag> copy = EnumSet.copyOf(flags);
     copy.remove(Flag.FAIL_SILENTLY);
     if (copy.isEmpty()) {
       return InfinispanCollections.emptySet();
     } else {
       return copy;
     }
   } else {
     return flags;
   }
 }
示例#13
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);
      }
    }
  }
示例#14
0
  private boolean validateNodeOptions(Operation joinOp, EnumSet<NodeOption> options) {
    if (options.isEmpty()) {
      joinOp.fail(new IllegalArgumentException("at least one option must be specified"));
      return false;
    }

    if (options.contains(NodeOption.OBSERVER) && options.contains(NodeOption.PEER)) {
      joinOp.fail(
          new IllegalArgumentException(
              String.format(
                  "%s and %s are mutually exclusive", NodeOption.OBSERVER, NodeOption.PEER)));
      return false;
    }

    return true;
  }
  public Map<EdgeLabel, Multimap<EdgeIndex, IEdgeTarget>> getInEdges(
      long receiverId,
      long senderId,
      NidVer oid,
      EnumSet<HistoryState> sourceHistoryStates,
      Optional<ClassId> sourceClassId,
      EnumSet<EdgeType> types,
      Optional<EdgeIndexRange> indexRange,
      Optional<EdgeLabel> label,
      boolean queryablesOnly)
      throws NodeNotFoundException {
    /*
    if ((label.isPresent() && label.get().isPrivate()) && (!sourceClassId.isPresent())) {
        throw new ExpectableException("Need the source class if a private label is given.");
    } ist nicht mehr notwendig, da im label neu die classID drinn ist. */
    if (types.isEmpty()) {
      throw new ExpectableException("types.isEmpty()");
    }
    final NodeImpl node = getNodeFromCurrentOrHistorized(receiverId, oid);
    if (node == null) {
      throw new NodeNotFoundException("Node not found");
    }

    final NodeClass nodeClass = this.ncApi.getClassById(node.getNodeSerie().getClassId());

    final Map<EdgeLabel, Multimap<EdgeIndex, EdgeImpl>> verInEdges = node.getVersionedInEdgeds();
    final Map<EdgeLabel, Multimap<EdgeIndex, EdgeImpl>> unverInEdges =
        node.getNodeSerie().getInEdges();

    final Map<EdgeLabel, Multimap<EdgeIndex, IEdgeTarget>> combination = new HashMap<>();

    /* Add versioned edge */
    addToEdges(
        combination, label, indexRange, queryablesOnly, nodeClass, verInEdges, sourceHistoryStates);

    /* Add unversioned edge */
    addToEdges(
        combination,
        label,
        indexRange,
        queryablesOnly,
        nodeClass,
        unverInEdges,
        sourceHistoryStates);

    return combination;
  }
  private String getMarkerHighlightClass(UICode row) {
    // no highlight necessary
    if (highlightedMarkers.isEmpty()) return null;

    List<MarkerType> markers = markerUtil.resolve(row.getAttributes());

    // no marker to highlight
    if (markers.isEmpty()) return null;

    markers.retainAll(highlightedMarkers);

    if (markers.size() == 1) return styleProvider.getStyle(markers.get(0)).getHighlightStyleName();

    if (markers.size() > 1) return generateGradient(markers);

    return null;
  }
示例#17
0
  /**
   * Grants a new permission for a given subject and resource.
   *
   * @param subjectid the subject to give permissions to
   * @param resourceName the resource name/type
   * @param permission the set or HTTP methods allowed
   * @return true if successful
   */
  public boolean grantResourcePermission(
      String subjectid, String resourceName, EnumSet<AllowedMethods> permission) {
    // clean up resource name
    resourceName = Utils.noSpaces(resourceName, "-");

    if (!StringUtils.isBlank(subjectid)
        && !StringUtils.isBlank(resourceName)
        && permission != null
        && !permission.isEmpty()) {
      if (!getResourcePermissions().containsKey(subjectid)) {
        Map<String, List<String>> perm = new HashMap<String, List<String>>();
        perm.put(resourceName, new ArrayList<String>(permission.size()));
        for (AllowedMethods allowedMethod : permission) {
          perm.get(resourceName).add(allowedMethod.toString());
        }
        getResourcePermissions().put(subjectid, perm);
      } else {
        if (permission.containsAll(AllowedMethods.ALL_VALUES)
            || permission.contains(AllowedMethods.READ_WRITE)
            || (permission.contains(AllowedMethods.READ_ONLY)
                && permission.contains(AllowedMethods.WRITE_ONLY))
            || (permission.contains(AllowedMethods.GET)
                && permission.contains(AllowedMethods.WRITE_ONLY))) {
          permission = AllowedMethods.READ_AND_WRITE;
        } else {
          if (permission.contains(AllowedMethods.WRITE_ONLY)) {
            permission = AllowedMethods.WRITE;
          } else if (permission.contains(AllowedMethods.READ_ONLY)) {
            permission = AllowedMethods.READ;
          }
        }
        List<String> perm = new ArrayList<String>(permission.size());
        for (AllowedMethods allowedMethod : permission) {
          perm.add(allowedMethod.toString());
        }
        getResourcePermissions().get(subjectid).put(resourceName, perm);
      }
      return true;
    }
    return false;
  }
示例#18
0
    private List<ApplicationReport> getApplicationReports(
        List<ApplicationReport> applicationReports,
        Set<String> applicationTypes,
        EnumSet<YarnApplicationState> applicationStates) {

      List<ApplicationReport> appReports = new ArrayList<ApplicationReport>();
      for (ApplicationReport appReport : applicationReports) {
        if (applicationTypes != null && !applicationTypes.isEmpty()) {
          if (!applicationTypes.contains(appReport.getApplicationType())) {
            continue;
          }
        }

        if (applicationStates != null && !applicationStates.isEmpty()) {
          if (!applicationStates.contains(appReport.getYarnApplicationState())) {
            continue;
          }
        }
        appReports.add(appReport);
      }
      return appReports;
    }
  private Map<String, String> parseXnioOption(final XMLExtendedStreamReader reader)
      throws XMLStreamException {
    final EnumSet<Attribute> required = EnumSet.of(Attribute.NAME, Attribute.VALUE);
    final int count = reader.getAttributeCount();
    String optionName = null;
    String optionValue = null;
    for (int i = 0; i < count; i++) {
      requireNoNamespaceAttribute(reader, i);
      final String value = reader.getAttributeValue(i);
      final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
      required.remove(attribute);
      switch (attribute) {
        case NAME:
          {
            if (value.trim().isEmpty()) {
              throw ParseUtils.invalidAttributeValue(reader, i);
            }
            optionName = value;
            break;
          }
        case VALUE:
          {
            optionValue = value;
            break;
          }
        default:
          throw unexpectedAttribute(reader, i);
      }
    }
    if (!required.isEmpty()) {
      throw missingRequired(reader, required);
    }
    // This element is just composed of attributes which we already processed, so no more content
    // is expected
    requireNoContent(reader);

    return Collections.singletonMap(optionName, optionValue);
  }
示例#20
0
  final void putForExternalRead(
      K key, V value, EnumSet<Flag> explicitFlags, ClassLoader explicitClassLoader) {
    Transaction ongoingTransaction = null;
    try {
      ongoingTransaction = getOngoingTransaction();
      if (ongoingTransaction != null) transactionManager.suspend();

      EnumSet<Flag> flags =
          EnumSet.of(
              FAIL_SILENTLY,
              FORCE_ASYNCHRONOUS,
              ZERO_LOCK_ACQUISITION_TIMEOUT,
              PUT_FOR_EXTERNAL_READ);
      if (explicitFlags != null && !explicitFlags.isEmpty()) {
        flags.addAll(explicitFlags);
      }

      // if the entry exists then this should be a no-op.
      putIfAbsent(
          key,
          value,
          defaultLifespan,
          TimeUnit.MILLISECONDS,
          defaultMaxIdleTime,
          TimeUnit.MILLISECONDS,
          flags,
          explicitClassLoader);
    } catch (Exception e) {
      if (log.isDebugEnabled()) log.debug("Caught exception while doing putForExternalRead()", e);
    } finally {
      try {
        if (ongoingTransaction != null) transactionManager.resume(ongoingTransaction);
      } catch (Exception e) {
        if (log.isDebugEnabled())
          log.debug("Had problems trying to resume a transaction after putForExternalRead()", e);
      }
    }
  }
  public Map<EdgeLabel, Map<EdgeIndex, EdgeImpl>> getOutEdgesImpl(
      long receiverId, long senderId, NidVer oid, EnumSet<EdgeType> types, boolean queryableOnly)
      throws NodeNotFoundException {
    if (types.isEmpty()) {
      throw new ExpectableException("Types cannot be empty");
    }
    final NodeImpl node = getNodeFromCurrentOrHistorized(receiverId, oid);
    if (node == null) {
      throw new NodeNotFoundException("Node not found");
    }
    final long nodeClassId = node.getNodeSerie().getClassId();
    final NodeClass nodeClass = this.ncApi.getClassById(nodeClassId);
    final Map<EdgeLabel, Map<EdgeIndex, EdgeImpl>> privateEdges = new HashMap<>();
    for (Map.Entry<EdgeLabel, Map<EdgeIndex, EdgeImpl>> edgesEntry :
        node.getOutEdges().entrySet()) {

      /* Is queryable? */
      final boolean isQueryable;
      if (edgesEntry.getKey().isPublic()) {
        isQueryable = edgesEntry.getKey().isPublicQueryable();
      } else {
        EdgeClass pec = nodeClass.getEdgeClasses().get(edgesEntry.getKey().getPrivateEdgeIndex());
        isQueryable = pec.isQueryable();
      }

      if (queryableOnly && (!isQueryable)) {
        continue;
      }
      final boolean isPublic = edgesEntry.getKey().isPublic();
      final boolean add =
          (isPublic && types.contains(EdgeType.publicMod))
              || (!isPublic && types.contains(EdgeType.privateMod));
      if (add) {
        privateEdges.put(edgesEntry.getKey(), edgesEntry.getValue());
      }
    }
    return privateEdges;
  }
示例#22
0
文件: Player.java 项目: marshauf/uni
  @Override
  public void update(float deltaTime) {
    // Compute player input direction
    if (cmds.isEmpty() == false) {
      dir.x = 0;
      dir.y = 0;
      if (cmds.contains(Command.MoveUp)) {
        dir.y += 1;
      }
      if (cmds.contains(Command.MoveDown)) {
        dir.y -= 1;
      }
      if (cmds.contains(Command.MoveLeft)) {
        dir.x -= 1;
      }
      if (cmds.contains(Command.MoveRight)) {
        dir.x += 1;
      }
      dir.nor();
      // Set the velocity of the player object to the direction * speed
      // This enables immediate turns
      super.setVelocity(dir.scl(speed));

      super.position.x += velocity.x * deltaTime;
      super.position.y += velocity.y * deltaTime;
      bounds.setCenter(super.position);

      System.out.println(position.toString());
    }

    if (timeLeftOnEmpowered > 0.0f) {
      timeLeftOnEmpowered -= deltaTime;
      if (timeLeftOnEmpowered < 0.0f) {
        timeLeftOnEmpowered = 0.0f;
      }
    }
  }
 @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++;
     }
   }
 }
示例#24
0
  @Override
  public void handlePatch(Operation patch) {
    NodeGroupState body = getBody(patch);
    if (body == null) {
      patch.fail(new IllegalArgumentException("body of type NodeGroupState is required"));
      return;
    }

    NodeGroupState localState = getState(patch);

    if (body.config == null && body.nodes.isEmpty()) {
      UpdateQuorumRequest bd = patch.getBody(UpdateQuorumRequest.class);
      if (UpdateQuorumRequest.KIND.equals(bd.kind)) {
        handleUpdateQuorumPatch(patch, localState);
        return;
      }
      patch.fail(new IllegalArgumentException("nodes or config are required"));
      return;
    }

    if (body.config != null && body.nodes.isEmpty()) {
      localState.config = body.config;
      patch.complete();
      return;
    }

    adjustStat(patch.getAction() + STAT_NAME_REFERER_SEGMENT + body.documentOwner, 1);
    EnumSet<NodeGroupChange> changes = EnumSet.noneOf(NodeGroupChange.class);
    mergeRemoteAndLocalMembership(localState, body, changes);
    patch.setNotificationDisabled(changes.isEmpty());

    localState.documentOwner = getHost().getId();
    NodeState localNodeState = localState.nodes.get(getHost().getId());
    localNodeState.groupReference = UriUtils.buildPublicUri(getHost(), getSelfLink());

    patch.setBody(localState).complete();

    int healthyCountThreshold =
        Math.max(localNodeState.membershipQuorum, localNodeState.synchQuorum);
    if (localState.nodes.size() < healthyCountThreshold) {
      setAvailable(false);
      return;
    }

    if (!NodeGroupUtils.isMembershipSettled(
        getHost(), getHost().getMaintenanceIntervalMicros(), localState)) {
      setAvailable(false);
      return;
    }

    if (!isAvailable()) {
      boolean hasQuorum = NodeGroupUtils.hasSynchronizationQuorum(getHost(), localState);
      setAvailable(hasQuorum);
    }

    if (localNodeState.status == NodeStatus.AVAILABLE) {
      return;
    }

    localNodeState.status = NodeStatus.AVAILABLE;
    this.sendAvailableSelfPatch(localNodeState);
  }
  private Response put(
      final UserGroupInformation ugi,
      final DelegationParam delegation,
      final UserParam username,
      final DoAsParam doAsUser,
      final String fullpath,
      final PutOpParam op,
      final DestinationParam destination,
      final OwnerParam owner,
      final GroupParam group,
      final PermissionParam permission,
      final OverwriteParam overwrite,
      final BufferSizeParam bufferSize,
      final ReplicationParam replication,
      final BlockSizeParam blockSize,
      final ModificationTimeParam modificationTime,
      final AccessTimeParam accessTime,
      final RenameOptionSetParam renameOptions,
      final CreateParentParam createParent,
      final TokenArgumentParam delegationTokenArgument)
      throws IOException, URISyntaxException {

    final Configuration conf = (Configuration) context.getAttribute(JspHelper.CURRENT_CONF);
    final NameNode namenode = (NameNode) context.getAttribute("name.node");
    final NamenodeProtocols np = namenode.getRpcServer();

    switch (op.getValue()) {
      case CREATE:
        {
          final URI uri =
              redirectURI(
                  namenode,
                  ugi,
                  delegation,
                  username,
                  doAsUser,
                  fullpath,
                  op.getValue(),
                  -1L,
                  blockSize.getValue(conf),
                  permission,
                  overwrite,
                  bufferSize,
                  replication,
                  blockSize);
          return Response.temporaryRedirect(uri).type(MediaType.APPLICATION_OCTET_STREAM).build();
        }
      case MKDIRS:
        {
          final boolean b = np.mkdirs(fullpath, permission.getFsPermission(), true);
          final String js = JsonUtil.toJsonString("boolean", b);
          return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
        }
      case CREATESYMLINK:
        {
          np.createSymlink(
              destination.getValue(),
              fullpath,
              PermissionParam.getDefaultFsPermission(),
              createParent.getValue());
          return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
        }
      case RENAME:
        {
          final EnumSet<Options.Rename> s = renameOptions.getValue();
          if (s.isEmpty()) {
            final boolean b = np.rename(fullpath, destination.getValue());
            final String js = JsonUtil.toJsonString("boolean", b);
            return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
          } else {
            np.rename2(fullpath, destination.getValue(), s.toArray(new Options.Rename[s.size()]));
            return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
          }
        }
      case SETREPLICATION:
        {
          final boolean b = np.setReplication(fullpath, replication.getValue(conf));
          final String js = JsonUtil.toJsonString("boolean", b);
          return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
        }
      case SETOWNER:
        {
          if (owner.getValue() == null && group.getValue() == null) {
            throw new IllegalArgumentException("Both owner and group are empty.");
          }

          np.setOwner(fullpath, owner.getValue(), group.getValue());
          return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
        }
      case SETPERMISSION:
        {
          np.setPermission(fullpath, permission.getFsPermission());
          return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
        }
      case SETTIMES:
        {
          np.setTimes(fullpath, modificationTime.getValue(), accessTime.getValue());
          return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
        }
      case RENEWDELEGATIONTOKEN:
        {
          final Token<DelegationTokenIdentifier> token = new Token<DelegationTokenIdentifier>();
          token.decodeFromUrlString(delegationTokenArgument.getValue());
          final long expiryTime = np.renewDelegationToken(token);
          final String js = JsonUtil.toJsonString("long", expiryTime);
          return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
        }
      case CANCELDELEGATIONTOKEN:
        {
          final Token<DelegationTokenIdentifier> token = new Token<DelegationTokenIdentifier>();
          token.decodeFromUrlString(delegationTokenArgument.getValue());
          np.cancelDelegationToken(token);
          return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
        }
      default:
        throw new UnsupportedOperationException(op + " is not supported");
    }
  }
示例#26
0
  @Override
  public <A> void sendDatagram(
      RegistrationReference registrationReference,
      Datagram datagram,
      A attachment,
      EnumSet<CompletionType> completionTypes,
      CompletionHandler<A> completionHandler,
      long timeout,
      TimeUnit timeUnit) {

    if (registrationReference == null) {
      throw new NullPointerException("Registration reference is null");
    }

    if (!registrationReference.isValid()) {
      throw new IllegalArgumentException("Registration reference is invalid");
    }

    if (datagram == null) {
      throw new NullPointerException("Datagram is null");
    }

    if (completionTypes == null) {
      throw new NullPointerException("Completion type set is null");
    }

    if (completionTypes.isEmpty()) {
      throw new IllegalArgumentException("Completion type set is empty");
    }

    if (completionHandler == null) {
      throw new NullPointerException("Complete handler is null");
    }

    if (timeUnit == null) {
      throw new NullPointerException("Time unit is null");
    }

    if (timeout <= 0) {
      timeout = defaultTimeout;
    } else {
      timeout = timeUnit.toMillis(timeout);
    }

    ensureOpen();

    datagram.attachment = attachment;
    datagram.completionHandler = (CompletionHandler<Object>) completionHandler;
    datagram.completionTypes = completionTypes;
    datagram.timeout = timeout;

    datagram.setAckRequest(completionTypes.contains(CompletionType.DELIVERED));

    if (datagram.getSequenceId() == 0) {
      datagram.setSequenceId(generateSequenceId());
    }

    if (completionTypes.contains(CompletionType.DELIVERED)
        || completionTypes.contains(CompletionType.REPLIED)) {

      addResponseWaitingDatagram(datagram);
    }

    doSendDatagram(registrationReference, datagram);
  }
示例#27
0
  /**
   * the actual constructor. Private access only
   *
   * @param source source
   * @param contig the contig
   * @param start the start base (one based)
   * @param stop the stop reference base (one based)
   * @param alleles alleles
   * @param genotypes genotypes map
   * @param log10PError qual
   * @param filters filters: use null for unfiltered and empty set for passes filters
   * @param attributes attributes
   * @param referenceBaseForIndel padded reference base
   * @param validationToPerform set of validation steps to take
   */
  protected VariantContext(
      String source,
      String ID,
      String contig,
      long start,
      long stop,
      Collection<Allele> alleles,
      GenotypesContext genotypes,
      double log10PError,
      Set<String> filters,
      Map<String, Object> attributes,
      Byte referenceBaseForIndel,
      EnumSet<Validation> validationToPerform) {
    if (contig == null) {
      throw new IllegalArgumentException("Contig cannot be null");
    }
    this.contig = contig;
    this.start = start;
    this.stop = stop;

    // intern for efficiency.  equals calls will generate NPE if ID is inappropriately passed in as
    // null
    if (ID == null || ID.equals(""))
      throw new IllegalArgumentException("ID field cannot be the null or the empty string");
    this.ID = ID.equals(VCFConstants.EMPTY_ID_FIELD) ? VCFConstants.EMPTY_ID_FIELD : ID;

    this.commonInfo = new CommonInfo(source, log10PError, filters, attributes);
    REFERENCE_BASE_FOR_INDEL = referenceBaseForIndel;

    // todo -- remove me when this check is no longer necessary
    if (this.commonInfo.hasAttribute(ID_KEY))
      throw new IllegalArgumentException(
          "Trying to create a VariantContext with a ID key.  Please use provided constructor argument ID");

    if (alleles == null) {
      throw new IllegalArgumentException("Alleles cannot be null");
    }

    // we need to make this a LinkedHashSet in case the user prefers a given ordering of alleles
    this.alleles = makeAlleles(alleles);

    if (genotypes == null || genotypes == NO_GENOTYPES) {
      this.genotypes = NO_GENOTYPES;
    } else {
      this.genotypes = genotypes.immutable();
    }

    // cache the REF and ALT alleles
    int nAlleles = alleles.size();
    for (Allele a : alleles) {
      if (a.isReference()) {
        REF = a;
      } else if (nAlleles == 2) { // only cache ALT when biallelic
        ALT = a;
      }
    }

    if (!validationToPerform.isEmpty()) {
      validate(validationToPerform);
    }
  }
 // -------------------------------------------------------------------------
 @Override
 public boolean isEmpty() {
   return _logLevels.isEmpty() && !hasException();
 }
示例#29
0
  /**
   * Merges current node group state with state that came through a PATCH.
   *
   * <p>PATCH requests are sent from
   *
   * <p>1) local service to itself, after it has communicated with a peer, during maintenance.
   *
   * <p>2) A remote peer when its probing this local service, during its maintenance cycle
   *
   * <p>The key invariants that should not be violated, guaranteeing forward evolution of state even
   * if nodes only talk to a small portion of their peers:
   *
   * <p>- When a status changes, the change is accepted if the remote version is higher
   *
   * <p>- A local node is the only node that can change its own node entry status, for a PATCH that
   * it receives.
   *
   * <p>- A node should never increment the version of a node entry, for other nodes, unless that
   * node entry is marked UNAVAILABLE
   *
   * <p>- When a status changes during gossip version must be incremented - Versions always move
   * forward
   */
  private void mergeRemoteAndLocalMembership(
      NodeGroupState localState, NodeGroupState remotePeerState, EnumSet<NodeGroupChange> changes) {
    if (localState == null) {
      return;
    }

    boolean isSelfPatch = remotePeerState.documentOwner.equals(getHost().getId());
    long now = Utils.getNowMicrosUtc();

    NodeState selfEntry = localState.nodes.get(getHost().getId());

    for (NodeState remoteNodeEntry : remotePeerState.nodes.values()) {

      NodeState l = localState.nodes.get(remoteNodeEntry.id);
      boolean isLocalNode = remoteNodeEntry.id.equals(getHost().getId());

      if (!isSelfPatch && isLocalNode) {
        if (remoteNodeEntry.status != l.status) {
          logWarning(
              "Peer %s is reporting us as %s, current status: %s",
              remotePeerState.documentOwner, remoteNodeEntry.status, l.status);
          if (remoteNodeEntry.documentVersion > l.documentVersion) {
            // increment local version to re-enforce we are alive and well
            l.documentVersion = remoteNodeEntry.documentVersion;
            l.documentUpdateTimeMicros = now;
            changes.add(NodeGroupChange.SELF_CHANGE);
          }
        }
        // local instance of node group service is the only one that can update its own
        // status
        continue;
      }

      if (l == null) {
        boolean hasExpired =
            remoteNodeEntry.documentExpirationTimeMicros > 0
                && remoteNodeEntry.documentExpirationTimeMicros < now;
        if (hasExpired || NodeState.isUnAvailable(remoteNodeEntry)) {
          continue;
        }
        if (!isLocalNode) {
          logInfo(
              "Adding new peer %s (%s), status %s",
              remoteNodeEntry.id, remoteNodeEntry.groupReference, remoteNodeEntry.status);
        }
        // we found a new peer, through the gossip PATCH. Add to our state
        localState.nodes.put(remoteNodeEntry.id, remoteNodeEntry);
        changes.add(NodeGroupChange.PEER_ADDED);
        continue;
      }

      boolean needsUpdate = l.status != remoteNodeEntry.status;
      if (needsUpdate) {
        changes.add(NodeGroupChange.PEER_STATUS_CHANGE);
      }

      if (isSelfPatch && isLocalNode && needsUpdate) {
        // we sent a self PATCH to update our status. Move our version forward;
        remoteNodeEntry.documentVersion =
            Math.max(remoteNodeEntry.documentVersion, l.documentVersion) + 1;
      }

      // versions move forward only, ignore stale nodes
      if (remoteNodeEntry.documentVersion < l.documentVersion) {
        logInfo(
            "v:%d - q:%d, v:%d - q:%d , %s - %s (local:%s %d)",
            l.documentVersion,
            l.membershipQuorum,
            remoteNodeEntry.documentVersion,
            remoteNodeEntry.membershipQuorum,
            l.id,
            remotePeerState.documentOwner,
            getHost().getId(),
            selfEntry.documentVersion);
        continue;
      }

      if (remoteNodeEntry.documentVersion == l.documentVersion && needsUpdate) {
        // pick update with most recent time, even if that is prone to drift and jitter
        // between nodes
        if (remoteNodeEntry.documentUpdateTimeMicros < l.documentUpdateTimeMicros) {
          logWarning(
              "Ignoring update for %s from peer %s. Local status: %s, remote status: %s",
              remoteNodeEntry.id, remotePeerState.documentOwner, l.status, remoteNodeEntry.status);
          continue;
        }
      }

      if (remoteNodeEntry.status == NodeStatus.UNAVAILABLE
          && l.documentExpirationTimeMicros == 0
          && remoteNodeEntry.documentExpirationTimeMicros == 0) {
        remoteNodeEntry.documentExpirationTimeMicros =
            Utils.getNowMicrosUtc() + localState.config.nodeRemovalDelayMicros;
        logInfo(
            "Set expiration at %d for unavailable node %s(%s)",
            remoteNodeEntry.documentExpirationTimeMicros,
            remoteNodeEntry.id,
            remoteNodeEntry.groupReference);
        changes.add(NodeGroupChange.PEER_STATUS_CHANGE);
        needsUpdate = true;
      }

      if (remoteNodeEntry.status == NodeStatus.UNAVAILABLE && needsUpdate) {
        // nodes increment their own entry version, except, if they are unavailable
        remoteNodeEntry.documentVersion++;
      }

      localState.nodes.put(remoteNodeEntry.id, remoteNodeEntry);
    }

    List<String> missingNodes = new ArrayList<>();
    for (NodeState l : localState.nodes.values()) {
      NodeState r = remotePeerState.nodes.get(l.id);
      if (!NodeState.isUnAvailable(l) || l.id.equals(getHost().getId())) {
        continue;
      }

      long expirationMicros = l.documentExpirationTimeMicros;
      if (r != null) {
        expirationMicros = Math.max(l.documentExpirationTimeMicros, r.documentExpirationTimeMicros);
      }

      if (expirationMicros > 0 && now > expirationMicros) {
        changes.add(NodeGroupChange.PEER_STATUS_CHANGE);
        logInfo("Removing expired unavailable node %s(%s)", l.id, l.groupReference);
        missingNodes.add(l.id);
      }
    }

    for (String id : missingNodes) {
      localState.nodes.remove(id);
    }

    boolean isModified = !changes.isEmpty();
    localState.membershipUpdateTimeMicros =
        Math.max(
            remotePeerState.membershipUpdateTimeMicros,
            isModified ? now : localState.membershipUpdateTimeMicros);
    if (isModified) {
      logInfo(
          "State updated, merge with %s, self %s, %d",
          remotePeerState.documentOwner,
          localState.documentOwner,
          localState.membershipUpdateTimeMicros);
    }
  }
示例#30
0
    @Override
    public void readElement(final XMLExtendedStreamReader reader, final List<ModelNode> list)
        throws XMLStreamException {

      final ModelNode address = new ModelNode();
      address.add(org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM, JCA);
      address.protect();

      final ModelNode subsystem = new ModelNode();
      subsystem.get(OP).set(ADD);
      subsystem.get(OP_ADDR).set(address);
      list.add(subsystem);

      // Handle elements
      final EnumSet<Element> visited = EnumSet.noneOf(Element.class);
      final EnumSet<Element> requiredElement = EnumSet.of(Element.DEFAULT_WORKMANAGER);

      while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {

        switch (Namespace.forUri(reader.getNamespaceURI())) {
          case JCA_1_0:
            {
              final Element element = Element.forName(reader.getLocalName());
              if (!visited.add(element)) {
                throw unexpectedElement(reader);
              }

              switch (element) {
                case ARCHIVE_VALIDATION:
                  {
                    parseArchiveValidation(reader, subsystem);
                    break;
                  }
                case BEAN_VALIDATION:
                  {
                    parseBeanValidation(reader, subsystem);
                    break;
                  }
                case DEFAULT_WORKMANAGER:
                  {
                    parseDefaultWorkManager(reader, address, list, subsystem);
                    requiredElement.remove(Element.DEFAULT_WORKMANAGER);
                    break;
                  }
                case CACHED_CONNECTION_MANAGER:
                  {
                    parseCcm(reader, subsystem);
                    break;
                  }
                default:
                  throw unexpectedElement(reader);
              }
              break;
            }
          default:
            throw unexpectedElement(reader);
        }
      }
      if (!requiredElement.isEmpty()) {
        throw missingRequiredElement(reader, requiredElement);
      }
    }