Exemplo n.º 1
0
  private double[] fetchDatas(String conditions, String type, int minute) {
    long time = (System.currentTimeMillis()) / 1000 / 60;
    int endMinute = (int) (time % (60)) - DATA_AREADY_MINUTE;
    int startMinute = endMinute - minute;
    double[] datas = null;

    if (startMinute < 0 && endMinute < 0) {
      String period = m_sdf.format(queryDayPeriod(-1).getTime());
      CommandQueryEntity queryEntity = new CommandQueryEntity(period + ";" + conditions + ";;");
      datas = ArrayUtils.toPrimitive(m_appDataService.queryValue(queryEntity, type), 0);
    } else if (startMinute < 0 && endMinute >= 0) {
      String last = m_sdf.format(queryDayPeriod(-1).getTime());
      String current = m_sdf.format(queryDayPeriod(0).getTime());
      CommandQueryEntity lastQueryEntity = new CommandQueryEntity(last + ";" + conditions + ";;");
      CommandQueryEntity currentQueryEntity =
          new CommandQueryEntity(current + ";" + conditions + ";;");
      double[] lastDatas =
          ArrayUtils.toPrimitive(m_appDataService.queryValue(lastQueryEntity, type), 0);
      double[] currentDatas =
          ArrayUtils.toPrimitive(m_appDataService.queryValue(currentQueryEntity, type), 0);
      datas = mergerArray(lastDatas, currentDatas);
    } else if (startMinute >= 0) {
      String period = m_sdf.format(queryDayPeriod(0).getTime());
      CommandQueryEntity queryEntity = new CommandQueryEntity(period + ";" + conditions + ";;");
      datas = ArrayUtils.toPrimitive(m_appDataService.queryValue(queryEntity, type), 0);
    }
    return datas;
  }
 @AuthorizeOperations(operations = {GooruOperationConstants.OPERATION_TASK_MANAGEMENT_READ})
 @Transactional(
     readOnly = false,
     propagation = Propagation.REQUIRED,
     rollbackFor = Exception.class)
 @RequestMapping(
     method = RequestMethod.GET,
     value = {"/{tid}/item/{id}"})
 public ModelAndView getTaskResourceAssociatedItem(
     @PathVariable(TID) String taskId,
     @PathVariable(ID) String resourceAssocId,
     @RequestParam(value = DATA_OBJECT, required = false) String data,
     HttpServletRequest request,
     HttpServletResponse response)
     throws Exception {
   TaskResourceAssoc taskResourceAssoc =
       this.getTaskService().getTaskResourceAssociatedItem(resourceAssocId);
   String[] includeFields = null;
   if (data != null && !data.isEmpty()) {
     JSONObject json = requestData(data);
     includeFields = getValue(FIELDS, json) != null ? getFields(getValue(FIELDS, json)) : null;
   }
   String[] includes =
       (String[])
           ArrayUtils.addAll(
               includeFields == null ? TASK_RESOURCE_ASSOC_INCLUDES : includeFields,
               ERROR_INCLUDE);
   includes = (String[]) ArrayUtils.addAll(includes, RESOURCE_INCLUDE_FIELDS);
   return toModelAndViewWithIoFilter(
       taskResourceAssoc, RESPONSE_FORMAT_JSON, EXCLUDE_ALL, includes);
 }
Exemplo n.º 3
0
 /**
  * 功能:获取除去占比经营数据总收的其它图例
  *
  * <p>作者 杨荣忠 2015-1-19 下午05:04:21
  *
  * @param conditionEntity
  * @return
  */
 public static String[] getZhabiDetach(ConditionEntity conditionEntity) {
   String[] array = getDimensionAll(conditionEntity);
   String[] result = (String[]) ArrayUtils.removeElement(array, ALL_COST);
   result = (String[]) ArrayUtils.removeElement(result, OTHER_ALL_COST);
   String[] result_add = (String[]) ArrayUtils.add(result, OTHER);
   return result_add;
 }
  public static Integer findIdColumn(String[] headings) {
    int idCol = -1;

    idCol = ArrayUtils.indexOf(headings, "local_id");
    if (idCol > -1) {
      return idCol;
    }

    idCol = ArrayUtils.indexOf(headings, "mrb_id");
    if (idCol > -1) {
      return idCol;
    }

    idCol = ArrayUtils.indexOf(headings, "waterid");
    if (idCol > -1) {
      return idCol;
    }

    idCol = ArrayUtils.indexOf(headings, "reach");
    if (idCol > -1) {
      return idCol;
    }

    return -1;
  }
Exemplo n.º 5
0
  /**
   * 分页语句 SELECT * FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY OrderDate) RowNum, * FROM Orders WHERE
   * OrderDate >= '1980-01-01' ) RowConstrainedResult WHERE RowNum >= 1 AND RowNum < 20 ORDER BY
   * RowNum
   */
  @Override
  public StatementWrapper pageStatement(
      String orderCol, String direction, int start, int limit, String strSQL, Object... values) {
    int indexFrom = StringUtils.indexOfIgnoreCase(strSQL, " FROM ");

    if (orderCol.contains(".")) {
      orderCol = orderCol.replaceAll("\\.", "\".\"");
    }
    orderCol = orderCol.toUpperCase();

    StringBuffer sbSQL =
        new StringBuffer("SELECT * FROM (")
            .append(strSQL.substring(0, indexFrom))
            .append(", ROW_NUMBER() OVER (ORDER BY \"")
            .append(orderCol)
            .append("\" ")
            .append(direction)
            .append(") ")
            .append(COLUMN_ROW_NUMBER)
            .append(strSQL.substring(indexFrom))
            .append(") WHERE ")
            .append(COLUMN_ROW_NUMBER)
            .append(" >= ? ");
    if (limit > 0) {
      sbSQL.append(" AND ").append(COLUMN_ROW_NUMBER).append(" <= ? ");
      values = ArrayUtils.addAll(values, new Object[] {start, start + limit});
    } else {
      values = ArrayUtils.add(values, start);
    }
    return new StatementWrapper(sbSQL.toString(), values);
  }
Exemplo n.º 6
0
  /**
   * Checks every node if it is essential for the network to be connected (i.e., the node is a
   * failure node). In each step, the network is prepared by setting all removed nodes (incl. the
   * one that is currently examined) to be iteration-path blocking and the iteration is then started
   * with a node that is known exist. All nodes that have their essentiality flag switched on are
   * then added to an array that is returned.
   *
   * @param removeArrayIndices An ArrayList of Integers (indices of the {@link nodeIndices} array)
   *     that should be considered as removed from the network, i.e. are not transversible by {@link
   *     iterateNetwork()}. An empty list can also be supplied and means that no nodes are removed.
   * @return An array of node indices that were determined to be failure points.
   */
  public int[] getFailureNodes(ArrayList<Integer> removeArrayIndices) {
    // array to capture whether node at nodeIndices[i] is essential or not
    boolean nodeEssential[] = new boolean[nodeIndices.length];

    // loop through nodes that are not removed with removeNodeIndices
    for (int curArrayIndex = 0; curArrayIndex < nodeIndices.length; curArrayIndex++) {
      if (removeArrayIndices.contains((Integer) curArrayIndex)) {
        continue;
      }
      // set current and all nodes in removeNodeIndices to visited
      boolean nodeReachable[] = new boolean[nodeIndices.length];
      nodeReachable[curArrayIndex] = true;
      for (int arrayIdx : removeArrayIndices) {
        nodeReachable[arrayIdx] = true;
      }
      // start iteration at a non-visited node and check if all were reached
      iterateNetwork(ArrayUtils.indexOf(nodeReachable, false), nodeReachable);
      nodeEssential[curArrayIndex] = ArrayUtils.indexOf(nodeReachable, false) != -1;
    }

    // return array with node indices that are essential (=failure points)
    ArrayList failureNodes = new ArrayList<Integer>();
    for (int curArrayIndex = 0; curArrayIndex < nodeEssential.length; curArrayIndex++) {
      if (nodeEssential[curArrayIndex] == true) {
        failureNodes.add(a2nIdx(curArrayIndex));
      }
    }
    return list2array(failureNodes);
  }
Exemplo n.º 7
0
    private void layoutComponents(
        Container target,
        int xOffset,
        int yOffset,
        int maxwidth,
        int rowheight,
        SizeRequirements[] xChildren,
        SizeRequirements[] yChildren,
        int start,
        int end,
        boolean ltr) {
      SizeRequirements[] children = (SizeRequirements[]) ArrayUtils.subarray(xChildren, start, end);
      int[] xOffsets = new int[children.length];
      int[] xSpans = new int[children.length];
      SizeRequirements.calculateTiledPositions(maxwidth, null, children, xOffsets, xSpans, ltr);

      children = (SizeRequirements[]) ArrayUtils.subarray(yChildren, start, end);
      int[] yOffsets = new int[children.length];
      int[] ySpans = new int[children.length];
      SizeRequirements total = new SizeRequirements(rowheight, rowheight, rowheight, 0.5f);
      SizeRequirements.calculateAlignedPositions(rowheight, total, children, yOffsets, ySpans, ltr);

      Insets in = target.getInsets();
      for (int i = 0; i < children.length; i++) {
        Component c = target.getComponent(i + start);
        c.setBounds(
            (int) Math.min((long) xOffset + (long) xOffsets[i], Integer.MAX_VALUE),
            (int) Math.min((long) yOffset + (long) yOffsets[i], Integer.MAX_VALUE),
            xSpans[i],
            ySpans[i]);
      }
    }
Exemplo n.º 8
0
 protected double calculateSimilarity(Collection<Double> item1, Collection<Double> item2) {
   System.out.println("item1 " + item1);
   System.out.println("item2 " + item2);
   double[] v1 = ArrayUtils.toPrimitive(item1.toArray(new Double[item1.size()]));
   double[] v2 = ArrayUtils.toPrimitive(item2.toArray(new Double[item2.size()]));
   return Vectors.calculateSimiliraty(v1, v2);
 }
 protected Map<String, List<Double>> generateUriRankRangeMapping(
     ObjectIntOpenHashMap<String> countedResources) {
   String uris[] = new String[countedResources.assigned];
   int counts[] = new int[countedResources.assigned];
   int pos = 0;
   for (int i = 0; i < countedResources.allocated.length; ++i) {
     if (countedResources.allocated[i]) {
       uris[pos] = (String) ((Object[]) countedResources.keys)[i];
       counts[pos] = countedResources.values[i];
       ++pos;
     }
   }
   AssociativeSort.quickSort(counts, uris);
   ArrayUtils.reverse(uris);
   ArrayUtils.reverse(counts);
   Map<String, List<Double>> uriPosMapping =
       new HashMap<String, List<Double>>((int) (1.75 * uris.length));
   int minRank, maxRank;
   for (int i = 0; i < uris.length; ++i) {
     minRank = i;
     while ((minRank > 0) && (counts[minRank - 1] == counts[minRank])) {
       --minRank;
     }
     maxRank = i;
     while ((maxRank < (counts.length - 1)) && (counts[maxRank + 1] == counts[maxRank])) {
       ++maxRank;
     }
     uriPosMapping.put(uris[i], Arrays.asList(new Double(minRank), new Double(maxRank)));
   }
   return uriPosMapping;
 }
  public void testQueryForListOnCobarSqlMapClientTemplate() {
    // 1. initialize data
    String[] names = {"Aaron", "Amily", "Aragon", "Darren", "Darwin"};
    batchInsertMultipleFollowersAsFixture(names);

    // 2. perform assertion
    @SuppressWarnings("unchecked")
    List<Follower> resultList =
        (List<Follower>)
            getSqlMapClientTemplate()
                .queryForList("com.alibaba.cobar.client.entities.Follower.findAll");
    assertTrue(CollectionUtils.isNotEmpty(resultList));
    assertEquals(5, resultList.size());
    for (Follower f : resultList) {
      assertTrue(ArrayUtils.contains(names, f.getName()));
    }

    // 3. perform assertion with another different query
    @SuppressWarnings("unchecked")
    List<Follower> followersWithNameStartsWithA =
        (List<Follower>)
            getSqlMapClientTemplate()
                .queryForList("com.alibaba.cobar.client.entities.Follower.finaByNameAlike", "A");
    assertTrue(CollectionUtils.isNotEmpty(followersWithNameStartsWithA));
    assertEquals(3, followersWithNameStartsWithA.size());
    for (Follower f : followersWithNameStartsWithA) {
      assertTrue(ArrayUtils.contains(names, f.getName()));
    }
  }
Exemplo n.º 11
0
 /**
  * Get a piece of string data with a position and string key, or <code>null</code> if the datum
  * cannot be found. Position keys are exclusive from all other key types.
  *
  * @param key
  * @return The found data.
  */
 public String getPositionDatum(NodePosition pos, String key) {
   byte[] keyBytes =
       ArrayUtils.addAll(
           bytes("npos::"), // $NON-NLS-1$
           ArrayUtils.addAll(pos.toBytes(), bytes("str::" + key))); // $NON-NLS-1$
   byte[] dataBytes = this.innerDb.get(keyBytes);
   return (dataBytes == null) ? null : asString(dataBytes);
 }
Exemplo n.º 12
0
 /** {@inheritDoc} */
 public boolean hasAccessPermission(Space space, String userId) {
   if (userId.equals(getUserACL().getSuperUser())
       || (ArrayUtils.contains(space.getMembers(), userId))
       || (ArrayUtils.contains(space.getManagers(), userId))) {
     return true;
   }
   return false;
 }
Exemplo n.º 13
0
 /** {@inheritDoc} */
 private Space removeInvited(Space space, String userId) {
   String[] invitedUsers = space.getInvitedUsers();
   if (ArrayUtils.contains(invitedUsers, userId)) {
     invitedUsers = (String[]) ArrayUtils.removeElement(invitedUsers, userId);
     space.setInvitedUsers(invitedUsers);
   }
   return space;
 }
Exemplo n.º 14
0
 /** {@inheritDoc} */
 private Space addInvited(Space space, String userId) {
   String[] invitedUsers = space.getInvitedUsers();
   if (!ArrayUtils.contains(invitedUsers, userId)) {
     invitedUsers = (String[]) ArrayUtils.add(invitedUsers, userId);
     space.setInvitedUsers(invitedUsers);
   }
   return space;
 }
Exemplo n.º 15
0
 /** {@inheritDoc} */
 private Space removePending(Space space, String userId) {
   String[] pendingUsers = space.getPendingUsers();
   if (ArrayUtils.contains(pendingUsers, userId)) {
     pendingUsers = (String[]) ArrayUtils.removeElement(pendingUsers, userId);
     space.setPendingUsers(pendingUsers);
   }
   return space;
 }
Exemplo n.º 16
0
 /** {@inheritDoc} */
 private Space addPending(Space space, String userId) {
   String[] pendingUsers = space.getPendingUsers();
   if (!ArrayUtils.contains(pendingUsers, userId)) {
     pendingUsers = (String[]) ArrayUtils.add(pendingUsers, userId);
     space.setPendingUsers(pendingUsers);
   }
   return space;
 }
Exemplo n.º 17
0
 @Override
 public void action(DomainMessage domainMessage) {
   long[] id = (long[]) domainMessage.getEventSource();
   id = ArrayUtils.removeElement(id, 0);
   if (ArrayUtils.isNotEmpty(id)) {
     domainMessage.setEventResult(answerRepository.forbidAnswer(id));
   }
 }
Exemplo n.º 18
0
 /**
  * Put a datum with a position and string key, overwriting as necessary.
  *
  * @param pos The position portion of the key.
  * @param key The string key.
  * @param data The data to put.
  */
 public void putPositionDatum(NodePosition pos, String key, String data) {
   byte[] keyBytes =
       ArrayUtils.addAll(
           bytes("npos::"), // $NON-NLS-1$
           ArrayUtils.addAll(pos.toBytes(), bytes("str::" + key))); // $NON-NLS-1$
   byte[] dataBytes = bytes(data);
   this.innerDb.put(keyBytes, dataBytes);
 }
Exemplo n.º 19
0
 public static int[] removeZeroFromChord(int[] chord) {
   int[] tempChord = chord;
   while (ArrayUtils.contains(tempChord, ZERO)) {
     int index = ArrayUtils.indexOf(tempChord, ZERO);
     tempChord = ArrayUtils.remove(tempChord, index);
   }
   return tempChord;
 }
Exemplo n.º 20
0
  @Test
  public void creatingKeyFromIdentityWithByteArrayIdentifier() {
    ObjectIdentity identity = new ObjectIdentityImpl(TYPE, ID.getBytes());

    AclRecord underTest = new AclRecord(identity, null);

    assertEquals(identity, underTest.getIdentity());
    assertTrue(ArrayUtils.isEquals(ID.getBytes(), underTest.getKey()));
    assertTrue(ArrayUtils.isEquals(byte[].class.getName().getBytes(), underTest.getIdTypeBytes()));
  }
Exemplo n.º 21
0
 /** {@inheritDoc} */
 public void removeMember(Space space, String userId) {
   String[] members = space.getMembers();
   if (ArrayUtils.contains(members, userId)) {
     members = (String[]) ArrayUtils.removeElement(members, userId);
     space.setMembers(members);
     this.updateSpace(space);
     SpaceUtils.removeUserFromGroupWithMemberMembership(userId, space.getGroupId());
     spaceLifeCycle.memberLeft(space, userId);
   }
 }
Exemplo n.º 22
0
  @Test
  public void creatingKeyFromIdentityWithConvertableIdentifier() {
    ObjectIdentity identity = new ObjectIdentityImpl(TYPE, ID);

    AclRecord underTest = new AclRecord(identity, new StringAclIdentifierConverter());

    assertEquals(identity, underTest.getIdentity());
    assertTrue(ArrayUtils.isEquals(ID.getBytes(), underTest.getKey()));
    assertTrue(ArrayUtils.isEquals(String.class.getName().getBytes(), underTest.getIdTypeBytes()));
  }
Exemplo n.º 23
0
 public DeprecatedProfiles(
     Plugins plugins,
     RuleFinder ruleFinder,
     RulesRepository[] r,
     CheckProfile[] deprecatedCheckProfiles) {
   this.deprecatedRepositories = (RulesRepository[]) ArrayUtils.clone(r);
   this.plugins = plugins;
   this.ruleFinder = ruleFinder;
   this.deprecatedCheckProfiles = (CheckProfile[]) ArrayUtils.clone(deprecatedCheckProfiles);
   this.deprecatedCheckProfileProviders = new CheckProfileProvider[0];
 }
 @Test
 public void TestGetKnownNamespace() throws Exception {
   MockServiceProvider.cts2Service = new MockService();
   GetKnownNamespace request = new GetKnownNamespace();
   GetKnownNamespaceResponse response = (GetKnownNamespaceResponse) this.doSoapCall(uri, request);
   NamespaceReference[] namespaceReferences = response.getReturn();
   assertEquals(3, namespaceReferences.length);
   assertTrue(ArrayUtils.contains(namespaceReferences, new DocumentedNamespaceReference("ns1")));
   assertTrue(ArrayUtils.contains(namespaceReferences, new DocumentedNamespaceReference("ns2")));
   assertTrue(ArrayUtils.contains(namespaceReferences, new DocumentedNamespaceReference("ns3")));
 }
 @Test
 public void testSetGetDimensions() {
   testSetGetComposition();
   cap.setShape("cylinder");
   double[] dims = new double[] {0.15, 0.16};
   cap.setDimensions(dims);
   assertEquals(
       "New dimensions not set/got correctly",
       Arrays.asList(ArrayUtils.toObject(dims)),
       Arrays.asList(ArrayUtils.toObject(cap.getDimensions())));
 }
Exemplo n.º 26
0
 public static String[] combine(Object... strings) {
   String[] combined = {};
   for (int i = 0; i < strings.length; i++) {
     Object obj = strings[i];
     if (obj instanceof String[]) {
       combined = (String[]) ArrayUtils.addAll(combined, (Object[]) strings[i]);
     } else {
       combined = (String[]) ArrayUtils.add(combined, obj.toString());
     }
   }
   return combined;
 }
Exemplo n.º 27
0
  public Pager findPager(Pager pager, Criteria criteria) {
    Assert.notNull(pager, "pager is required");
    Assert.notNull(criteria, "criteria is required");

    Integer pageNumber = pager.getPageNumber();
    Integer pageSize = pager.getPageSize();
    String searchBy = pager.getSearchBy();
    String keyword = pager.getKeyword();
    String orderBy = pager.getOrderBy();
    Pager.Order order = pager.getOrder();

    if (StringUtils.isNotEmpty(searchBy) && StringUtils.isNotEmpty(keyword)) {
      if (searchBy.contains(".")) {
        String alias = StringUtils.substringBefore(searchBy, ".");
        criteria.createAlias(alias, alias);
      }
      criteria.add(Restrictions.like(searchBy, "%" + keyword + "%"));
    }

    pager.setTotalCount(criteriaResultTotalCount(criteria));

    if (StringUtils.isNotEmpty(orderBy) && order != null) {
      if (order == Pager.Order.asc) {
        criteria.addOrder(Order.asc(orderBy));
      } else {
        criteria.addOrder(Order.desc(orderBy));
      }
    }

    ClassMetadata classMetadata = sessionFactory.getClassMetadata(entityClass);
    if (!StringUtils.equals(orderBy, ORDER_LIST_PROPERTY_NAME)
        && ArrayUtils.contains(classMetadata.getPropertyNames(), ORDER_LIST_PROPERTY_NAME)) {
      criteria.addOrder(Order.asc(ORDER_LIST_PROPERTY_NAME));
      criteria.addOrder(Order.desc(CREATE_DATE_PROPERTY_NAME));
      if (StringUtils.isEmpty(orderBy) || order == null) {
        pager.setOrderBy(ORDER_LIST_PROPERTY_NAME);
        pager.setOrder(Pager.Order.asc);
      }
    } else if (!StringUtils.equals(orderBy, CREATE_DATE_PROPERTY_NAME)
        && ArrayUtils.contains(classMetadata.getPropertyNames(), CREATE_DATE_PROPERTY_NAME)) {
      criteria.addOrder(Order.desc(CREATE_DATE_PROPERTY_NAME));
      if (StringUtils.isEmpty(orderBy) || order == null) {
        pager.setOrderBy(CREATE_DATE_PROPERTY_NAME);
        pager.setOrder(Pager.Order.desc);
      }
    }

    criteria.setFirstResult((pageNumber - 1) * pageSize);
    criteria.setMaxResults(pageSize);

    pager.setResult(criteria.list());
    return pager;
  }
Exemplo n.º 28
0
 /** {@inheritDoc} */
 public void addMember(Space space, String userId) {
   String[] members = space.getMembers();
   space = this.removeInvited(space, userId);
   space = this.removePending(space, userId);
   if (!ArrayUtils.contains(members, userId)) {
     members = (String[]) ArrayUtils.add(members, userId);
     space.setMembers(members);
     this.updateSpace(space);
     SpaceUtils.addUserToGroupWithMemberMembership(userId, space.getGroupId());
     spaceLifeCycle.memberJoined(space, userId);
   }
 }
Exemplo n.º 29
0
  @Test
  public void creatingIdentityWithByteArrayIdentifier() {
    NavigableMap<byte[], byte[]> familyMap = recordMap(byte[].class, false);
    AclRecord underTest = new AclRecord(ID.getBytes(), familyMap, null);

    ObjectIdentity returnedIdentity = underTest.getIdentity();
    assertEquals(TYPE, returnedIdentity.getType());
    assertTrue(ArrayUtils.isEquals(ID.getBytes(), returnedIdentity.getIdentifier()));
    assertTrue(ArrayUtils.isEquals(ID.getBytes(), underTest.getKey()));
    assertTrue(ArrayUtils.isEquals(byte[].class.getName().getBytes(), underTest.getIdTypeBytes()));
    assertEquals(new GrantedAuthoritySid(SOME_PRINCIPAL), underTest.getOwner());
  }
Exemplo n.º 30
0
 private void checkExeuctionErrors(ProcessReports[] processReports) {
   if (samplingCount == 0
       && ArrayUtils.isNotEmpty(this.processReports)
       && ArrayUtils.isEmpty(processReports)) {
     getListeners()
         .apply(
             new Informer<ConsoleShutdownListener>() {
               public void inform(ConsoleShutdownListener listener) {
                 listener.readyToStop(StopReason.SCRIPT_ERROR);
               }
             });
   }
 }