Example usage for java.util Arrays copyOfRange

List of usage examples for java.util Arrays copyOfRange

Introduction

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

Prototype

public static boolean[] copyOfRange(boolean[] original, int from, int to) 

Source Link

Document

Copies the specified range of the specified array into a new array.

Usage

From source file:net.ripe.rpki.validator.util.TrustAnchorLocator.java

/**
 * @see http://tools.ietf.org/html/draft-ietf-sidr-ta-07
 *//*from w  w  w  . j  a  v a  2 s .co m*/
private static TrustAnchorLocator readStandardTrustAnchorLocator(File file, String contents)
        throws URISyntaxException {
    String caName = Files.getNameWithoutExtension(file.getName());
    String[] lines = contents.trim().split("\\s*(\r\n|\n\r|\n|\r)\\s*");
    URI location = new URI(lines[0]);
    int i = 1;
    while (lines[i].startsWith("rsync://")) {
        i++;
    }
    String publicKeyInfo = StringUtils.join(Arrays.copyOfRange(lines, i, lines.length));
    return new TrustAnchorLocator(file, caName, location, publicKeyInfo, new ArrayList<URI>());
}

From source file:com.github.mrstampy.pprspray.core.streamer.chunk.AbstractMediaChunk.java

/**
 * Constructor assumes that the message supplied is of the correct media type,
 * as identified by implementations.//  w ww. j a v  a 2  s.c om
 *
 * @param message
 *          the message
 * @param expected
 *          the expected
 */
protected AbstractMediaChunk(byte[] message, MediaStreamType expected) {
    extractMediaStreamType(message, expected);
    extractHeaderLength(message);
    extractMessageHash(message);
    extractMediaHash(message);
    extractSequence(message);
    extractCustomHeaderChunk(message);
    extractAckRequired(message);
    if (message.length > getHeaderLength())
        setData(Arrays.copyOfRange(message, getHeaderLength(), message.length));
}

From source file:com.mitre.core.search.solrfacetsearch.provider.impl.SolrFirstVariantCategoryManager.java

/**
 * Generate a list of {@link SolrFirstVariantCategoryEntryData} based on a Solr property String that holds the first
 * category name list.// w  w  w  .j  ava2 s. c  o m
 *
 * @param solrProperty
 *           The first category name list.
 * @return List of {@link SolrFirstVariantCategoryEntryData};
 */
public List<SolrFirstVariantCategoryEntryData> buildFirstVariantCategoryListFromSolrProperty(
        final String solrProperty) {
    final List<SolrFirstVariantCategoryEntryData> entries = new ArrayList<>();
    // Split by beans. Discard first entry in array, as it will be empty
    final String[] original = solrProperty.split(BEFORE_BEAN);
    if (original.length > 1) {
        final String[] propertyEntries = Arrays.copyOfRange(original, 1, original.length);
        for (final String propertyEntry : propertyEntries) {
            final String[] tokens = propertyEntry.split(FIELD_SEPARATOR);
            if (tokens != null && tokens.length == TOTAL_FIELDS) {
                for (int i = 0; i < tokens.length; i += TOTAL_FIELDS) {
                    final SolrFirstVariantCategoryEntryData entry = new SolrFirstVariantCategoryEntryData();
                    entry.setCategoryName(tokens[i]);
                    entry.setVariantCode(tokens[i + 1]);
                    entries.add(entry);
                }
            } else {
                throw new IllegalArgumentException("The solrProperty [" + solrProperty + "] should have "
                        + TOTAL_FIELDS + " fields separated by '" + FIELD_SEPARATOR + "'");
            }

        }
    }
    return entries;
}

From source file:com.github.tell.mathematics.combinatorics.Combination.java

public T[][] makeCombination() {
    if (numberOfSelection == 0) {
        //noinspection unchecked
        return (T[][]) Array.newInstance(cls, 1, 0);

    } else if (numberOfSelection == 1) {
        @SuppressWarnings("unchecked")
        final T[][] result = (T[][]) Array.newInstance(cls, elements.length, 0);
        assert result.length == elements.length : String.format("result = %s, numberOfSelection = %s",
                Arrays.deepToString(result), numberOfSelection);
        for (int i = 0; i < elements.length; i++) {
            result[i] = Arrays.copyOfRange(elements, i, i + 1);
        }//w  ww  .j a  v  a2s.c  o  m
        return result;

    } else if (numberOfSelection == elements.length) {
        @SuppressWarnings("unchecked")
        final T[][] result = (T[][]) Array.newInstance(cls, 1, 0);
        result[0] = ArrayUtils.clone(elements);
        return result;

    } else if (numberOfSelection == elements.length - 1) {
        @SuppressWarnings("unchecked")
        final T[][] result = (T[][]) Array.newInstance(cls, elements.length, 0);
        for (int i = elements.length - 1; i >= 0; i--) {
            final int j = elements.length - 1 - i;
            result[j] = Arrays.copyOf(elements, i);
            result[j] = ArrayUtils.addAll(result[j], ArrayUtils.subarray(elements, i + 1, elements.length));
            logger.trace("generated array = {}", Arrays.deepToString(result[j]));
        }
        return result;

    } else {
        final T[] partialElements = Arrays.copyOf(elements, elements.length - 1);

        logger.trace("partialElements = {}, numberOfSelection = {}", Arrays.deepToString(partialElements),
                numberOfSelection);

        final Combination<T> leftHandSideGenerator = new Combination<T>(partialElements, numberOfSelection);
        final T[][] leftCombination = leftHandSideGenerator.makeCombination();

        final Combination<T> rightHandSideGenerator = new Combination<T>(partialElements,
                numberOfSelection - 1);
        final T[][] rightCombination = rightHandSideGenerator.makeCombination();
        for (int i = 0; i < rightCombination.length; i++) {
            rightCombination[i] = ArrayUtils.add(rightCombination[i], elements[elements.length - 1]);
        }

        //noinspection unchecked
        return ArrayUtils.addAll(leftCombination, rightCombination);
    }
}

From source file:com.navercorp.pinpoint.common.buffer.FixedBufferTest.java

@Test
public void testPadBytes() throws Exception {
    int TOTAL_LENGTH = 20;
    int TEST_SIZE = 10;
    Buffer buffer = new FixedBuffer(32);
    byte[] test = new byte[10];

    random.nextBytes(test);/*from ww  w .  j  a va 2 s  . c  o m*/

    buffer.putPadBytes(test, TOTAL_LENGTH);

    byte[] result = buffer.getBuffer();
    Assert.assertEquals(result.length, TOTAL_LENGTH);
    Assert.assertTrue("check data",
            Arrays.equals(Arrays.copyOfRange(test, 0, TEST_SIZE), Arrays.copyOfRange(result, 0, TEST_SIZE)));
    byte[] padBytes = new byte[TOTAL_LENGTH - TEST_SIZE];
    Assert.assertTrue("check pad", Arrays.equals(Arrays.copyOfRange(padBytes, 0, TEST_SIZE),
            Arrays.copyOfRange(result, TEST_SIZE, TOTAL_LENGTH)));

}

From source file:com.edmunds.etm.tools.urltoken.application.UrlTokenTool.java

public void run(String[] args) {

    if (args.length < 1) {
        printUsage();//from   w  w w. j a  va  2 s. c o m
        return;
    }

    String commandName = args[0];
    Command cmd = commandLocator.get(commandName);
    if (cmd == null) {
        printUsage();
        return;
    }
    command = cmd;
    if (args.length > 1) {
        arguments = Arrays.copyOfRange(args, 1, args.length);
    } else {
        arguments = new String[] {};
    }

    connection.connect();

    try {
        executionComplete.await();
    } catch (InterruptedException e) {
        logger.warn("Main thread interrupted, exiting", e);
    } finally {
        connection.close();
    }
}

From source file:com.moz.fiji.schema.util.SplitKeyFile.java

/**
 * Decodes a string encoded row key./*  ww w .j a v a  2 s  .  c  o m*/
 *
 * @param encoded Encoded row key.
 * @return the row key, as a byte array.
 * @throws IOException on I/O error.
 */
public static byte[] decodeRowKey(String encoded) throws IOException {
    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    int index = 0;
    final byte[] bytes = Bytes.toBytes(encoded);
    while (index < bytes.length) {
        final byte data = bytes[index++];

        if (data != '\\') {
            os.write(data);
        } else {
            if (index == bytes.length) {
                throw new IOException(
                        String.format("Invalid trailing escape in encoded row key: '%s'.", encoded));
            }
            final byte escaped = bytes[index++];

            switch (escaped) {
            case '\\': {
                // Escaped backslash:
                os.write('\\');
                break;
            }
            case 'x': {
                // Escaped byte in hexadecimal:
                if (index + 1 >= bytes.length) {
                    throw new IOException(
                            String.format("Invalid hexadecimal escape in encoded row key: '%s'.", encoded));
                }
                final String hex = Bytes.toString(Arrays.copyOfRange(bytes, index, index + 2));
                try {
                    final int decodedByte = Integer.parseInt(hex, 16);
                    if ((decodedByte < 0) || (decodedByte > 255)) {
                        throw new IOException(
                                String.format("Invalid hexadecimal escape in encoded row key: '%s'.", encoded));
                    }
                    os.write(decodedByte);
                } catch (NumberFormatException nfe) {
                    throw new IOException(
                            String.format("Invalid hexadecimal escape in encoded row key: '%s'.", encoded));
                }
                index += 2;
                break;
            }
            default:
                throw new IOException(String.format("Invalid escape in encoded row key: '%s'.", encoded));
            }
        }
    }
    return os.toByteArray();
}

From source file:com.twitter.elephantbird.pig.piggybank.Invoker.java

private static Object[] dropFirstObject(Object[] original) {
    if (original.length < 2) {
        return new Object[0];
    } else {//from   w w w.  j a  v  a2  s.com
        return Arrays.copyOfRange(original, 1, original.length - 1);
    }
}

From source file:alluxio.cli.AbstractShell.java

/**
 * Handles the specified shell command request, displaying usage if the command format is invalid.
 *
 * @param argv [] Array of arguments given by the user's input from the terminal
 * @return 0 if command is successful, -1 if an error occurred
 *///from  w  w  w  . j  av  a  2  s . co m
public int run(String... argv) {
    if (argv.length == 0) {
        printUsage();
        return -1;
    }

    // Sanity check on the number of arguments
    String cmd = argv[0];
    Command command = mCommands.get(cmd);

    if (command == null) {
        String[] replacementCmd = getReplacementCmd(cmd);
        if (replacementCmd == null) {
            // Unknown command (we didn't find the cmd in our dict)
            System.err.println(String.format("%s is an unknown command.", cmd));
            printUsage();
            return -1;
        } else {
            // Handle command alias, and print out WARNING message for deprecated cmd.
            String deprecatedMsg = "WARNING: " + cmd + " is deprecated. Please use "
                    + StringUtils.join(replacementCmd, " ") + " instead.";
            System.out.println(deprecatedMsg);

            String[] replacementArgv = (String[]) ArrayUtils.addAll(replacementCmd,
                    ArrayUtils.subarray(argv, 1, argv.length));
            return run(replacementArgv);
        }
    }

    String[] args = Arrays.copyOfRange(argv, 1, argv.length);
    CommandLine cmdline;
    try {
        cmdline = command.parseAndValidateArgs(args);
    } catch (InvalidArgumentException e) {
        System.out.println("Usage: " + command.getUsage());
        LOG.error("Invalid arguments for command {}:", command.getCommandName(), e);
        return -1;
    }

    // Handle the command
    try {
        return command.run(cmdline);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        LOG.error("Error running " + StringUtils.join(argv, " "), e);
        return -1;
    }
}