@Override
  public void readFrom(StreamInput in) throws IOException {
    super.readFrom(in);
    if (in.getVersion().before(Version.V_1_4_0)) {
      // term vector used to read & write the index twice, here and in the parent class
      in.readString();
    }
    type = in.readString();
    id = in.readString();

    if (in.getVersion().onOrAfter(Version.V_1_4_0)) {
      if (in.readBoolean()) {
        doc = in.readBytesReference();
      }
    }
    routing = in.readOptionalString();
    preference = in.readOptionalString();
    long flags = in.readVLong();

    flagsEnum.clear();
    for (Flag flag : Flag.values()) {
      if ((flags & (1 << flag.ordinal())) != 0) {
        flagsEnum.add(flag);
      }
    }
    int numSelectedFields = in.readVInt();
    if (numSelectedFields > 0) {
      selectedFields = new HashSet<>();
      for (int i = 0; i < numSelectedFields; i++) {
        selectedFields.add(in.readString());
      }
    }
  }
 private void setFlag(Flag flag, boolean set) {
   if (set && !flagsEnum.contains(flag)) {
     flagsEnum.add(flag);
   } else if (!set) {
     flagsEnum.remove(flag);
     assert (!flagsEnum.contains(flag));
   }
 }
예제 #3
0
 public static EnumSet<AcSentMessageTypeEnum> collectFromCodes(Collection<String> v) {
   if (v == null) return null;
   EnumSet<AcSentMessageTypeEnum> set = newEnumSet();
   for (String s : v) {
     AcSentMessageTypeEnum e = _AcSentMessageTypeEnum._m.get(s);
     if (e != null) set.add(e);
   }
   return set;
 }
예제 #4
0
  @Override
  public void setModeEnabled(TerminalMode mode, boolean enabled) {
    if (enabled) {
      myModes.add(mode);
    } else {
      myModes.remove(mode);
    }

    mode.setEnabled(this, enabled);
  }
 public static EnumSet<AcUspsDomesticRouteStatusStatusEnum> collectFromCodes(
     Collection<String> v) {
   if (v == null) return null;
   EnumSet<AcUspsDomesticRouteStatusStatusEnum> set = newEnumSet();
   for (String s : v) {
     AcUspsDomesticRouteStatusStatusEnum e = _AcUspsDomesticRouteStatusStatusEnum._m.get(s);
     if (e != null) set.add(e);
   }
   return set;
 }
 public static EnumSet<AcUspsInternationalClaimLegTypeEnum> collectFromCodes(
     Collection<String> v) {
   if (v == null) return null;
   EnumSet<AcUspsInternationalClaimLegTypeEnum> set = newEnumSet();
   for (String s : v) {
     AcUspsInternationalClaimLegTypeEnum e = _AcUspsInternationalClaimLegTypeEnum._m.get(s);
     if (e != null) set.add(e);
   }
   return set;
 }
 public static EnumSet<AcUspsInternationalCandidateRouteOfferHistoryStatusEnum> collectFromCodes(
     Collection<String> v) {
   if (v == null) return null;
   EnumSet<AcUspsInternationalCandidateRouteOfferHistoryStatusEnum> set = newEnumSet();
   for (String s : v) {
     AcUspsInternationalCandidateRouteOfferHistoryStatusEnum e =
         _AcUspsInternationalCandidateRouteOfferHistoryStatusEnum._m.get(s);
     if (e != null) set.add(e);
   }
   return set;
 }
예제 #8
0
 private static void printBufferObjectChecks(
     PrintWriter writer, ExecutableElement method, Mode mode, boolean context_specific) {
   EnumSet<BufferKind> check_set = EnumSet.noneOf(BufferKind.class);
   for (VariableElement param : method.getParameters()) {
     BufferObject bo_annotation = param.getAnnotation(BufferObject.class);
     if (bo_annotation != null) {
       check_set.add(bo_annotation.value());
     }
   }
   for (BufferKind kind : check_set) {
     printBufferObjectCheck(writer, kind, mode, context_specific);
   }
 }
예제 #9
0
  public Collection<BUS_PERMISSION> getPermissions(String user) {
    if (isBusConfigField(user)) {
      throw new IllegalArgumentException("Invalid user name: " + user);
    }

    String perms = get(user);
    EnumSet<BUS_PERMISSION> result = EnumSet.noneOf(BUS_PERMISSION.class);
    if (StringUtils.isNotBlank(perms)) {
      for (String perm : perms.split(",")) {
        result.add(BUS_PERMISSION.valueOf(perm));
      }
    }
    return result;
  }
예제 #10
0
  // TODO: [AH] this should be pre-initialized in ObjectTemplate
  private EnumSet<AttributeType> getAttributeTypesAfter(
      final ObjectTemplate objectTemplate, final AttributeType attributeType) {
    final EnumSet<AttributeType> beforeAttributes = EnumSet.noneOf(AttributeType.class);
    final List<AttributeTemplate> attributeTemplates = objectTemplate.getAttributeTemplates();

    for (int i = 0; i < attributeTemplates.size(); i++) {
      final AttributeType templateType = attributeTemplates.get(i).getAttributeType();

      if (templateType == attributeType) {
        for (; i < attributeTemplates.size(); i++) {
          beforeAttributes.add(attributeTemplates.get(i).getAttributeType());
        }
      }
    }
    return beforeAttributes;
  }
예제 #11
0
  /**
   * Parses a list of tags from the command line, assuming it comes from the GATK Engine tags, and
   * returns the corresponding EnumSet.
   *
   * @param arg the actual engine arg, used for the UserException if there's an error
   * @param tags a list of string tags that should be converted to the MissingPedField value
   * @return
   */
  public static final EnumSet<MissingPedField> parseMissingFieldTags(
      final Object arg, final List<String> tags) {
    final EnumSet<MissingPedField> missingFields = EnumSet.noneOf(MissingPedField.class);

    for (final String tag : tags) {
      try {
        missingFields.add(MissingPedField.valueOf(tag));
      } catch (IllegalArgumentException e) {
        throw new UserException.BadArgumentValue(
            arg.toString(),
            "Unknown tag " + tag + " allowed values are " + MissingPedField.values());
      }
    }

    return missingFields;
  }
예제 #12
0
    static EnumSet<FileAttribute> parse(String s) {
      if (s == null || s.length() == 0) {
        return EnumSet.allOf(FileAttribute.class);
      }

      EnumSet<FileAttribute> set = EnumSet.noneOf(FileAttribute.class);
      FileAttribute[] attributes = values();
      for (char c : s.toCharArray()) {
        int i = 0;
        for (; i < attributes.length && c != attributes[i].symbol; i++) ;
        if (i < attributes.length) {
          if (!set.contains(attributes[i])) {
            set.add(attributes[i]);
          } else {
            throw new IllegalArgumentException(
                "There are more than one '" + attributes[i].symbol + "' in " + s);
          }
        } else {
          throw new IllegalArgumentException("'" + c + "' in " + s + " is undefined.");
        }
      }
      return set;
    }
예제 #13
0
 private void add(Cycle cycle) {
   cycles.add(cycle);
 }
예제 #14
0
 protected void paintEvent(WPaintDevice paintDevice) {
   if (!(this.chart_ != null) || !this.chart_.cObjCreated_) {
     return;
   }
   if (this.chart_.getSeries(this.seriesColumn_).getType() != SeriesType.LineSeries
       && this.chart_.getSeries(this.seriesColumn_).getType() != SeriesType.CurveSeries) {
     if (this.getMethod() == WPaintedWidget.Method.HtmlCanvas) {
       StringBuilder ss = new StringBuilder();
       ss.append("jQuery.removeData(").append(this.getJsRef()).append(",'sobj');");
       ss.append("\nif (")
           .append(this.getObjJsRef())
           .append(") {")
           .append(this.getObjJsRef())
           .append(".canvas.style.cursor = 'auto';")
           .append("setTimeout(")
           .append(this.getObjJsRef())
           .append(".repaint,0);}\n");
       this.doJavaScript(ss.toString());
     }
     logger.error(
         new StringWriter()
             .append("WAxisSliderWidget is not associated with a line or curve series.")
             .toString());
     return;
   }
   WPainter painter = new WPainter(paintDevice);
   boolean horizontal = this.chart_.getOrientation() == Orientation.Vertical;
   double w = horizontal ? this.getWidth().getValue() : this.getHeight().getValue();
   double h = horizontal ? this.getHeight().getValue() : this.getWidth().getValue();
   boolean autoPadding = this.autoPadding_;
   if (autoPadding
       && EnumUtils.mask(paintDevice.getFeatures(), WPaintDevice.FeatureFlag.HasFontMetrics)
           .equals(0)
       && this.labelsEnabled_) {
     logger.error(
         new StringWriter()
             .append(
                 "setAutoLayout(): device does not have font metrics (not even server-side font metrics).")
             .toString());
     autoPadding = false;
   }
   if (autoPadding) {
     if (horizontal) {
       if (this.labelsEnabled_) {
         this.setSelectionAreaPadding(0, EnumSet.of(Side.Top));
         this.setSelectionAreaPadding(
             (int)
                 (this.chart_
                         .getAxis(Axis.XAxis)
                         .calcMaxTickLabelSize(paintDevice, Orientation.Vertical)
                     + 10),
             EnumSet.of(Side.Bottom));
         this.setSelectionAreaPadding(
             (int)
                 Math.max(
                     this.chart_
                             .getAxis(Axis.XAxis)
                             .calcMaxTickLabelSize(paintDevice, Orientation.Horizontal)
                         / 2,
                     10.0),
             EnumSet.of(Side.Left, Side.Right));
       } else {
         this.setSelectionAreaPadding(0, EnumSet.of(Side.Top));
         this.setSelectionAreaPadding(5, EnumSet.of(Side.Left, Side.Right, Side.Bottom));
       }
     } else {
       if (this.labelsEnabled_) {
         this.setSelectionAreaPadding(0, EnumSet.of(Side.Right));
         this.setSelectionAreaPadding(
             (int)
                 Math.max(
                     this.chart_
                             .getAxis(Axis.XAxis)
                             .calcMaxTickLabelSize(paintDevice, Orientation.Vertical)
                         / 2,
                     10.0),
             EnumSet.of(Side.Top, Side.Bottom));
         this.setSelectionAreaPadding(
             (int)
                 (this.chart_
                         .getAxis(Axis.XAxis)
                         .calcMaxTickLabelSize(paintDevice, Orientation.Horizontal)
                     + 10),
             EnumSet.of(Side.Left));
       } else {
         this.setSelectionAreaPadding(0, EnumSet.of(Side.Right));
         this.setSelectionAreaPadding(5, EnumSet.of(Side.Top, Side.Bottom, Side.Left));
       }
     }
   }
   double left =
       horizontal
           ? this.getSelectionAreaPadding(Side.Left)
           : this.getSelectionAreaPadding(Side.Top);
   double right =
       horizontal
           ? this.getSelectionAreaPadding(Side.Right)
           : this.getSelectionAreaPadding(Side.Bottom);
   double top =
       horizontal
           ? this.getSelectionAreaPadding(Side.Top)
           : this.getSelectionAreaPadding(Side.Right);
   double bottom =
       horizontal
           ? this.getSelectionAreaPadding(Side.Bottom)
           : this.getSelectionAreaPadding(Side.Left);
   double maxW = w - left - right;
   WRectF drawArea = new WRectF(left, 0, maxW, h);
   List<WAxis.Segment> segmentsBak =
       new ArrayList<WAxis.Segment>(this.chart_.getAxis(Axis.XAxis).segments_);
   double renderIntervalBak = this.chart_.getAxis(Axis.XAxis).renderInterval_;
   this.chart_
       .getAxis(Axis.XAxis)
       .prepareRender(
           horizontal ? Orientation.Horizontal : Orientation.Vertical, drawArea.getWidth());
   final WRectF chartArea = this.chart_.chartArea_;
   WRectF selectionRect = null;
   {
     double u =
         -this.chart_.xTransformHandle_.getValue().getDx()
             / (chartArea.getWidth() * this.chart_.xTransformHandle_.getValue().getM11());
     selectionRect = new WRectF(0, top, maxW, h - (top + bottom));
     this.transform_.setValue(
         new WTransform(
             1 / this.chart_.xTransformHandle_.getValue().getM11(), 0, 0, 1, u * maxW, 0));
   }
   WRectF seriesArea = new WRectF(left, top + 5, maxW, h - (top + bottom + 5));
   WTransform selectionTransform =
       this.hv(new WTransform(1, 0, 0, 1, left, 0).multiply(this.transform_.getValue()));
   WRectF rect = selectionTransform.map(this.hv(selectionRect));
   painter.fillRect(this.hv(new WRectF(left, top, maxW, h - top - bottom)), this.background_);
   painter.fillRect(rect, this.selectedAreaBrush_);
   final double TICK_LENGTH = 5;
   final double ANGLE1 = 15;
   final double ANGLE2 = 80;
   double tickStart = 0.0;
   double tickEnd = 0.0;
   double labelPos = 0.0;
   AlignmentFlag labelHFlag = AlignmentFlag.AlignCenter;
   AlignmentFlag labelVFlag = AlignmentFlag.AlignMiddle;
   final WAxis axis = this.chart_.getAxis(Axis.XAxis);
   if (horizontal) {
     tickStart = 0;
     tickEnd = TICK_LENGTH;
     labelPos = TICK_LENGTH;
     labelVFlag = AlignmentFlag.AlignTop;
   } else {
     tickStart = -TICK_LENGTH;
     tickEnd = 0;
     labelPos = -TICK_LENGTH;
     labelHFlag = AlignmentFlag.AlignRight;
   }
   if (horizontal) {
     if (axis.getLabelAngle() > ANGLE1) {
       labelHFlag = AlignmentFlag.AlignRight;
       if (axis.getLabelAngle() > ANGLE2) {
         labelVFlag = AlignmentFlag.AlignMiddle;
       }
     } else {
       if (axis.getLabelAngle() < -ANGLE1) {
         labelHFlag = AlignmentFlag.AlignLeft;
         if (axis.getLabelAngle() < -ANGLE2) {
           labelVFlag = AlignmentFlag.AlignMiddle;
         }
       }
     }
   } else {
     if (axis.getLabelAngle() > ANGLE1) {
       labelVFlag = AlignmentFlag.AlignBottom;
       if (axis.getLabelAngle() > ANGLE2) {
         labelHFlag = AlignmentFlag.AlignCenter;
       }
     } else {
       if (axis.getLabelAngle() < -ANGLE1) {
         labelVFlag = AlignmentFlag.AlignTop;
         if (axis.getLabelAngle() < -ANGLE2) {
           labelHFlag = AlignmentFlag.AlignCenter;
         }
       }
     }
   }
   EnumSet<AxisProperty> axisProperties = EnumSet.of(AxisProperty.Line);
   if (this.labelsEnabled_) {
     axisProperties.add(AxisProperty.Labels);
   }
   if (horizontal) {
     axis.render(
         painter,
         axisProperties,
         new WPointF(drawArea.getLeft(), h - bottom),
         new WPointF(drawArea.getRight(), h - bottom),
         tickStart,
         tickEnd,
         labelPos,
         EnumSet.of(labelHFlag, labelVFlag));
     WPainterPath line = new WPainterPath();
     line.moveTo(drawArea.getLeft() + 0.5, h - (bottom - 0.5));
     line.lineTo(drawArea.getRight(), h - (bottom - 0.5));
     painter.strokePath(line, this.chart_.getAxis(Axis.XAxis).getPen());
   } else {
     axis.render(
         painter,
         axisProperties,
         new WPointF(this.getSelectionAreaPadding(Side.Left) - 1, drawArea.getLeft()),
         new WPointF(this.getSelectionAreaPadding(Side.Left) - 1, drawArea.getRight()),
         tickStart,
         tickEnd,
         labelPos,
         EnumSet.of(labelHFlag, labelVFlag));
     WPainterPath line = new WPainterPath();
     line.moveTo(this.getSelectionAreaPadding(Side.Left) - 0.5, drawArea.getLeft() + 0.5);
     line.lineTo(this.getSelectionAreaPadding(Side.Left) - 0.5, drawArea.getRight());
     painter.strokePath(line, this.chart_.getAxis(Axis.XAxis).getPen());
   }
   WPainterPath curve = new WPainterPath();
   {
     WTransform t =
         new WTransform(1, 0, 0, 1, seriesArea.getLeft(), seriesArea.getTop())
             .multiply(
                 new WTransform(
                     seriesArea.getWidth() / chartArea.getWidth(),
                     0,
                     0,
                     seriesArea.getHeight() / chartArea.getHeight(),
                     0,
                     0))
             .multiply(new WTransform(1, 0, 0, 1, -chartArea.getLeft(), -chartArea.getTop()));
     if (!horizontal) {
       t.assign(
           new WTransform(
                   0,
                   1,
                   1,
                   0,
                   this.getSelectionAreaPadding(Side.Left)
                       - this.getSelectionAreaPadding(Side.Right)
                       - 5,
                   0)
               .multiply(t)
               .multiply(new WTransform(0, 1, 1, 0, 0, 0)));
     }
     curve.assign(t.map(this.chart_.pathForSeries(this.seriesColumn_)));
   }
   {
     WRectF leftHandle = this.hv(new WRectF(-5, top, 5, h - top - bottom));
     WTransform t =
         new WTransform(1, 0, 0, 1, left, -top)
             .multiply(
                 new WTransform()
                     .translate(this.transform_.getValue().map(selectionRect.getTopLeft())));
     painter.fillRect(this.hv(t).map(leftHandle), this.handleBrush_);
   }
   {
     WRectF rightHandle = this.hv(new WRectF(0, top, 5, h - top - bottom));
     WTransform t =
         new WTransform(1, 0, 0, 1, left, -top)
             .multiply(
                 new WTransform()
                     .translate(this.transform_.getValue().map(selectionRect.getTopRight())));
     painter.fillRect(this.hv(t).map(rightHandle), this.handleBrush_);
   }
   if (this.selectedSeriesPen_ != this.seriesPen_
       && !this.selectedSeriesPen_.equals(this.seriesPen_)) {
     WPainterPath clipPath = new WPainterPath();
     clipPath.addRect(this.hv(selectionRect));
     painter.setClipPath(selectionTransform.map(clipPath));
     painter.setClipping(true);
     painter.setPen(this.getSelectedSeriesPen());
     painter.drawPath(curve);
     WPainterPath leftClipPath = new WPainterPath();
     leftClipPath.addRect(
         this.hv(new WTransform(1, 0, 0, 1, -selectionRect.getWidth(), 0).map(selectionRect)));
     painter.setClipPath(
         this.hv(
                 new WTransform(1, 0, 0, 1, left, -top)
                     .multiply(
                         new WTransform()
                             .translate(
                                 this.transform_.getValue().map(selectionRect.getTopLeft()))))
             .map(leftClipPath));
     painter.setPen(this.getSeriesPen());
     painter.drawPath(curve);
     WPainterPath rightClipPath = new WPainterPath();
     rightClipPath.addRect(
         this.hv(new WTransform(1, 0, 0, 1, selectionRect.getWidth(), 0).map(selectionRect)));
     painter.setClipPath(
         this.hv(
                 new WTransform(1, 0, 0, 1, left - selectionRect.getRight(), -top)
                     .multiply(
                         new WTransform()
                             .translate(
                                 this.transform_.getValue().map(selectionRect.getTopRight()))))
             .map(rightClipPath));
     painter.drawPath(curve);
     painter.setClipping(false);
   } else {
     painter.setPen(this.getSeriesPen());
     painter.drawPath(curve);
   }
   if (this.getMethod() == WPaintedWidget.Method.HtmlCanvas) {
     WApplication app = WApplication.getInstance();
     StringBuilder ss = new StringBuilder();
     ss.append("new Wt3_3_5.WAxisSliderWidget(")
         .append(app.getJavaScriptClass())
         .append(",")
         .append(this.getJsRef())
         .append(",")
         .append(this.getObjJsRef())
         .append(",")
         .append("{chart:")
         .append(this.chart_.getCObjJsRef())
         .append(",transform:")
         .append(this.transform_.getJsRef())
         .append(",rect:function(){return ")
         .append(rect.getJsRef())
         .append("},drawArea:")
         .append(drawArea.getJsRef())
         .append(",series:")
         .append(this.seriesColumn_)
         .append("});");
     this.doJavaScript(ss.toString());
   }
   Utils.copyList(segmentsBak, this.chart_.getAxis(Axis.XAxis).segments_);
   this.chart_.getAxis(Axis.XAxis).renderInterval_ = renderIntervalBak;
 }
예제 #15
0
 @Override
 public void addImpactLevel(eROMImpact impact) {
   reImpacts.add(impact);
 }
예제 #16
0
  /**
   * Checks a function for RESTFful annotations.
   *
   * @return {@code true} if module contains relevant annotations
   * @throws QueryException query exception
   */
  boolean analyze() throws QueryException {
    // parse all annotations
    final EnumSet<HTTPMethod> mth = EnumSet.noneOf(HTTPMethod.class);
    final boolean[] declared = new boolean[function.args.length];
    boolean found = false;
    final int as = function.ann.size();
    for (int a = 0; a < as; a++) {
      final QNm name = function.ann.names[a];
      final Value value = function.ann.values[a];
      final byte[] local = name.local();
      final byte[] uri = name.uri();
      final boolean rexq = eq(uri, QueryText.RESTXQURI);
      if (rexq) {
        if (eq(PATH, local)) {
          // annotation "path"
          if (path != null) error(ANN_TWICE, "%", name.string());
          path = new RestXqPath(toString(value, name));
          for (final String s : path) {
            if (s.trim().startsWith("{")) checkVariable(s, AtomType.AAT, declared);
          }
        } else if (eq(CONSUMES, local)) {
          // annotation "consumes"
          strings(value, name, consumes);
        } else if (eq(PRODUCES, local)) {
          // annotation "produces"
          strings(value, name, produces);
        } else if (eq(QUERY_PARAM, local)) {
          // annotation "query-param"
          queryParams.add(param(value, name, declared));
        } else if (eq(FORM_PARAM, local)) {
          // annotation "form-param"
          formParams.add(param(value, name, declared));
        } else if (eq(HEADER_PARAM, local)) {
          // annotation "header-param"
          headerParams.add(param(value, name, declared));
        } else if (eq(COOKIE_PARAM, local)) {
          // annotation "cookie-param"
          cookieParams.add(param(value, name, declared));
        } else {
          // method annotations
          final HTTPMethod m = HTTPMethod.get(string(local));
          if (m == null) error(ANN_UNKNOWN, "%", name.string());
          if (!value.isEmpty()) {
            // remember post/put variable
            if (requestBody != null) error(ANN_TWICE, "%", name.string());
            if (m != POST && m != PUT) error(METHOD_VALUE, m);
            requestBody = checkVariable(toString(value, name), declared);
          }
          if (mth.contains(m)) error(ANN_TWICE, "%", name.string());
          mth.add(m);
        }
      } else if (eq(uri, QueryText.OUTPUTURI)) {
        // serialization parameters
        final String key = string(local);
        final String val = toString(value, name);
        if (output.get(key) == null) error(UNKNOWN_SER, key);
        output.set(key, val);
      }
      found |= rexq;
    }
    if (!mth.isEmpty()) methods = mth;

    if (found) {
      if (path == null) error(ANN_MISSING, PATH);
      for (int i = 0; i < declared.length; i++)
        if (!declared[i]) error(VAR_UNDEFINED, function.args[i].name.string());
    }
    return found;
  }
  /** Initialize constants and try to collect information about the JVM internals. */
  static {
    // Initialize empirically measured defaults. We'll modify them to the current
    // JVM settings later on if possible.
    int referenceSize = Constants.JRE_IS_64BIT ? 8 : 4;
    int objectHeader = Constants.JRE_IS_64BIT ? 16 : 8;
    // The following is objectHeader + NUM_BYTES_INT, but aligned (object alignment)
    // so on 64 bit JVMs it'll be align(16 + 4, @8) = 24.
    int arrayHeader = Constants.JRE_IS_64BIT ? 24 : 12;

    supportedFeatures = EnumSet.noneOf(JvmFeature.class);

    Class<?> unsafeClass = null;
    Object tempTheUnsafe = null;
    try {
      unsafeClass = Class.forName("sun.misc.Unsafe");
      final Field unsafeField = unsafeClass.getDeclaredField("theUnsafe");
      unsafeField.setAccessible(true);
      tempTheUnsafe = unsafeField.get(null);
    } catch (Exception e) {
      // Ignore.
    }
    theUnsafe = tempTheUnsafe;

    // get object reference size by getting scale factor of Object[] arrays:
    try {
      final Method arrayIndexScaleM = unsafeClass.getMethod("arrayIndexScale", Class.class);
      referenceSize = ((Number) arrayIndexScaleM.invoke(theUnsafe, Object[].class)).intValue();
      supportedFeatures.add(JvmFeature.OBJECT_REFERENCE_SIZE);
    } catch (Exception e) {
      // ignore.
    }

    // "best guess" based on reference size. We will attempt to modify
    // these to exact values if there is supported infrastructure.
    objectHeader = Constants.JRE_IS_64BIT ? (8 + referenceSize) : 8;
    arrayHeader = Constants.JRE_IS_64BIT ? (8 + 2 * referenceSize) : 12;

    // get the object header size:
    // - first try out if the field offsets are not scaled (see warning in Unsafe docs)
    // - get the object header size by getting the field offset of the first field of a dummy object
    // If the scaling is byte-wise and unsafe is available, enable dynamic size measurement for
    // estimateRamUsage().
    Method tempObjectFieldOffsetMethod = null;
    try {
      final Method objectFieldOffsetM = unsafeClass.getMethod("objectFieldOffset", Field.class);
      final Field dummy1Field = DummyTwoLongObject.class.getDeclaredField("dummy1");
      final int ofs1 = ((Number) objectFieldOffsetM.invoke(theUnsafe, dummy1Field)).intValue();
      final Field dummy2Field = DummyTwoLongObject.class.getDeclaredField("dummy2");
      final int ofs2 = ((Number) objectFieldOffsetM.invoke(theUnsafe, dummy2Field)).intValue();
      if (Math.abs(ofs2 - ofs1) == NUM_BYTES_LONG) {
        final Field baseField = DummyOneFieldObject.class.getDeclaredField("base");
        objectHeader = ((Number) objectFieldOffsetM.invoke(theUnsafe, baseField)).intValue();
        supportedFeatures.add(JvmFeature.FIELD_OFFSETS);
        tempObjectFieldOffsetMethod = objectFieldOffsetM;
      }
    } catch (Exception e) {
      // Ignore.
    }
    objectFieldOffsetMethod = tempObjectFieldOffsetMethod;

    // Get the array header size by retrieving the array base offset
    // (offset of the first element of an array).
    try {
      final Method arrayBaseOffsetM = unsafeClass.getMethod("arrayBaseOffset", Class.class);
      // we calculate that only for byte[] arrays, it's actually the same for all types:
      arrayHeader = ((Number) arrayBaseOffsetM.invoke(theUnsafe, byte[].class)).intValue();
      supportedFeatures.add(JvmFeature.ARRAY_HEADER_SIZE);
    } catch (Exception e) {
      // Ignore.
    }

    NUM_BYTES_OBJECT_REF = referenceSize;
    NUM_BYTES_OBJECT_HEADER = objectHeader;
    NUM_BYTES_ARRAY_HEADER = arrayHeader;

    // Try to get the object alignment (the default seems to be 8 on Hotspot,
    // regardless of the architecture).
    int objectAlignment = 8;
    try {
      final Class<?> beanClazz = Class.forName("com.sun.management.HotSpotDiagnosticMXBean");
      // Try to get the diagnostic mxbean without calling {@link
      // ManagementFactory#getPlatformMBeanServer()}
      // which starts AWT thread (and shows junk in the dock) on a Mac:
      Object hotSpotBean;
      // Java 7+, HotSpot
      try {
        hotSpotBean =
            ManagementFactory.class
                .getMethod("getPlatformMXBean", Class.class)
                .invoke(null, beanClazz);
      } catch (Exception e1) {
        // Java 6, HotSpot
        try {
          Class<?> sunMF = Class.forName("sun.management.ManagementFactory");
          hotSpotBean = sunMF.getMethod("getDiagnosticMXBean").invoke(null);
        } catch (Exception e2) {
          // Last resort option is an attempt to get it from ManagementFactory's server anyway (may
          // start AWT).
          hotSpotBean =
              ManagementFactory.newPlatformMXBeanProxy(
                  ManagementFactory.getPlatformMBeanServer(),
                  "com.sun.management:type=HotSpotDiagnostic",
                  beanClazz);
        }
      }
      if (hotSpotBean != null) {
        final Method getVMOptionMethod = beanClazz.getMethod("getVMOption", String.class);
        final Object vmOption = getVMOptionMethod.invoke(hotSpotBean, "ObjectAlignmentInBytes");
        objectAlignment =
            Integer.parseInt(vmOption.getClass().getMethod("getValue").invoke(vmOption).toString());
        supportedFeatures.add(JvmFeature.OBJECT_ALIGNMENT);
      }
    } catch (Exception e) {
      // Ignore.
    }

    NUM_BYTES_OBJECT_ALIGNMENT = objectAlignment;

    JVM_INFO_STRING =
        "[JVM: "
            + Constants.JVM_NAME
            + ", "
            + Constants.JVM_VERSION
            + ", "
            + Constants.JVM_VENDOR
            + ", "
            + Constants.JAVA_VENDOR
            + ", "
            + Constants.JAVA_VERSION
            + "]";
  }
예제 #18
0
    static Arguments valueOf(String[] args, Configuration conf) throws IOException {
      List<Path> srcs = new ArrayList<Path>();
      Path dst = null;
      Path log = null;
      EnumSet<Options> flags = EnumSet.noneOf(Options.class);
      String presevedAttributes = null;
      String mapredSslConf = null;
      long filelimit = Long.MAX_VALUE;
      long sizelimit = Long.MAX_VALUE;

      for (int idx = 0; idx < args.length; idx++) {
        Options[] opt = Options.values();
        int i = 0;
        for (; i < opt.length && !args[idx].startsWith(opt[i].cmd); i++) ;

        if (i < opt.length) {
          flags.add(opt[i]);
          if (opt[i] == Options.PRESERVE_STATUS) {
            presevedAttributes = args[idx].substring(2);
            FileAttribute.parse(presevedAttributes); // validation
          } else if (opt[i] == Options.FILE_LIMIT) {
            filelimit = Options.FILE_LIMIT.parseLong(args, ++idx);
          } else if (opt[i] == Options.SIZE_LIMIT) {
            sizelimit = Options.SIZE_LIMIT.parseLong(args, ++idx);
          }
        } else if ("-f".equals(args[idx])) {
          if (++idx == args.length) {
            throw new IllegalArgumentException("urilist_uri not specified in -f");
          }
          srcs.addAll(fetchFileList(conf, new Path(args[idx])));
        } else if ("-log".equals(args[idx])) {
          if (++idx == args.length) {
            throw new IllegalArgumentException("logdir not specified in -log");
          }
          log = new Path(args[idx]);
        } else if ("-mapredSslConf".equals(args[idx])) {
          if (++idx == args.length) {
            throw new IllegalArgumentException("ssl conf file not specified in -mapredSslConf");
          }
          mapredSslConf = args[idx];
        } else if ("-m".equals(args[idx])) {
          if (++idx == args.length) {
            throw new IllegalArgumentException("num_maps not specified in -m");
          }
          try {
            conf.setInt(MAX_MAPS_LABEL, Integer.valueOf(args[idx]));
          } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Invalid argument to -m: " + args[idx]);
          }
        } else if ('-' == args[idx].codePointAt(0)) {
          throw new IllegalArgumentException("Invalid switch " + args[idx]);
        } else if (idx == args.length - 1) {
          dst = new Path(args[idx]);
        } else {
          srcs.add(new Path(args[idx]));
        }
      }
      // mandatory command-line parameters
      if (srcs.isEmpty() || dst == null) {
        throw new IllegalArgumentException("Missing " + (dst == null ? "dst path" : "src"));
      }
      // incompatible command-line flags
      final boolean isOverwrite = flags.contains(Options.OVERWRITE);
      final boolean isUpdate = flags.contains(Options.UPDATE);
      final boolean isDelete = flags.contains(Options.DELETE);
      if (isOverwrite && isUpdate) {
        throw new IllegalArgumentException("Conflicting overwrite policies");
      }
      if (isDelete && !isOverwrite && !isUpdate) {
        throw new IllegalArgumentException(
            Options.DELETE.cmd
                + " must be specified with "
                + Options.OVERWRITE
                + " or "
                + Options.UPDATE
                + ".");
      }
      return new Arguments(
          srcs, dst, log, flags, presevedAttributes, filelimit, sizelimit, mapredSslConf);
    }