Java 类org.apache.commons.lang.ArrayUtils 实例源码

项目:pds    文件:SysUserController.java   
/**
 * 删除用户
 */
@SysLog("删除用户")
@RequestMapping("/delete")
@RequiresPermissions("sys:user:delete")
public R delete(@RequestBody Long[] userIds){
    if(ArrayUtils.contains(userIds, 1L)){
        return R.error("系统管理员不能删除");
    }

    if(ArrayUtils.contains(userIds, getUserId())){
        return R.error("当前用户不能删除");
    }

    sysUserService.deleteBatch(userIds);

    return R.ok();
}
项目:ytk-learn    文件:GBMLRDataFlow.java   
@Override
protected void lastSampleHandle() throws Mp4jException {
    TMP_XIDX[count] = xindex;
    int localnum = realNum[cursor2d];
    xidx[cursor2d] = new int[localnum + 1];
    System.arraycopy(TMP_XIDX, 0, xidx[cursor2d], 0, localnum + 1);

    y[cursor2d] = new float[localnum];
    System.arraycopy(TMP_Y, 0, y[cursor2d], 0, localnum);

    weight[cursor2d] = new float[localnum];
    System.arraycopy(TMP_WEIGHT, 0, weight[cursor2d], 0, localnum);

    z[cursor2d] = new float[localnum];
    System.arraycopy(TMP_Z, 0, z[cursor2d], 0, localnum);

    predict[cursor2d] = new float[localnum];

    randMask[cursor2d] = new BitSet(localnum);

    LOG_UTILS.verboseInfo(loadingPrefix + "finished read data, cursor2d:" + cursor2d +
            ", real num:" + ArrayUtils.toString(Arrays.copyOfRange(realNum, 0, cursor2d + 1)) +
            ", weight sum:" + ArrayUtils.toString(Arrays.copyOfRange(weightNum, 0, cursor2d + 1)), false);
}
项目:incubator-servicecomb-java-chassis    文件:Version.java   
public Version(String version) {
  Objects.requireNonNull(version);

  String[] versions = version.split("\\.", -1);
  if (versions.length > 3) {
    throw new IllegalStateException(String.format("Invalid version \"%s\".", version));
  }

  if (versions.length < 3) {
    versions = (String[]) ArrayUtils.addAll(versions, ZERO);
  }
  this.major = parseNumber("major", version, versions[0]);
  this.minor = parseNumber("minor", version, versions[1]);
  this.patch = parseNumber("patch", version, versions[2]);

  this.version = combineStringVersion();
  this.numberVersion = combineVersion();
}
项目:rapidminer    文件:SelectionCreator.java   
/**
 * Creates an example index start selection for each numerical attribute, or if there is none,
 * only one.
 *
 * @return a map containing for each numerical attribute an example index array such that the
 *         associated attribute values are in ascending order.
 */
public Map<Integer, int[]> getStartSelection() {
    Map<Integer, int[]> selection = new HashMap<>();
    if (columnTable.getNumberOfRegularNumericalAttributes() == 0) {
        selection.put(0, createFullArray(columnTable.getNumberOfExamples()));
    } else {
        Integer[] bigSelectionArray = createFullBigArray(columnTable.getNumberOfExamples());
        for (int j = columnTable.getNumberOfRegularNominalAttributes(); j < columnTable
                .getTotalNumberOfRegularAttributes(); j++) {
            final double[] attributeColumn = columnTable.getNumericalAttributeColumn(j);
            Integer[] startSelection = Arrays.copyOf(bigSelectionArray, bigSelectionArray.length);
            Arrays.sort(startSelection, new Comparator<Integer>() {

                @Override
                public int compare(Integer a, Integer b) {
                    return Double.compare(attributeColumn[a], attributeColumn[b]);
                }
            });
            selection.put(j, ArrayUtils.toPrimitive(startSelection));
        }
    }
    return selection;
}
项目:DroidSentinel    文件:WeightedMovingAverage.java   
public double getPrediction(List<Double> data){
    //Predict a simple value
    //pred[i]= SMA[i-1]+(O[i-2]-SMA[i-2])
    double pred=0.0;

    double[] dObs=ArrayUtils.toPrimitive(data.toArray(new Double[data.size()]));
    List<Double> SMA_data = getWMA((List) ((ArrayList) data).clone());
    double[] dSMA=ArrayUtils.toPrimitive(SMA_data.toArray(new Double[SMA_data.size()]));

    int i = data.size()-1;
    if(i>2){
        pred=dSMA[i]+(dObs[i-1]-dSMA[i-1]);
        //System.out.println("pred: "+pred+"dSMA[i-1]:" + dSMA[i-1]+" + (dObs[i-2]"+dObs[i-2]+"-dSMA[i-2]): "+dSMA[i-2]+")");
    }
    else{
        pred= 0;
    }
    return pred;
}
项目:calendar-based-microsim    文件:ArrayHandler.java   
/**
 * picks randomly non-repeating some elements from a source array and not in
 * another array. For example, pickRandomFromArray(new int[] {1,2,3,4,5,6},
 * new int[] {2,6}, 2) returns {1,5}.
 * 
 * @param srcArray
 *            the source array where elements will be picked from.
 * @param excludedArray
 *            the array containing elements that must not be picked.
 * @param nPick
 *            number of array to be picked.
 * @sRandom a random object generating controlled random numbers.
 * @return a subset of the source array that have no elements as specified
 *         in the excludedArray.
 */
public static int[] pickRandomFromArray(int[] srcArray, int[] excludedArray,
        int nPick, Random sRandom) {
    if (nPick <= 0 || srcArray == null || srcArray.length == 0) {
        return null;
       }
    int[] excluded = excludedArray;
    int[] finArr = new int[nPick];
    int[] remained = getNonCommonInArrays(srcArray,excluded);
    if (remained.length < nPick) {
        finArr = null;
       } else {
        for (int i = 0; i <= nPick - 1; i++) {
            if (remained.length == 1) {
                finArr[i] = remained[0];
               } else {
                //finArr[i] = remained[sRandom.nextInt(remained.length - 1)];
                finArr[i] = remained[sRandom.nextInt(remained.length)];
               }
            excluded = ArrayUtils.add(excluded, finArr[i]);
            remained = getNonCommonInArrays(srcArray, excluded);
        }
    }
    return finArr;
}
项目:SparkSeq    文件:GATKVariantContextUtils.java   
public static Pair<int[],byte[]> getNumTandemRepeatUnits(final byte[] refBases, final byte[] altBases, final byte[] remainingRefContext) {
     /* we can't exactly apply same logic as in basesAreRepeated() to compute tandem unit and number of repeated units.
       Consider case where ref =ATATAT and we have an insertion of ATAT. Natural description is (AT)3 -> (AT)2.
     */

    byte[] longB;
    // find first repeat unit based on either ref or alt, whichever is longer
    if (altBases.length > refBases.length)
        longB = altBases;
    else
        longB = refBases;

    // see if non-null allele (either ref or alt, whichever is longer) can be decomposed into several identical tandem units
    // for example, -*,CACA needs to first be decomposed into (CA)2
    final int repeatUnitLength = findRepeatedSubstring(longB);
    final byte[] repeatUnit = Arrays.copyOf(longB, repeatUnitLength);

    final int[] repetitionCount = new int[2];
    // look for repetitions forward on the ref bases (i.e. starting at beginning of ref bases)
    int repetitionsInRef = findNumberOfRepetitions(repeatUnit, refBases, true);
    repetitionCount[0] = findNumberOfRepetitions(repeatUnit, ArrayUtils.addAll(refBases, remainingRefContext), true)-repetitionsInRef;
    repetitionCount[1] = findNumberOfRepetitions(repeatUnit, ArrayUtils.addAll(altBases, remainingRefContext), true)-repetitionsInRef;

    return new Pair<>(repetitionCount, repeatUnit);

}
项目:athena    文件:CpmanViewMessageHandler.java   
private Map<ControlMetricType, Long[]> generateMatrix(ControlPlaneMonitorService cpms,
                                                      ClusterService cs, DeviceId deviceId) {
    Map<ControlMetricType, Long[]> data = Maps.newHashMap();
    for (ControlMetricType cmt : CONTROL_MESSAGE_METRICS) {
        ControlLoadSnapshot cls = cpms.getLoadSync(cs.getLocalNode().id(),
                cmt, NUM_OF_DATA_POINTS, TimeUnit.MINUTES, Optional.of(deviceId));

        // TODO: in some cases, the number of returned data set is
        // less than what we expected (expected -1)
        // As a workaround, we simply fill the slot with 0 values,
        // such a bug should be fixed with updated RRD4J lib...
        data.put(cmt, ArrayUtils.toObject(fillData(cls.recent(), NUM_OF_DATA_POINTS)));
        timestamp = cls.time();
    }
    return data;
}
项目:DroidSentinel    文件:WeightedMovingAverage.java   
public List<Double> getAllPredictions(List<Double> data, int T){
    //returns all the predictions for a time serie
    //this is expensive, but helps in testing
    double[] dObs=ArrayUtils.toPrimitive(data.toArray(new Double[data.size()]));
    double[] sol= new double[data.size()+T];
    for(int i=0;i<data.size();i++){
        List<Double> subList = new ArrayList<Double>(data.subList(0, i));
        if(i<T){
            sol[i]=dObs[i];
            sol[i+T]=getPrediction(subList);
        }
        else{
            sol[i+T]=getPrediction(subList);
        }
    }//for

    List<Double> auxSOl=convertDoubletoArrayList(sol);
    return auxSOl;
}
项目:YiDu-Novel    文件:RegiAuthorAction.java   
/**
 * <p>
 * 保存画面的内容
 * </p>
 * 
 * @return
 * @throws Exception
 */
public String register() {
    logger.debug("register start.");
    if (ArrayUtils.contains(YiDuConstants.ALLOW_SAMPLE_TYPES, getSampleContentType())) {
        try {
            // saveArticlespic();
        } catch (Exception e) {
            addActionError(getText("errors.file.save"));
            return FREEMARKER;
        }
    } else {
        addActionError(getText("errors.file.type"));
        return FREEMARKER;
    }

    addActionMessage(getText("messages.save.success"));
    logger.debug("register normally end.");
    return FREEMARKER;
}
项目:lams    文件:MethodUtils.java   
/**
 * <p>Invoke a method whose parameter types match exactly the parameter
 * types given.</p>
 *
 * <p>This uses reflection to invoke the method obtained from a call to
 * <code>getAccessibleMethod()</code>.</p>
 *
 * @param object invoke method on this object
 * @param methodName get method with this name
 * @param args use these arguments - treat null as empty array
 * @param parameterTypes match these parameters - treat null as empty array
 * @return The value returned by the invoked method
 *
 * @throws NoSuchMethodException if there is no such accessible method
 * @throws InvocationTargetException wraps an exception thrown by the
 *  method invoked
 * @throws IllegalAccessException if the requested method is not accessible
 *  via reflection
 */
public static Object invokeExactMethod(Object object, String methodName,
        Object[] args, Class[] parameterTypes)
        throws NoSuchMethodException, IllegalAccessException,
        InvocationTargetException {
    if (args == null) {
        args = ArrayUtils.EMPTY_OBJECT_ARRAY;
    }
    if (parameterTypes == null) {
        parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY;
    }
    Method method = getAccessibleMethod(object.getClass(), methodName,
            parameterTypes);
    if (method == null) {
        throw new NoSuchMethodException("No such accessible method: "
                + methodName + "() on object: "
                + object.getClass().getName());
    }
    return method.invoke(object, args);
}
项目:soundwave    文件:EsIteratorTest.java   
@Test
public void noRetrieval() throws Exception {
  ScrollableResponse<List<Integer>> scrollableResponse = new ScrollableResponse<>();
  scrollableResponse.setValue(Arrays.asList(1, 2, 3, 4, 5));
  scrollableResponse.setScrollToEnd(true);

  EsIterator<Integer> l = new EsIterator<>(scrollableResponse, s -> scrollableResponse);
  int count = 0;
  ArrayList<Integer> result = new ArrayList<>();
  while (l.hasNext()) {
    result.add(l.next());
    count++;
  }
  Assert.assertArrayEquals(new int[]{1, 2, 3, 4, 5},
      ArrayUtils.toPrimitive(result.toArray(new Integer[0])));
}
项目:patcher    文件:ClassesExportAction.java   
private void getVirtualFile(String sourceName, VirtualFile virtualFile[], String compileRoot)
        throws Exception {
    if (!ArrayUtils.isEmpty(virtualFile)) {
        VirtualFile arr$[] = virtualFile;
        int len$ = arr$.length;
        for (int i$ = 0; i$ < len$; i$++) {
            VirtualFile vf = arr$[i$];
            String srcName;
            if (StringUtils.indexOf(vf.toString(), "$") != -1)
                srcName = StringUtils.substring(vf.toString(), StringUtils.lastIndexOf(vf.toString(), "/") + 1, StringUtils.indexOf(vf.toString(), "$"));
            else
                srcName = StringUtils.substring(vf.toString(), StringUtils.lastIndexOf(vf.toString(), "/") + 1, StringUtils.length(vf.toString()) - 6);
            String dstName = StringUtils.substring(sourceName, 0, StringUtils.length(sourceName) - 5);
            if (StringUtils.equals(srcName, dstName)) {
                String outRoot = (new StringBuilder()).append(StringUtils.substring(compileRoot, 0, StringUtils.lastIndexOf(compileRoot, "/"))).append("/out").toString();
                String packagePath = StringUtils.substring(vf.getPath(), StringUtils.length(compileRoot), StringUtils.length(vf.getPath()));
                File s = new File(vf.getPath());
                File t = new File((new StringBuilder()).append(outRoot).append(packagePath).toString());
                FileUtil.copy(s, t);
            }
            if (!ArrayUtils.isEmpty(virtualFile))
                getVirtualFile(sourceName, vf.getChildren(), compileRoot);
        }

    }
}
项目:lams    文件:EqualsBuilder.java   
/**
 * <p>Appends the fields and values defined by the given object of the
 * given Class.</p>
 * 
 * @param lhs  the left hand object
 * @param rhs  the right hand object
 * @param clazz  the class to append details of
 * @param builder  the builder to append to
 * @param useTransients  whether to test transient fields
 * @param excludeFields  array of field names to exclude from testing
 */
private static void reflectionAppend(
    Object lhs,
    Object rhs,
    Class clazz,
    EqualsBuilder builder,
    boolean useTransients,
    String[] excludeFields) {
    Field[] fields = clazz.getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);
    for (int i = 0; i < fields.length && builder.isEquals; i++) {
        Field f = fields[i];
        if (!ArrayUtils.contains(excludeFields, f.getName())
            && (f.getName().indexOf('$') == -1)
            && (useTransients || !Modifier.isTransient(f.getModifiers()))
            && (!Modifier.isStatic(f.getModifiers()))) {
            try {
                builder.append(f.get(lhs), f.get(rhs));
            } catch (IllegalAccessException e) {
                //this can't happen. Would get a Security exception instead
                //throw a runtime exception in case the impossible happens.
                throw new InternalError("Unexpected IllegalAccessException");
            }
        }
    }
}
项目:osc-core    文件:KubernetesDeploymentApiTest.java   
public Object[] getNullInputsTestData() {
    List<Object[]> inputsList = new ArrayList<Object[]>();
    inputsList.add(new Object[]{null, "namespace", "name"});
    inputsList.add(new Object[]{"uuid", null, "name"});
    inputsList.add(new Object[]{"uuid", "namespace", null});

    List<Object[]> result = new ArrayList<Object[]>();

    for (DeploymentOperation operation : DeploymentOperation.values()) {
        for (Object[] inputs : inputsList) {
            result.add(ArrayUtils.add(inputs, operation));
        }
    }

    return result.toArray();
}
项目:coddy    文件:JWTService.java   
private JWTToken generateToken(Map<String, Object> claims, Date notBefore) {

        byte[] secret = DEFAULT_JWT_SECRET;

        if (!ArrayUtils.isEmpty(this.jwtSecret)) {
            secret = this.jwtSecret;
        }

        int sessionExpireMinutes = DEFAULT_JWT_SESSION_TIMEOUT_MINUTE;

        if (NumberUtils.isDigits(this.jwtTimeOut)) {
            sessionExpireMinutes = Integer.parseInt(this.jwtTimeOut);
        }

        LocalDateTime expiration = LocalDateTime.now().plusMinutes(sessionExpireMinutes);

        return new JWTToken(Jwts.builder()
                .setClaims(claims)
                .setNotBefore(notBefore)
                .setExpiration(Date.from(expiration.atZone(ZoneId.systemDefault()).toInstant()))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact());
    }
项目:DroidSentinel    文件:DoubleMovingAverage.java   
public List<Double> getAllPredictions(List<Double> data, int T){
    //returns all the predictions for a time serie
    //this is expensive, but helps in testing
    double[] dObs=ArrayUtils.toPrimitive(data.toArray(new Double[data.size()]));
    double[] sol= new double[data.size()+T];
    for(int i=0;i<data.size();i++){
        List<Double> subList = new ArrayList<Double>(data.subList(0, i));
        if(i<T){
            sol[i]=dObs[i];
            sol[i+T]=getPrediction(subList);
        }
        else{
            sol[i+T]=getPrediction(subList);
        }
    }//for

    List<Double> auxSOl=convertDoubletoArrayList(sol);
    return auxSOl;
}
项目:soundwave    文件:EsIteratorTest.java   
@Test
public void onRetrieval() throws Exception {
  ScrollableResponse<List<Integer>> scrollableResponse1 = new ScrollableResponse<>();
  scrollableResponse1.setValue(Arrays.asList(1, 2, 3, 4, 5));
  scrollableResponse1.setScrollToEnd(false);

  ScrollableResponse<List<Integer>> scrollableResponse2 = new ScrollableResponse<>();
  scrollableResponse2.setValue(Arrays.asList(1, 2, 3));
  scrollableResponse2.setScrollToEnd(true);

  EsIterator<Integer> l = new EsIterator<>(scrollableResponse1, s -> scrollableResponse2);
  int count = 0;
  ArrayList<Integer> result = new ArrayList<>();
  while (l.hasNext()) {
    result.add(l.next());
    count++;
  }

  Assert.assertArrayEquals(new int[]{1, 2, 3, 4, 5, 1, 2, 3},
      ArrayUtils.toPrimitive(result.toArray(new Integer[0])));
}
项目:ytk-learn    文件:CoreData.java   
protected void lastSampleHandle() throws Mp4jException {
    TMP_XIDX[count] = xindex;
    int localnum = realNum[cursor2d];
    xidx[cursor2d] = new int[localnum + 1];
    System.arraycopy(TMP_XIDX, 0, xidx[cursor2d], 0, localnum + 1);

    y[cursor2d] = new float[localnum];
    System.arraycopy(TMP_Y, 0, y[cursor2d], 0, localnum);

    weight[cursor2d] = new float[localnum];
    System.arraycopy(TMP_WEIGHT, 0, weight[cursor2d], 0, localnum);

    predict[cursor2d] = new float[localnum];

    LOG_UTILS.verboseInfo(loadingPrefix + "finished read data, cursor2d:" + cursor2d +
            ", real num:" + ArrayUtils.toString(Arrays.copyOfRange(realNum, 0, cursor2d + 1)) +
            ", weight sum:" + ArrayUtils.toString(Arrays.copyOfRange(weightNum, 0, cursor2d + 1)), false);
}
项目:bubichain-sdk-java    文件:BlockchainKeyPairFactory.java   
/**
 * 根据公钥生成布比地址 1.对Q进行RIPEMD160算法得到20字节的N,即N = RIPEMD160(Q)
 * 2.在N前面加4字节前缀和1字节版本号。即M=0XE69A73FF01+N
 * 3.对M进行两次SHA256算法取前四字节,即Checksum=SHA256(SHA256(M))的前4字节
 * 4.将Checksum加到M后面,即S=M+Checksum 5.对S进行Base58编码即得到布比地址bubixxxxxxxxxxxx
 *
 * @param pubKey
 * @return 布比地址字符串
 */
private static String generateBubiAddress(EdDSAPublicKey pubKey){
    try {
        MessageDigest md = MessageDigest.getInstance("RIPEMD160");
        md.update(pubKey.getAbyte());
        byte[] N = md.digest();

        byte[] pubKeyheadArr = Utils.hexToBytes("E69A73FF01");
        byte[] M = ArrayUtils.addAll(pubKeyheadArr, N);
        md = MessageDigest.getInstance("SHA-256");
        md.update(M);
        byte[] M_256_1 = md.digest();
        md.update(M_256_1);
        byte[] M_256_2 = md.digest();
        byte[] S = new byte[M.length + 4];
        System.arraycopy(M, 0, S, 0, M.length);
        System.arraycopy(M_256_2, 0, S, M.length, 4);
        return Base58Utils.encode(S);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Error occured on generating BubiAddress!--" + e.getMessage(), e);
    }
}
项目:kaltura-ce-sakai-extension    文件:KalturaAPIService.java   
/**
 * Gets a HashMap representation of metadata for an entry or set of entries associated with a given container
 * (since each kaltura entry can have multiple permissions related to each collection)
 * NOTE: this will always return a map which is the same size as the input array of entries
 * 
 * OPTIMIZATION method (fetch lots of metadata at once)
 * 
 * @param containerId the id of the container (typically this will be the collection id or site id)
 * @param entryId the id of the entry (can be 1 or many values)
 * @return Map of the {entryId -> Map of metadata {key -> value} }
 */
protected Map<String, Map<String, String>> getMetadataForEntry(String containerId, String... entryIds) {
    if (StringUtils.isEmpty(containerId)) {
        throw new IllegalArgumentException("container id must be set");
    }
    if (entryIds == null || entryIds.length == 0) {
        throw new IllegalArgumentException("entry ids must be set and not empty");
    }
    if (log.isDebugEnabled()) log.debug("getMetadataForEntry(containerId="+containerId+", entryId="+ArrayUtils.toString(entryIds)+")");
    Map<String, Map<String, String>> metadata = new LinkedHashMap<String, Map<String, String>>(entryIds.length);
    // generate the default set of metadata permissions for when they do not exist
    Map<String, String> defaultMetadata = decodeMetadataPermissions(null, false);
    HashSet<String> containerIds = new HashSet<String>(1);
    containerIds.add(containerId);
    // get a set of metadata entries (only includes the entries which have metadata)
    Map<String, Map<String, String>> entriesMetadata = getMetadataForContainersEntries(containerIds, entryIds).get(containerId);
    // construct a map with all entries and fill in any missing metadata with default metadata (to ensure every input entry id is returned)
    for (String entryId : entryIds) {
        if (entriesMetadata.containsKey(entryId)) {
            metadata.put(entryId, entriesMetadata.get(entryId));
        } else {
            metadata.put(entryId, defaultMetadata);
        }
    }
    return metadata;
}
项目:Equella    文件:ExtendedPropertiesLayout.java   
private String escapeKey(String key)
{
    StringBuilder newkey = new StringBuilder();

    for( int i = 0; i < key.length(); i++ )
    {
        char c = key.charAt(i);

        if( ArrayUtils.contains(SEPARATORS, c) || ArrayUtils.contains(WHITE_SPACE, c) )
        {
            // escape the separator
            newkey.append('\\');
            newkey.append(c);
        }
        else
        {
            newkey.append(c);
        }
    }

    return newkey.toString();
}
项目:ytk-learn    文件:GBDTCoreData.java   
protected void lastSampleHandle() throws Mp4jException {
    int localnum = realNum[cursor2d];

    weight[cursor2d] = new float[localnum];
    System.arraycopy(TMP_WEIGHT, 0, weight[cursor2d], 0, localnum);

    y[cursor2d] = new float[localnum * numTreeInGroup];
    System.arraycopy(TMP_Y, 0, y[cursor2d], 0, localnum * numTreeInGroup);

    initScore[cursor2d] = new float[localnum * numTreeInGroup];
    System.arraycopy(TMP_INIT_SCORE, 0, initScore[cursor2d], 0, localnum * numTreeInGroup);

    score[cursor2d] = new float[localnum * numTreeInGroup];
    predict[cursor2d] = new float[localnum * numTreeInGroup];

    LOG_UTILS.verboseInfo(loadingPrefix + "finished read data, cursor2d:" + cursor2d +
            ", real num:" + ArrayUtils.toString(Arrays.copyOfRange(realNum, 0, cursor2d + 1)) +
            ", weight sum:" + ArrayUtils.toString(Arrays.copyOfRange(weightNum, 0, cursor2d + 1)), false);
}
项目:lams    文件:ExceptionUtils.java   
/**
 * <p>Creates a compact stack trace for the root cause of the supplied
 * <code>Throwable</code>.</p>
 *
 * <p>The output of this method is consistent across JDK versions.
 * It consists of the root exception followed by each of its wrapping
 * exceptions separated by '[wrapped]'. Note that this is the opposite
 * order to the JDK1.4 display.</p>
 *
 * @param throwable  the throwable to examine, may be null
 * @return an array of stack trace frames, never null
 * @since 2.0
 */
public static String[] getRootCauseStackTrace(Throwable throwable) {
    if (throwable == null) {
        return ArrayUtils.EMPTY_STRING_ARRAY;
    }
    Throwable throwables[] = getThrowables(throwable);
    int count = throwables.length;
    ArrayList frames = new ArrayList();
    List nextTrace = getStackFrameList(throwables[count - 1]);
    for (int i = count; --i >= 0;) {
        List trace = nextTrace;
        if (i != 0) {
            nextTrace = getStackFrameList(throwables[i - 1]);
            removeCommonFrames(trace, nextTrace);
        }
        if (i == count - 1) {
            frames.add(throwables[i].toString());
        } else {
            frames.add(WRAPPED_MARKER + throwables[i].toString());
        }
        for (int j = 0; j < trace.size(); j++) {
            frames.add(trace.get(j));
        }
    }
    return (String[]) frames.toArray(new String[0]);
}
项目:lams    文件:MethodUtils.java   
/**
 * <p>Invoke a named method whose parameter type matches the object type.</p>
 *
 * <p>This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.</p>
 *
 * <p>This method supports calls to methods taking primitive parameters 
 * via passing in wrapping classes. So, for example, a <code>Boolean</code> object
 * would match a <code>boolean</code> primitive.</p>
 *
 * @param object invoke method on this object
 * @param methodName get method with this name
 * @param args use these arguments - treat null as empty array
 * @param parameterTypes match these parameters - treat null as empty array
 * @return The value returned by the invoked method
 *
 * @throws NoSuchMethodException if there is no such accessible method
 * @throws InvocationTargetException wraps an exception thrown by the method invoked
 * @throws IllegalAccessException if the requested method is not accessible via reflection
 */
public static Object invokeMethod(Object object, String methodName,
        Object[] args, Class[] parameterTypes)
        throws NoSuchMethodException, IllegalAccessException,
        InvocationTargetException {
    if (parameterTypes == null) {
        parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY;
    }
    if (args == null) {
        args = ArrayUtils.EMPTY_OBJECT_ARRAY;
    }
    Method method = getMatchingAccessibleMethod(object.getClass(),
            methodName, parameterTypes);
    if (method == null) {
        throw new NoSuchMethodException("No such accessible method: "
                + methodName + "() on object: "
                + object.getClass().getName());
    }
    return method.invoke(object, args);
}
项目:shop-manager    文件:AuthAspect.java   
private Object[] ignoreHttpRequest(Object[] args) {
    if (args == null) return null;
    for (Object o : args) {
        if (o instanceof HttpServletRequest) {
            args = ArrayUtils.removeElement(args, o);
            return args;
        }
    }
    return args;
}
项目:xxl-job    文件:MailUtil.java   
/**
 * 发送邮件 (完整版)(结合Spring)
 * 
 * //@param javaMailSender: 发送Bean
 * //@param sendFrom        : 发送人邮箱
 * //@param sendNick        : 发送人昵称
 * @param toAddress     : 收件人邮箱
 * @param mailSubject   : 邮件主题
 * @param mailBody      : 邮件正文
 * @param mailBodyIsHtml: 邮件正文格式,true:HTML格式;false:文本格式
 * @param attachments   : 附件
 */
@SuppressWarnings("null")
public static boolean sendMailSpring(String toAddress, String mailSubject, String mailBody, boolean mailBodyIsHtml,File[] attachments) {
    JavaMailSender javaMailSender = null;//ResourceBundle.getInstance().getJavaMailSender();
    try {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, ArrayUtils.isNotEmpty(attachments), "UTF-8"); // 设置utf-8或GBK编码,否则邮件会有乱码;multipart,true表示文件上传

        helper.setFrom(sendFrom, sendNick);
        helper.setTo(toAddress);

        // 设置收件人抄送的名片和地址(相当于群发了)
        //helper.setCc(InternetAddress.parse(MimeUtility.encodeText("邮箱001") + " <@163.com>," + MimeUtility.encodeText("邮箱002") + " <@foxmail.com>"));

        helper.setSubject(mailSubject);
        helper.setText(mailBody, mailBodyIsHtml);

        // 添加附件
        if (ArrayUtils.isNotEmpty(attachments)) {
            for (File file : attachments) {
                helper.addAttachment(MimeUtility.encodeText(file.getName()), file); 
            }
        }

        // 群发
        //MimeMessage[] mailMessages = { mimeMessage };

        javaMailSender.send(mimeMessage);
        return true;
    } catch (Exception e) {
        logger.info("{}", e);
    }
    return false;
}
项目:smaph    文件:SmaphUtils.java   
/**
 * @param ftrCount
 *            the number of features.
 * @param excludedFeatures
 *            the features that have to be excluded from the feature list.
 * @return a vector containing all feature ids from 1 to ftrCount
 *         (included), except those in excludedFeatures.
 */
public static int[] getAllFtrVect(int ftrCount, int[] excludedFeatures) {
    Arrays.sort(excludedFeatures);
    Vector<Integer> res = new Vector<>();
    for (int i = 1; i < ftrCount + 1; i++)
        if (Arrays.binarySearch(excludedFeatures, i) < 0)
            res.add(i);
    return ArrayUtils.toPrimitive(res.toArray(new Integer[] {}));
}
项目:smaph    文件:SmaphUtils.java   
/**
 * @param base
 * @param ftrId
 * @return a new feature vector composed by base with the addition of ftrId.
 */
public static int[] addFtrVect(int[] base, int ftrId) {
    if (base == null)
        return new int[] { ftrId };
    else {
        if (ArrayUtils.contains(base, ftrId))
            throw new IllegalArgumentException("Trying to add a feature to a vector that already contains it.");
        int[] newVect = new int[base.length + 1];
        System.arraycopy(base, 0, newVect, 0, base.length);
        newVect[newVect.length - 1] = ftrId;
        Arrays.sort(newVect);
        return newVect;
    }
}
项目:smaph    文件:ExampleGatherer.java   
private String writeLineLibSvm(double[] ftrVect, BufferedWriter wr, double gold, int id, int[] selectedFeatures)
        throws IOException {
    String line = String.format("%.5f ", gold);
    for (int ftr = 0; ftr < ftrVect.length; ftr++)
        if (selectedFeatures == null || ArrayUtils.contains(selectedFeatures, ftr + 1))
            line += String.format("%d:%.9f ", ftr + 1, ftrVect[ftr]);
    line += " #id=" + id;
    return line;
}
项目:buenojo    文件:ResourceHelper.java   
public static final String getResourceAddress(boolean isFromGameResourceInput, String... fileResourcePathComponents)
{
    if (isFromGameResourceInput)
    {
        final String[] inputGameResourceArray = {BuenOjoFileUtils.GAME_RESOURCES_INPUT_DIR};
        fileResourcePathComponents = (String[]) ArrayUtils.addAll(inputGameResourceArray, fileResourcePathComponents);
    }   
    return getResourceAddress(fileResourcePathComponents);
}
项目:buenojo    文件:ResourceHelper.java   
public static final URL getResource(final boolean isFromGameResourceInput,String... fileResourcePathComponents)
{
    if (isFromGameResourceInput)
    {
        final String[] inputGameResourceArray = {BuenOjoFileUtils.GAME_RESOURCES_INPUT_DIR};
        fileResourcePathComponents = (String[]) ArrayUtils.addAll(inputGameResourceArray, fileResourcePathComponents);

    }   
    return getResource(fileResourcePathComponents);
}
项目:marathon-auth-plugin    文件:HTTPAuthFilter.java   
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
        FilterChain arg2) throws IOException, ServletException {

    if(AuthUtil.getAuthFlag()){
         arg2.doFilter(arg0, arg1);
         return ;
    }

    try{
         HttpServletRequest request  = (HttpServletRequest) arg0;
        WrapperResponse wrapper = new WrapperResponse((HttpServletResponse)arg1);
        boolean flag =  doGet(request, wrapper);
        log.info("HTTPAuthFilter uri {} doGet flag : {}",request.getRequestURI(),flag);
        if(flag){
                arg2.doFilter(arg0, wrapper);
                byte[] content = wrapper.getContent();
                content = filterGroups(request, content);
                   if(ArrayUtils.isNotEmpty(content)){
                       ServletOutputStream out = arg1.getOutputStream();
                        out.write(content);
                        out.flush();
                        out.close();
                   }
        }
    }catch(Exception e){
        log.error(e.getMessage(),e);
    }finally{
        AuthUtil.THREAD_LOCAL_USER.remove();
    }

}
项目:configx    文件:DependencyConfigUtils.java   
public static void registerDependency(BeanDefinitionRegistry registry, String beanName, String[] propertyNames) {
    if (ArrayUtils.isEmpty(propertyNames)) {
        return;
    }
    String dependencyBeanName = beanName + ".dependency";
    BeanDefinitionBuilder meta = BeanDefinitionBuilder.genericBeanDefinition(RefreshBeanDependencyFactoryBean.class);
    meta.addPropertyValue("beanName", beanName);
    meta.addPropertyValue("propertyNames", propertyNames);
    registry.registerBeanDefinition(dependencyBeanName, meta.getBeanDefinition());
}
项目:lams    文件:ReflectionToStringBuilder.java   
/**
 * Returns a new array of Strings without null elements. Internal method used to normalize exclude lists
 * (arrays and collections). Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} 
 * if an array element is <code>null</code>.
 * 
 * @param array
 *            The array to check
 * @return The given array or a new array without null.
 */
static String[] toNoNullStringArray(Object[] array) {
    ArrayList list = new ArrayList(array.length);
    for (int i = 0; i < array.length; i++) {
        Object e = array[i];
        if (e != null) {
            list.add(e.toString());
        }
    }
    return (String[]) list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
项目:calendar-based-microsim    文件:PopulationAnalytics.java   
/**
 * 
 * @return an ID of a new household, which is calculated by adding 1 to the max ID in the household pool.
 */
public static int calculateNewHholdID() {
    int[] existingHhIDs = ArrayHandler.toInt(Population.getHhPool().keySet());
    int max = Collections.max(Arrays.asList(ArrayUtils.toObject(existingHhIDs)));
    return max+1;
    //return (existingHhIDs[ArrayHandler.getIndexOfMax(existingHhIDs)] + 1);
}
项目:calendar-based-microsim    文件:PopulationAnalytics.java   
/**
 * 
 * @return an ID of a new individual, which is calculated by adding 1 to the max ID in the individual pool.
 */
public static int calculateNewIndivID() {
    int[] existingIndivIDs = ArrayHandler.toInt(Population.getIndivPool().keySet());
    int max = Collections.max(Arrays.asList(ArrayUtils.toObject(existingIndivIDs)));
    return max+1;
    //return (existingIndivIDs[ArrayHandler.getIndexOfMax(existingIndivIDs)] + 1);
}
项目:calendar-based-microsim    文件:Population.java   
/**
 * 
 * @return an ID of a new individual, which is calculated by adding 1 to the max ID in the Population.initIndivPool.
 */
public static int calculateNewIndivIDInitPool() {
    int[] existingIndivIDs = ArrayHandler.toInt(initIndivPool.keySet());
    if (existingIndivIDs==null || existingIndivIDs.length==0) {
        return 0;
    } else {
        int max = Collections.max(Arrays.asList(ArrayUtils.toObject(existingIndivIDs)));
        return max+1;
        //return (existingIndivIDs[ArrayHandler.getIndexOfMax(existingIndivIDs)] + 1);
    }

}
项目:oneops    文件:WorkOrderExecutor.java   
/**
 * Removes the remote work order after remote execution
 *
 * @param wo remote work order to be removed.
 * @param keyFile file to be used for executing the remote ssh
 * @param pr the process runner.
 */
private void removeRemoteWorkOrder(CmsWorkOrderSimple wo, String keyFile,
    ProcessRunner pr) {
  String user = ONEOPS_USER;
  String comments = "";
  if (!isDebugEnabled(wo)) {
    // clear the workorder files
    String logKey = getLogKey(wo);
    String host = getHost(wo, getLogKey(wo));
    String port = "22";
    if (host.contains(":")) {
      String[] parts = host.split(":");
      host = parts[0];
      port = parts[1];
      logger.info("using port from " + config.getIpAttribute());
    }

    String remoteCmd = "rm " + getRemoteFileName(wo);
    String[] cmd = (String[]) ArrayUtils.addAll(sshCmdLine,
        new String[]{keyFile, "-p " + port, user + "@" + host, remoteCmd});
    logger.info(logKey + " ### EXEC: " + user + "@" + host + " " + remoteCmd);
    ProcessResult result = pr.executeProcessRetry(
        new ExecutionContext(wo, cmd, getLogKey(wo), getRetryCountForWorkOrder(wo)));
    if (result.getResultCode() != 0) {
      // Not throwing exceptions, Should be ok if we are not able to
      // remove remote wo.
      logger.error(logKey + comments);
    } else {
      logger.info("removed remote workorder");
    }
  } else {
    logger.info("debug enabled, not removing remote workorders");

  }
}
项目:ahar    文件:ArchiveManager.java   
private String[] prepareArguments(Path harPath, Path[] fileList, String replication) {
    Object[] args = new String[]{"-archiveName", harPath.getName(), "-p", "/", "-r", replication};
    for (Path path : fileList) {
        args = ArrayUtils.add(args, makeRelativeToRoot(path.toString()));
    }
    args = ArrayUtils.add(args, new String(harPath.getParent().toString() + "/"));
    return (String[]) args;
}