private Number incrValue(int dir) {
    Number newValue;
    if ((value instanceof Float) || (value instanceof Double)) {
      double v = value.doubleValue() + (stepSize.doubleValue() * (double) dir);
      if (value instanceof Double) {
        newValue = new Double(v);
      } else {
        newValue = new Float(v);
      }
    } else {
      long v = value.longValue() + (stepSize.longValue() * (long) dir);

      if (value instanceof Long) {
        newValue = new Long(v);
      } else if (value instanceof Integer) {
        newValue = new Integer((int) v);
      } else if (value instanceof Short) {
        newValue = new Short((short) v);
      } else {
        newValue = new Byte((byte) v);
      }
    }

    if ((maximum != null) && (maximum.compareTo(newValue) < 0)) {
      return null;
    }
    if ((minimum != null) && (minimum.compareTo(newValue) > 0)) {
      return null;
    } else {
      return newValue;
    }
  }
示例#2
0
  protected void prepare(
      Map stormConf, final TopologyContext context, final IOutputCollector collector) {

    _rand = new Random();
    _collector = collector;

    _context = context;

    heartbeatTimeoutMills = getHeartbeatTimeoutMillis(stormConf);

    _process = new NuShellProcess(_command, this, this);

    // subprocesses must send their pid first thing
    Number subpid = _process.launch(stormConf, context);
    LOG.info("Launched subprocess with pid " + subpid);
    this.pid = subpid.longValue();

    /**
     * randomizing the initial delay would prevent all shell bolts from heartbeating at the same
     * time frame
     */
    int initialDelayMillis = random.nextInt(4000) + 1000;
    BoltHeartbeatTimerTask task = new BoltHeartbeatTimerTask(this);
    heartBeatExecutorService.scheduleAtFixedRate(
        task, initialDelayMillis, getHeartbeatPeriodMillis(stormConf), TimeUnit.MILLISECONDS);
  }
示例#3
0
  private void writeNumber(Number obj, Buffer buf) {
    long value = obj.longValue();

    if (value >= -32 && value <= Byte.MAX_VALUE) {
      // Integer
      if (T) Log.trace("writing Integer value: " + value);
      buf.writeI8((byte) value);
    } else if (value >= Byte.MIN_VALUE && value < -32) {
      if (T) Log.trace("writing I8 value: " + value);
      buf.writeI8(TYPE_I8);
      buf.writeI8((byte) value);
    } else if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) {
      // I16
      if (T) Log.trace("writing I16 value: " + value);
      buf.writeI8(TYPE_I16);
      buf.writeI16((short) value);
    } else if (value >= Integer.MIN_VALUE && value <= Integer.MAX_VALUE) {
      // I32
      if (T) Log.trace("writing I32 value: " + value);
      buf.writeI8(TYPE_I32);
      buf.writeI32((int) value);
    } else {
      // I64
      if (T) Log.trace("writing I64 value: " + value);
      buf.writeI8(TYPE_I64);
      buf.writeI64(value);
    }
  }
示例#4
0
 @Override
 public long getLong(final String key) {
   final Number number = this.extractNumber(this.findLastTag(key));
   if (number == null) {
     return 0L;
   }
   return number.longValue();
 }
示例#5
0
 /**
  * Looks up the given key in the given map, converting the result into a {@link Long}. First,
  * {@link #getNumber(Map,Object)} is invoked. If the result is null, then null is returned.
  * Otherwise, the long value of the resulting {@link Number} is returned.
  *
  * @param map the map whose value to look up
  * @param key the key whose value to look up in that map
  * @return a {@link Long} or null
  */
 public static Long getLong(Map map, Object key) {
   Number answer = getNumber(map, key);
   if (answer == null) {
     return null;
   } else if (answer instanceof Long) {
     return (Long) answer;
   }
   return new Long(answer.longValue());
 }
示例#6
0
  /**
   * Overrides the parent implementation to provide a more efficient mechanism for generating
   * primary keys, while generating the primary key support on the fly.
   *
   * @param count the batch size
   * @param entity the entity requesting primary keys
   * @param channel open JDBCChannel
   * @return NSArray of NSDictionary where each dictionary corresponds to a unique primary key value
   */
  public NSArray newPrimaryKeys(int count, EOEntity entity, JDBCChannel channel) {
    if (isPrimaryKeyGenerationNotSupported(entity)) {
      return null;
    }

    EOAttribute attribute = (EOAttribute) entity.primaryKeyAttributes().lastObject();
    String attrName = attribute.name();
    boolean isIntType = "i".equals(attribute.valueType());

    NSMutableArray results = new NSMutableArray(count);
    String sequenceName = sequenceNameForEntity(entity);
    DB2Expression expression = new DB2Expression(entity);

    boolean succeeded = false;
    for (int tries = 0; !succeeded && tries < 2; tries++) {
      while (results.count() < count) {
        try {
          StringBuffer sql = new StringBuffer();
          sql.append("SELECT ");
          sql.append("next value for " + sequenceName + " AS KEY");
          sql.append(" from sysibm.sysdummy1");
          expression.setStatement(sql.toString());
          channel.evaluateExpression(expression);
          try {
            NSDictionary row;
            while ((row = channel.fetchRow()) != null) {
              Enumeration pksEnum = row.allValues().objectEnumerator();
              while (pksEnum.hasMoreElements()) {
                Number pkObj = (Number) pksEnum.nextElement();
                Number pk;
                if (isIntType) {
                  pk = Integer.valueOf(pkObj.intValue());
                } else {
                  pk = Long.valueOf(pkObj.longValue());
                }
                results.addObject(new NSDictionary(pk, attrName));
              }
            }
          } finally {
            channel.cancelFetch();
          }
          succeeded = true;
        } catch (JDBCAdaptorException ex) {
          throw ex;
        }
      }
    }

    if (results.count() != count) {
      throw new IllegalStateException(
          "Unable to generate primary keys from the sequence for " + entity + ".");
    }

    return results;
  }
示例#7
0
 private String convertNumber(Number number) {
   if (Integer.class.isInstance(number)) {
     return NumericUtils.intToPrefixCoded(number.intValue());
   } else if (Double.class.isInstance(number)) {
     return NumericUtils.doubleToPrefixCoded(number.doubleValue());
   } else if (Long.class.isInstance(number)) {
     return NumericUtils.longToPrefixCoded(number.longValue());
   } else if (Float.class.isInstance(number)) {
     return NumericUtils.floatToPrefixCoded(number.floatValue());
   } else if (Byte.class.isInstance(number)) {
     return NumericUtils.intToPrefixCoded(number.intValue());
   } else if (Short.class.isInstance(number)) {
     return NumericUtils.intToPrefixCoded(number.intValue());
   } else if (BigDecimal.class.isInstance(number)) {
     return NumericUtils.doubleToPrefixCoded(number.doubleValue());
   } else if (BigInteger.class.isInstance(number)) {
     return NumericUtils.longToPrefixCoded(number.longValue());
   } else {
     throw new IllegalArgumentException("Unsupported numeric type " + number.getClass().getName());
   }
 }
示例#8
0
文件: URL.java 项目: yungoo/apple-qos
 public long getParameter(String key, long defaultValue) {
   Number n = getNumbers().get(key);
   if (n != null) {
     return n.longValue();
   }
   String value = getParameter(key);
   if (value == null || value.length() == 0) {
     return defaultValue;
   }
   long l = Long.parseLong(value);
   getNumbers().put(key, l);
   return l;
 }
 protected int putNumber(String name, Number n) {
   int start = _buf.position();
   if (n instanceof Integer) {
     _put(NUMBER_INT, name);
     _buf.putInt(n.intValue());
   } else if (n instanceof Long) {
     _put(NUMBER_LONG, name);
     _buf.putLong(n.longValue());
   } else {
     _put(NUMBER, name);
     _buf.putDouble(n.doubleValue());
   }
   return _buf.position() - start;
 }
示例#10
0
 protected void putNumber(String name, Number n) {
   if (n instanceof Integer
       || n instanceof Short
       || n instanceof Byte
       || n instanceof AtomicInteger) {
     _put(NUMBER_INT, name);
     _buf.writeInt(n.intValue());
   } else if (n instanceof Long || n instanceof AtomicLong) {
     _put(NUMBER_LONG, name);
     _buf.writeLong(n.longValue());
   } else if (n instanceof Float || n instanceof Double) {
     _put(NUMBER, name);
     _buf.writeDouble(n.doubleValue());
   } else {
     throw new IllegalArgumentException("can't serialize " + n.getClass());
   }
 }
示例#11
0
 public RexNode toRex(Expression expression) {
   switch (expression.getNodeType()) {
     case MemberAccess:
       return rexBuilder.makeFieldAccess(
           toRex(((MemberExpression) expression).expression),
           ((MemberExpression) expression).field.getName());
     case GreaterThan:
       return binary(expression, SqlStdOperatorTable.greaterThanOperator);
     case LessThan:
       return binary(expression, SqlStdOperatorTable.lessThanOperator);
     case Parameter:
       return parameter((ParameterExpression) expression);
     case Call:
       MethodCallExpression call = (MethodCallExpression) expression;
       SqlOperator operator = RexToLixTranslator.JAVA_TO_SQL_METHOD_MAP.get(call.method);
       if (operator != null) {
         return rexBuilder.makeCall(
             operator,
             toRex(
                 Expressions.<Expression>list()
                     .appendIfNotNull(call.targetExpression)
                     .appendAll(call.expressions)));
       }
       throw new RuntimeException("Could translate call to method " + call.method);
     case Constant:
       final ConstantExpression constant = (ConstantExpression) expression;
       Object value = constant.value;
       if (value instanceof Number) {
         Number number = (Number) value;
         if (value instanceof Double || value instanceof Float) {
           return rexBuilder.makeApproxLiteral(BigDecimal.valueOf(number.doubleValue()));
         } else if (value instanceof BigDecimal) {
           return rexBuilder.makeExactLiteral((BigDecimal) value);
         } else {
           return rexBuilder.makeExactLiteral(BigDecimal.valueOf(number.longValue()));
         }
       } else if (value instanceof Boolean) {
         return rexBuilder.makeLiteral((Boolean) value);
       } else {
         return rexBuilder.makeLiteral(constant.toString());
       }
     default:
       throw new UnsupportedOperationException(
           "unknown expression type " + expression.getNodeType() + " " + expression);
   }
 }
示例#12
0
  public long saveGroup(Group group) throws IOException {
    MapSqlParameterSource params = new MapSqlParameterSource();
    params.addValue("name", group.getName()).addValue("description", group.getDescription());

    if (group.getGroupId() == Group.UNSAVED_ID) {
      SimpleJdbcInsert insert =
          new SimpleJdbcInsert(template)
              .withTableName("_Group")
              .usingGeneratedKeyColumns("groupId");
      Number newId = insert.executeAndReturnKey(params);
      group.setGroupId(newId.longValue());
    } else {
      params.addValue("groupId", group.getGroupId());
      NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(template);
      namedTemplate.update(GROUP_UPDATE, params);
    }

    return group.getGroupId();
  }
 @Override
 public long hash(Number v) {
   // have to use a bit of reflection to ensure good hash values since
   // we don't have truely type specific stats
   if (v instanceof Long) {
     return hasher.hashLong(v.longValue()).asLong();
   } else if (v instanceof Integer) {
     return hasher.hashInt(v.intValue()).asLong();
   } else if (v instanceof Double) {
     return hasher.hashLong(Double.doubleToRawLongBits(v.doubleValue())).asLong();
   } else if (v instanceof Float) {
     return hasher.hashInt(Float.floatToRawIntBits(v.floatValue())).asLong();
   } else if (v instanceof Byte) {
     return hasher.newHasher().putByte(v.byteValue()).hash().asLong();
   } else if (v instanceof Short) {
     return hasher.newHasher().putShort(v.shortValue()).hash().asLong();
   }
   // else...
   throw new SolrException(
       SolrException.ErrorCode.SERVER_ERROR,
       "Unsupported Numeric Type (" + v.getClass() + ") for hashing: " + statsField);
 }
示例#14
0
  @Transactional(readOnly = false, rollbackFor = IOException.class)
  @TriggersRemove(
      cacheName = {"userCache", "lazyUserCache"},
      keyGenerator =
          @KeyGenerator(
              name = "HashCodeCacheKeyGenerator",
              properties = {
                @Property(name = "includeMethod", value = "false"),
                @Property(name = "includeParameterTypes", value = "false")
              }))
  public long saveUser(User user) throws IOException {
    Blob roleBlob = null;
    if (user.getRoles() != null) {
      List<String> roles = new ArrayList<String>(Arrays.asList(user.getRoles()));
      if (user.isExternal() && !roles.contains("ROLE_EXTERNAL")) roles.add("ROLE_EXTERNAL");
      if (user.isInternal() && !roles.contains("ROLE_INTERNAL")) roles.add("ROLE_INTERNAL");
      if (user.isAdmin() && !roles.contains("ROLE_ADMIN")) roles.add("ROLE_ADMIN");
      user.setRoles(roles.toArray(new String[user.getRoles().length]));

      try {
        if (user.getRoles().length > 0) {
          byte[] rbytes = LimsUtils.join(user.getRoles(), ",").getBytes();
          roleBlob = new SerialBlob(rbytes);
        }
      } catch (SerialException e) {
        e.printStackTrace();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }

    MapSqlParameterSource params = new MapSqlParameterSource();
    params
        .addValue("active", user.isActive())
        .addValue("admin", user.isAdmin())
        .addValue("external", user.isExternal())
        .addValue("fullName", user.getFullName())
        .addValue("internal", user.isInternal())
        .addValue("loginName", user.getLoginName())
        .addValue("roles", roleBlob)
        .addValue("email", user.getEmail());

    if (passwordCodecService != null) {
      params.addValue("password", passwordCodecService.encrypt(user.getPassword()));
    } else {
      log.warn(
          "No PasswordCodecService has been wired to this SQLSecurityDAO. This means your passwords may be being "
              + "stored in plaintext, if not already encrypted. Please specify a PasswordCodecService in your Spring config and (auto)wire it "
              + "to this DAO.");
      params.addValue("password", user.getPassword());
    }

    if (user.getUserId() == UserImpl.UNSAVED_ID) {
      SimpleJdbcInsert insert =
          new SimpleJdbcInsert(template).withTableName("User").usingGeneratedKeyColumns("userId");
      Number newId = insert.executeAndReturnKey(params);
      user.setUserId(newId.longValue());
    } else {
      params.addValue("userId", user.getUserId());
      NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(template);
      namedTemplate.update(USER_UPDATE, params);
    }

    // sort User_Group

    // delete existing joins
    MapSqlParameterSource delparams = new MapSqlParameterSource();
    delparams.addValue("userId", user.getUserId());
    NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(template);
    namedTemplate.update(USER_GROUP_DELETE_BY_USER_ID, delparams);

    if (user.getGroups() != null && !user.getGroups().isEmpty()) {
      SimpleJdbcInsert eInsert = new SimpleJdbcInsert(template).withTableName("User_Group");
      for (Group g : user.getGroups()) {
        MapSqlParameterSource ugParams = new MapSqlParameterSource();
        ugParams
            .addValue("users_userId", user.getUserId())
            .addValue("groups_groupId", g.getGroupId());

        eInsert.execute(ugParams);
      }
    }

    return user.getUserId();
  }