Ejemplo n.º 1
0
  @SuppressWarnings("rawtypes")
  public static boolean isSirenProperty(Class<?> type, Object obj, Field field) {
    boolean isProp = false;

    Siren4JProperty anno = field.getAnnotation(Siren4JProperty.class);
    if (anno != null || type.isEnum()) {
      isProp = true;
    } else if (ArrayUtils.contains(propertyTypes, type)) {
      isProp = true;
    } else if (obj != null && Collection.class.isAssignableFrom(type)) {
      // Try to determine value type
      if (!((Collection) obj).isEmpty()) {
        Object first = findFirstNonNull(((Collection) obj).iterator());
        if (first == null || ArrayUtils.contains(propertyTypes, first.getClass())) {
          isProp = true;
        }
      }
    } else if (obj != null && Map.class.isAssignableFrom(type)) {
      // Try to determine value types of key and value
      if (!((Map) obj).isEmpty()) {
        Object firstKey = findFirstNonNull(((Map) obj).keySet().iterator());
        Object firstVal = findFirstNonNull(((Map) obj).entrySet().iterator());
        if ((firstKey == null || ArrayUtils.contains(propertyTypes, firstKey.getClass()))
            && (firstVal == null
                || ArrayUtils.contains(
                    propertyTypes, ((HashMap.Entry) firstVal).getValue().getClass()))) {
          isProp = true;
        }
      }
    }
    return isProp;
  }
Ejemplo n.º 2
0
 private void predicate(
     JPAQuery query,
     QSpecial special,
     Integer[] siteId,
     Integer[] categoryId,
     Date beginDate,
     Date endDate,
     Boolean isWithImage,
     Boolean isRecommend) {
   query.from(special);
   BooleanBuilder exp = new BooleanBuilder();
   if (ArrayUtils.isNotEmpty(siteId)) {
     exp = exp.and(special.site.id.in(siteId));
   }
   if (ArrayUtils.isNotEmpty(categoryId)) {
     exp = exp.and(special.category.id.in(categoryId));
   }
   if (beginDate != null) {
     exp = exp.and(special.creationDate.goe(beginDate));
   }
   if (endDate != null) {
     exp = exp.and(special.creationDate.goe(endDate));
   }
   if (isWithImage != null) {
     exp = exp.and(special.withImage.eq(isWithImage));
   }
   if (isRecommend != null) {
     exp = exp.and(special.recommend.eq(isRecommend));
   }
   query.where(exp);
 }
Ejemplo n.º 3
0
  public static final Map<String, String> unserializeQuery(byte[] inQueryBytes) {
    HashMap<String, String> queryMap = new HashMap<String, String>();
    int offset = 0;

    if (inQueryBytes == null || inQueryBytes.length < 4) return queryMap;

    do {
      int keyLength = (int) numberFromByteArray(inQueryBytes, offset, FIELD_BYTE_LENGTH, null);
      offset += FIELD_BYTE_LENGTH;

      byte[] charBytes = ArrayUtils.subarray(inQueryBytes, offset, offset + keyLength);
      String key = new String(charBytes);
      offset += charBytes.length;

      int valueLength = (int) numberFromByteArray(inQueryBytes, offset, FIELD_BYTE_LENGTH, null);
      offset += FIELD_BYTE_LENGTH;

      byte[] valueCharBytes = ArrayUtils.subarray(inQueryBytes, offset, offset + valueLength);
      String value = new String(valueCharBytes);
      offset += valueCharBytes.length;

      queryMap.put(key, value);
    } while (offset < inQueryBytes.length);

    return queryMap;
  }
  /**
   * 部署classpath下面的流程定义
   *
   * <p>从属性配置文件中获取属性<b>workflow.modules</b>扫描**deployments**
   *
   * <p>然后从每个**deployments/${module}**查找在属性配置文件中的属性**workflow.module.keys.${ submodule}**
   *
   * <p>配置实例:
   *
   * <p>
   *
   * <pre>
   * #workflow for deploy
   * workflow.modules=budget,erp,oa
   * workflow.module.keys.budget=budget
   * workflow.module.keys.erp=acceptInsurance,billing,effectInsurance,endorsement,payment
   * workflow.module.keys.oa=caruse,leave,officalstamp,officesupply,out,overtime
   * </pre>
   *
   * <p>
   *
   * @param processKey 流程定义KEY
   * @throws Exception
   */
  public void deployFromClasspath(String exportDir, String... processKey) throws Exception {
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    String[] processKeys = {"leave", "leave-dynamic-from", "leave-formkey", "dispatch"};
    for (String loopProcessKey : processKeys) {

      /*
       * 需要过滤指定流程
       */
      if (ArrayUtils.isNotEmpty(processKey)) {
        if (ArrayUtils.contains(processKey, loopProcessKey)) {
          logger.debug("hit module of {}", processKey);
          deploySingleProcess(resourceLoader, loopProcessKey, exportDir);
        } else {
          logger.debug(
              "module: {} not equals process key: {}, ignore and continue find next.",
              loopProcessKey,
              processKey);
        }
      } else {
        /*
         * 所有流程
         */
        deploySingleProcess(resourceLoader, loopProcessKey, exportDir);
      }
    }
  }
    private void retrieveMonitorDetails(final HttpResponse res) {
      Header[] headers = res.getHeaders(HttpHeader.LOCATION);
      if (ArrayUtils.isNotEmpty(headers)) {
        this.location = URI.create(headers[0].getValue());
      } else {
        throw new AsyncRequestException(
            "Invalid async request response. Monitor URL '" + headers[0].getValue() + "'");
      }

      headers = res.getHeaders(HttpHeader.RETRY_AFTER);
      if (ArrayUtils.isNotEmpty(headers)) {
        this.retryAfter = Integer.parseInt(headers[0].getValue());
      }

      headers = res.getHeaders(HttpHeader.PREFERENCE_APPLIED);
      if (ArrayUtils.isNotEmpty(headers)) {
        for (Header header : headers) {
          if (header.getValue().equalsIgnoreCase(new ODataPreferences().respondAsync())) {
            preferenceApplied = true;
          }
        }
      }
      try {
        EntityUtils.consume(res.getEntity());
      } catch (IOException ex) {
        Logger.getLogger(AsyncRequestWrapperImpl.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
Ejemplo n.º 6
0
 public ItemStack[] getLastActiveItems() {
   if (this.inventory.currentItem == -1)
     return ArrayUtils.addAll(new ItemStack[] {null}, this.inventory.armorInventory);
   return ArrayUtils.addAll(
       new ItemStack[] {this.inventory.mainInventory[this.inventory.currentItem]},
       this.inventory.armorInventory);
 }
Ejemplo n.º 7
0
 @Override
 public String onKill(NpcInstance npc, QuestState st) {
   int npcId = npc.getNpcId();
   int cond = st.getCond();
   if (cond == 3) {
     if (ArrayUtils.contains(SOD, npcId)) {
       st.rollAndGive(
           FleetSteedTroupsTotem,
           (int) Config.RATE_QUESTS_REWARD * 1,
           17); // Шанс на глаз и с потолка. Умножается на рейт квестов и делится на кол-во членов
       // группы. Для нас это (nRate*3)/9
     } else if (ArrayUtils.contains(SOI, npcId)) {
       st.rollAndGive(
           NucleusofanIncompleteSoul,
           (int) Config.RATE_QUESTS_REWARD * 1,
           17); // Шанс на глаз и с потолка. Умножается на рейт квестов и делится на кол-во членов
       // группы. Для нас это (nRate*3)/9
     } else if (ArrayUtils.contains(SOA, npcId)) {
       st.rollAndGive(
           SpiritStoneDust,
           (int) Config.RATE_QUESTS_REWARD * 1,
           20); // Шанс на глаз и с потолка. Умножается на рейт квестов и делится на кол-во членов
       // группы. Для нас это (nRate*3)/9
     }
   }
   return null;
 }
Ejemplo n.º 8
0
 public SparseMatrixRow(ValueConf vconf, int rowIndex, LinkedHashMap<Integer, Float> row) {
   this(
       vconf,
       rowIndex,
       ArrayUtils.toPrimitive(row.keySet().toArray(new Integer[] {})),
       ArrayUtils.toPrimitive(row.values().toArray(new Float[] {})));
 }
  /**
   * Replace a single conditional compilation variable
   *
   * @param variable something like "@_win32"
   * @return the value
   */
  private static String replaceOneVariable(
      final String variable, final BrowserVersion browserVersion) {
    final String[] varNaN = {
      "@_win16", "@_mac", "@_alpha", "@_mc680x0", "@_PowerPC", "@_debug", "@_fast"
    };
    final String[] varTrue = {"@_win32", "@_x86", "@_jscript"};

    if (ArrayUtils.contains(varTrue, variable)) {
      return "true";
    } else if ("@_jscript_version".equals(variable)) {
      if (browserVersion.getBrowserVersionNumeric() <= 6) {
        return "5.6";
      } else if (browserVersion.getBrowserVersionNumeric() == 7) {
        return "5.7";
      }
      return "5.8";
    } else if ("@_jscript_build".equals(variable)) {
      if (browserVersion.getBrowserVersionNumeric() <= 6) {
        return "6626";
      }
      if (browserVersion.getBrowserVersionNumeric() == 7) {
        return "5730";
      }
      return "18702";
    } else if (ArrayUtils.contains(varNaN, variable)) {
      return "NaN";
    }
    return variable;
  }
Ejemplo n.º 10
0
  /**
   * @param cmd
   * @param dir
   * @param out
   * @param err
   * @param env
   * @return
   */
  private CommandResult exec(
      String[] pCmd, File dir, StringWriter pOut, StringWriter pErr, String[] env)
      throws IOException, InterruptedException {

    int out = 0;
    String pCmdString = ArrayUtils.toString(pCmd);
    if (_log.isDebugEnabled())
      _log.debug(
          "Executing '" + pCmdString + "' with Environment '" + ArrayUtils.toString(env) + "'");
    StopWatch clock = new StopWatch();
    clock.start();
    try {
      process = Runtime.getRuntime().exec(pCmd, env, dir);
      out = handleProcess(process, pCmdString, pOut, pErr, _outputList, sig_interrupt);
    } finally {
      this.cleanUpProcess();
      clock.stop();
      if (_log.isInfoEnabled()) _log.info("'" + pCmd + "' completed in " + clock.getTime() + " ms");
    }
    if (sig_interrupt.getValue() == true) {
      out = -9999;
    }
    CommandResult result = new CommandResult(pCmdString, out, pOut.toString(), pErr.toString());
    return result;
  }
Ejemplo n.º 11
0
    /** Main method that responds to mouseClick events. */
    public void mouseClicked(MouseEvent arg0) {
      if (errListModel.getSize() > 0
          && !errorsList.isSelectionEmpty()
          && !correctionsList.isSelectionEmpty()) {

        String correction = correctionsList.getSelectedValue();
        String error = errorsList.getSelectedValue();

        char[] inputAsChars = text.getText().toCharArray();
        int errIndex = getErrorIndex(error, inputAsChars);

        for (int i = 0; i < error.length(); i++) {
          inputAsChars = ArrayUtils.remove(inputAsChars, errIndex);
        }

        for (int i = 0; i < correction.length(); i++) {
          inputAsChars =
              ArrayUtils.add(
                  inputAsChars, errIndex, correction.charAt(correction.length() - i - 1));
        }

        correctionsListModel.clear();
        errListModel.clear();

        text.setText(new String(inputAsChars));
      }
    }
 public SeedOfAnnihilationInstance(int objectId, NpcTemplate template) {
   super(objectId, template);
   if (ArrayUtils.contains(BISTAKON_MOBS, template.getNpcId()))
     addMinions(BISTAKON_MINIONS[Rnd.get(BISTAKON_MINIONS.length)], template);
   else if (ArrayUtils.contains(COKRAKON_MOBS, template.getNpcId()))
     addMinions(COKRAKON_MINIONS[Rnd.get(COKRAKON_MINIONS.length)], template);
 }
Ejemplo n.º 13
0
  @Override
  public void addSessionId(final String sessionId) {

    try {

      final String[] ids = getProperty(Principal.sessionIds);
      if (ids != null) {

        if (!ArrayUtils.contains(ids, sessionId)) {

          setProperty(
              Principal.sessionIds,
              (String[]) ArrayUtils.add(getProperty(Principal.sessionIds), sessionId));
        }

      } else {

        setProperty(Principal.sessionIds, new String[] {sessionId});
      }

    } catch (FrameworkException ex) {
      logger.log(
          Level.SEVERE, "Could not add sessionId " + sessionId + " to array of sessionIds", ex);
    }
  }
Ejemplo n.º 14
0
    @Override
    protected String[] transformInternal(Attribute attr) throws Exception {
      String attrId = attr.getId();

      return (this.binaryAttrDetector.isBinary(attrId)
          ? ArrayUtils.toArray(getBinaryAttributeId(attrId), attrId)
          : ArrayUtils.toArray(attrId));
    }
 @Override
 public void dumpSystemStatus(String eventName, boolean logAsDebug) {
   if (logAsDebug) {
     log.debug(eventName + " " + ArrayUtils.toString(getSystemStatus()));
   } else {
     log.info(eventName + " " + ArrayUtils.toString(getSystemStatus()));
   }
 }
Ejemplo n.º 16
0
 @Override
 public void update(Care care) throws Exception {
   // TODO Auto-generated method stub
   Object[] params = care.toArray();
   params = ArrayUtils.remove(params, 2);
   params = ArrayUtils.add(params, care.getId());
   update(
       "update care set theme=?, object=?, next=?, way=?, people=?, note=? where id = ?", params);
 }
Ejemplo n.º 17
0
  public QueryParams addParam(String name, String... values) {
    String[] oldValues = params.get(name);
    if (ArrayUtils.isNotEmpty(oldValues)) {
      values = ArrayUtils.addAll(oldValues, values);
    }

    params.put(name, values);

    return this;
  }
Ejemplo n.º 18
0
  /** 1 - Restore View {@inheritDoc} */
  @Override
  public void restoreState(FacesContext context, Object state) {

    values = (Object[]) state;
    log.info(
        "UIOtp.restoreState() "
            + ArrayUtils.toString(ArrayUtils.subarray(values, 1, values.length)));

    super.restoreState(context, values[0]);
    forComponents = (String) values[1];
  }
Ejemplo n.º 19
0
 private static void writeBlocksToNBT(
     NBTTagCompound tagCompound, BlockMeta[] blocks, String name) {
   List<Integer> ids = new ArrayList<Integer>(blocks.length);
   List<Integer> meta = new ArrayList<Integer>(blocks.length);
   for (BlockMeta t : blocks) {
     ids.add(Block.blockRegistry.getIDForObject(t.getBlock()));
     meta.add((int) t.getMeta());
   }
   tagCompound.setIntArray(name, ArrayUtils.toPrimitive(ids.toArray(new Integer[ids.size()])));
   tagCompound.setIntArray(
       name + "_meta", ArrayUtils.toPrimitive(meta.toArray(new Integer[meta.size()])));
 }
Ejemplo n.º 20
0
 public void sendPacket(
     Packet packetIn, GenericFutureListener listener, GenericFutureListener... listeners) {
   if (this.channel != null && this.channel.isOpen()) {
     this.flushOutboundQueue();
     this.dispatchPacket(
         packetIn, (GenericFutureListener[]) ArrayUtils.add(listeners, 0, listener));
   } else {
     this.outboundPacketsQueue.add(
         new NetworkManager.InboundHandlerTuplePacketListener(
             packetIn, (GenericFutureListener[]) ArrayUtils.add(listeners, 0, listener)));
   }
 }
Ejemplo n.º 21
0
  @Override
  public List<T> listQuery(String condition, Object[] params, Integer start, Integer max) {
    StringBuilder sql = new StringBuilder("select * from ").append(getTable());
    if (StringUtils.isNotBlank(condition)) {
      sql.append(" where ").append(condition);
    }

    if (start != null && max != null && start >= 0 && max > 0) {
      sql.append(" limit ?,?");
      params = ArrayUtils.add(params, start);
      params = ArrayUtils.add(params, max);
    }
    return query(sql.toString(), new MyBeanListHandler<T>(this.clazz), params);
  }
Ejemplo n.º 22
0
  public void a(Packet var1, GenericFutureListener var2, GenericFutureListener... var3) {
    if (g()) {
      m();
      this.a(var1, ArrayUtils.add(var3, 0, var2));
    } else {
      j.writeLock().lock();

      try {
        i.add(new class_ek.class_a_in_class_ek(var1, ArrayUtils.add(var3, 0, var2)));
      } finally {
        j.writeLock().unlock();
      }
    }
  }
Ejemplo n.º 23
0
  /** Try and convert an object to a List. */
  private List<?> toList(Object o) {
    Class<?> c = o.getClass();
    if (!c.isArray()) {
      return null;
    }

    if (c.getComponentType().isPrimitive()) {
      if (o instanceof boolean[]) {
        return Arrays.asList(ArrayUtils.toObject((boolean[]) o));
      } else if (o instanceof byte[]) {
        return Arrays.asList(ArrayUtils.toObject((byte[]) o));
      } else if (o instanceof short[]) {
        return Arrays.asList(ArrayUtils.toObject((short[]) o));
      } else if (o instanceof int[]) {
        return Arrays.asList(ArrayUtils.toObject((int[]) o));
      } else if (o instanceof long[]) {
        return Arrays.asList(ArrayUtils.toObject((long[]) o));
      } else if (o instanceof float[]) {
        return Arrays.asList(ArrayUtils.toObject((float[]) o));
      } else if (o instanceof double[]) {
        return Arrays.asList(ArrayUtils.toObject((double[]) o));
      } else if (o instanceof char[]) {
        return Arrays.asList(ArrayUtils.toObject((char[]) o));
      } else {
        throw new RuntimeException("Unhandled primitive type");
      }
    } else {
      return Arrays.asList((Object[]) o);
    }
  }
Ejemplo n.º 24
0
  public QueryParams addParam(String name, String value) {
    String[] oldValues = params.get(name);
    String[] values;

    if (ArrayUtils.isNotEmpty(oldValues)) {
      values = ArrayUtils.add(oldValues, value);
    } else {
      values = new String[1];
      values[0] = value;
    }

    params.put(name, values);

    return this;
  }
Ejemplo n.º 25
0
  // Declare parameters
  @Parameters(name = "{index}: {0}")
  public static Iterable<Object[]> data() {
    System.out.println("Working Directory = " + System.getProperty("user.dir"));
    File currentDir = new File(System.getProperty("user.dir"));
    String rootPath = new File(currentDir, "src/test/resources/models/sbml-test-cases").getPath();
    // Get all the SBML files
    LinkedList<String> sbmlPaths = walk(rootPath);

    int N = sbmlPaths.size();
    System.out.println("Number of SBML test cases: " + N);
    Object[][] resources = new String[N][1];
    for (int k = 0; k < N; k++) {
      String path = sbmlPaths.get(k);
      // create the resource
      String[] items = path.split("/");
      int mindex = -1;
      for (int i = 0; i < items.length; i++) {
        if (items[i].equals("models")) {
          mindex = i;
          break;
        }
      }
      String resource = StringUtils.join(ArrayUtils.subarray(items, mindex, items.length), "/");
      // System.out.println(resource);
      resources[k][0] = "/" + resource; // String.format("/models/BiGG/%s", fname);
    }
    return Arrays.asList(resources);
  }
Ejemplo n.º 26
0
 @Override
 public ImmoXmlVersion getPreviousVersion() {
   ImmoXmlVersion[] versions = ImmoXmlVersion.values();
   int pos = ArrayUtils.indexOf(versions, this);
   pos--;
   return (pos >= 0) ? versions[pos] : null;
 }
Ejemplo n.º 27
0
 @Override
 public ImmoXmlVersion getNextVersion() {
   ImmoXmlVersion[] versions = ImmoXmlVersion.values();
   int pos = ArrayUtils.indexOf(versions, this);
   pos++;
   return (versions.length > pos) ? versions[pos] : null;
 }
Ejemplo n.º 28
0
 @Override
 public void onCommand(GenericMessageEvent event, CallInfo callInfo, String[] args) {
   if (args.length < 1) {
     event.respond("Not enough arguments.");
     return;
   }
   if (args[0].equalsIgnoreCase("help")) {
     event.respond(Colors.BOLD + "Channel Preferences Help");
     event.respond("preferences [channel] set [option] [value] (values...)");
     return;
   }
   if (args.length < 2) {
     event.respond("Not enough arguments.");
     return;
   }
   final String channel = args[0], subcommand = args[1];
   if (channel.charAt(0) != '#') {
     event.respond("Channel did not start with \"#\"");
     return;
   }
   String[] subcommandArgs = ArrayUtils.subarray(args, 2, args.length);
   if (subcommand.equalsIgnoreCase("set"))
     set(event, new ChannelPreferences(channel), subcommandArgs);
   else event.respond("Unknown subcommand!");
 }
Ejemplo n.º 29
0
  /**
   * Encodes the given array of bytes using the Base64 encoding algorithm.
   *
   * @param bytesToEncode the array of bytes to encode
   * @return a new array of encoded bytes
   */
  public static byte[] encode(byte[] bytesToEncode) {
    if (ArrayUtils.isEmpty(bytesToEncode)) {
      return new byte[0];
    }

    return ENCODER.encode(bytesToEncode).getBytes();
  }
    @Override
    public R getODataResponse() {
      HttpResponse res = null;
      for (int i = 0; response == null && i < MAX_RETRY; i++) {
        res = checkMonitor(location);

        if (res.getStatusLine().getStatusCode() == HttpStatusCode.ACCEPTED.getStatusCode()) {

          final Header[] headers = res.getHeaders(HttpHeader.RETRY_AFTER);
          if (ArrayUtils.isNotEmpty(headers)) {
            this.retryAfter = Integer.parseInt(headers[0].getValue());
          }

          try {
            // wait for retry-after
            Thread.sleep(retryAfter * 1000);
          } catch (InterruptedException ignore) {
            // ignore
          }

        } else {
          location = null;
          return instantiateResponse(res);
        }
      }

      if (response == null) {
        throw new ODataClientErrorException(res == null ? null : res.getStatusLine());
      }

      return response;
    }