Example usage for java.util Arrays copyOf

List of usage examples for java.util Arrays copyOf

Introduction

In this page you can find the example usage for java.util Arrays copyOf.

Prototype

public static boolean[] copyOf(boolean[] original, int newLength) 

Source Link

Document

Copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length.

Usage

From source file:com.opengamma.maths.lowlevelapi.functions.utilities.Unique.java

/**
 * Uniques the data, duplicates are removed based on their absolute difference in magnitude with respect to tol
 * @param data float[] the data/*from w  w w.ja v a  2 s .c om*/
 * @param tol the tolerance for two numbers being considered identical
 * @return the float[] uniqued data
 */
public static float[] byTol(float[] data, float tol) {
    Validate.notNull(data);
    int n = data.length;
    float[] sorteddata = Sort.stateless(data);
    int j = 0;
    for (int i = 1; i < n; i++) {
        if (!(Math.abs(sorteddata[i] - sorteddata[j]) < tol)) {
            j++;
            sorteddata[j] = sorteddata[i];
        }
    }
    return Arrays.copyOf(sorteddata, j + 1);
}

From source file:com.redhat.rcm.version.util.InputUtils.java

public static String[] getIncludedSubpaths(final File basedir, final String includes, final String excludes,
        final VersionManagerSession session) {
    final DirectoryScanner scanner = new DirectoryScanner();
    scanner.setBasedir(basedir);//from   www.  j a  v a  2  s .  c om

    final String[] initExcludes = new String[] { session.getWorkspace().getName() + "/**",
            session.getReports().getName() + "/**" };

    final String[] excludePattern = excludes == null ? new String[] {} : excludes.split("\\s*,\\s*");

    final String[] excluded = Arrays.copyOf(initExcludes, initExcludes.length + excludePattern.length);

    System.arraycopy(excludePattern, 0, excluded, initExcludes.length, excludePattern.length);

    scanner.setExcludes(excluded);
    scanner.addDefaultExcludes();

    final String[] included = includes == null ? new String[] { "**/pom.xml", "**/*.pom" }
            : includes.split("\\s*,\\s*");

    scanner.setIncludes(included);

    scanner.scan();

    final String[] includedSubpaths = scanner.getIncludedFiles();

    logger.info("Scanning from " + basedir + " and got included files " + Arrays.toString(includedSubpaths)
            + " and got excluded files " + Arrays.toString(scanner.getExcludedFiles()));

    return includedSubpaths;
}

From source file:testFileHandler.java

public void decrypt(String encryptedText, String secretKey, javax.swing.JTextArea plainTextField)
        throws Exception {

    byte[] message = Base64.decodeBase64(encryptedText.getBytes("utf-8"));

    MessageDigest md = MessageDigest.getInstance("SHA-1");
    byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8"));
    byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);

    SecretKey key = new SecretKeySpec(keyBytes, "DESede");
    Cipher decipher = Cipher.getInstance("DESede");
    decipher.init(Cipher.DECRYPT_MODE, key);

    byte[] plainText = decipher.doFinal(message);
    plainTextField.setText(new String(plainText, "UTF-8"));
}

From source file:com.netflix.hystrix.contrib.javanica.command.BatchHystrixCommand.java

@Override
@SuppressWarnings("unchecked")
protected List<Object> getFallback() {
    if (getFallbackAction() != null) {
        final CommandAction commandAction = getFallbackAction();

        try {//w w  w.  j  a va  2s  .c  o  m
            return (List<Object>) process(new Action() {
                @Override
                Object execute() {
                    Object[] args = toArgs(getCollapsedRequests());
                    if (commandAction.getMetaHolder().isExtendedFallback()) {
                        if (commandAction.getMetaHolder().isExtendedParentFallback()) {
                            args[args.length - 1] = getFailedExecutionException();
                        } else {
                            args = Arrays.copyOf(args, args.length + 1);
                            args[args.length - 1] = getFailedExecutionException();
                        }
                    } else {
                        if (commandAction.getMetaHolder().isExtendedParentFallback()) {
                            args = ArrayUtils.remove(args, args.length - 1);
                        }
                    }
                    return commandAction
                            .executeWithArgs(commandAction.getMetaHolder().getFallbackExecutionType(), args);
                }
            });
        } catch (Throwable e) {
            LOGGER.error(FallbackErrorMessageBuilder.create().append(commandAction, e).build());
            throw new FallbackInvocationException(e.getCause());
        }
    } else {
        return super.getFallback();
    }

}

From source file:com.netflix.genie.common.model.FileAttachment.java

/**
 * Get the data for the attachment./*w ww .ja  v a2  s  .c  o m*/
 *
 * @return the data for the attachment
 */
public byte[] getData() {
    if (this.data != null) {
        return Arrays.copyOf(this.data, this.data.length);
    } else {
        return null;
    }
}

From source file:com.bigdata.dastor.dht.CollatingOrderPreservingPartitioner.java

/**
 * Convert a byte array containing the most significant of 'sigbytes' bytes
 * representing a big-endian magnitude into a BigInteger.
 *///from  w  w  w.  j  a  v  a2s .c o  m
private BigInteger bigForBytes(byte[] bytes, int sigbytes) {
    if (bytes.length != sigbytes) {
        // append zeros
        bytes = Arrays.copyOf(bytes, sigbytes);
    }
    return new BigInteger(1, bytes);
}

From source file:com.opengamma.analytics.math.linearalgebra.TridiagonalMatrix.java

/**
 * @return An array of the values of the upper sub-diagonal
 */
public double[] getUpperSubDiagonal() {
    return Arrays.copyOf(_b, _b.length);
}

From source file:rasmantuta.testutil.PopulatedTemporaryFolder.java

public void mkdirs(String fileName) {
    final String[] strings = fileName.split("/");
    String dir = "";
    for (String string : Arrays.copyOf(strings, strings.length - 1)) {
        if (!"".equals(string)) {
            dir += "/" + string;
            if (!dir.equals(fileName))
                tempFolder.newFolder(dir);
        }/*from  w  w w .j  a  v  a2  s .  c  o  m*/
    }
}

From source file:com.almende.util.NamespaceUtil.java

/**
 * Populate cache./* w w w  . j a v a 2s . c  om*/
 * 
 * @param destination
 *            the destination
 * @param steps
 *            the steps
 * @param methods
 *            the methods
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws InvocationTargetException
 *             the invocation target exception
 */
private void populateCache(final Object destination, final String steps, final AnnotatedMethod[] methods)
        throws IllegalAccessException, InvocationTargetException {
    final AnnotatedClass clazz = AnnotationUtil.get(destination.getClass());
    for (final AnnotatedMethod method : clazz.getAnnotatedMethods(Namespace.class)) {
        final String path = steps + "." + method.getAnnotation(Namespace.class).value();
        methods[methods.length - 1] = method;
        cache.put(path, Arrays.copyOf(methods, methods.length));

        final Object newDest = method.getActualMethod().invoke(destination, (Object[]) null);
        // recurse:
        if (newDest != null) {
            populateCache(newDest, path, Arrays.copyOf(methods, methods.length + 1));
        }
    }
}

From source file:com.kantenkugel.discordbot.jdocparser.JDoc.java

public static List<Documentation> getJava(final String name) {
    final String[] noArgNames = name.toLowerCase().split("\\(")[0].split("[#.]");
    String className = String.join(".", Arrays.copyOf(noArgNames, noArgNames.length - 1));
    String urlPath;/*www .  ja  va 2 s.co  m*/
    synchronized (javaJavaDocs) {
        urlPath = javaJavaDocs.get(name.toLowerCase());
        if (urlPath == null)
            urlPath = javaJavaDocs.get(className);
        else
            className = name.toLowerCase();
        if (urlPath == null)
            return Collections.emptyList();
    }

    Map<String, JDocParser.ClassDocumentation> resultMap = new HashMap<>();
    InputStream is = null;
    try {
        Response res = Bot.httpClient
                .newCall(new Request.Builder().url(JDocUtil.JAVA_JDOCS_PREFIX + urlPath).get().build())
                .execute();
        if (!res.isSuccessful()) {
            JDocUtil.LOG.warn("OkHttp returned failure for java8 index: " + res.code());
            return Collections.emptyList();
        }
        is = res.body().byteStream();
        JDocParser.parse(JDocUtil.JAVA_JDOCS_PREFIX, urlPath, is, resultMap);
    } catch (Exception e) {
        JDocUtil.LOG.error("Error parsing java javadocs for {}", name, e);
    } finally {
        if (is != null)
            try {
                is.close();
            } catch (Exception ignored) {
            }
    }

    if (!resultMap.containsKey(className)) {
        JDocUtil.LOG.warn("Parser didn't return wanted docs");
        return Collections.emptyList();
    }

    JDocParser.ClassDocumentation doc = resultMap.get(className);

    if (noArgNames.length == 1 || className.equalsIgnoreCase(name))
        return Collections.singletonList(doc);

    String searchObj = name.toLowerCase().substring(className.length() + 1);//class name + seperator dot
    if (doc.classValues.containsKey(searchObj)) {
        return Collections.singletonList(doc.classValues.get(searchObj));
    } else {
        boolean fuzzy = false;
        String fixedSearchObj = searchObj;
        if (fixedSearchObj.charAt(fixedSearchObj.length() - 1) != ')') {
            fixedSearchObj += "()";
            fuzzy = true;
        }
        String[] methodParts = fixedSearchObj.split("[()]");
        String methodName = methodParts[0];
        if (doc.methodDocs.containsKey(methodName.toLowerCase())) {
            return getMethodDocs(doc, methodName, fixedSearchObj, fuzzy);
        } else if (doc.inheritedMethods.containsKey(methodName.toLowerCase())) {
            return getJava(doc.inheritedMethods.get(methodName.toLowerCase()) + '.' + searchObj);
        }
        return Collections.emptyList();
    }
}