Example usage for org.apache.commons.lang ArrayUtils subarray

List of usage examples for org.apache.commons.lang ArrayUtils subarray

Introduction

In this page you can find the example usage for org.apache.commons.lang ArrayUtils subarray.

Prototype

public static boolean[] subarray(boolean[] array, int startIndexInclusive, int endIndexExclusive) 

Source Link

Document

Produces a new boolean array containing the elements between the start and end indices.

Usage

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  a2 s. c o  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;
    }
}

From source file:net.ripe.rpki.commons.crypto.util.Asn1Util.java

public static DERBitString resourceToBitString(UniqueIpResource resource, int bitCount) {
    int resourceTypeByteSize = resource.getType().getBitSize() / Byte.SIZE;

    byte[] value = resource.getValue().toByteArray();
    byte[] padded;
    if (value.length > resourceTypeByteSize) {
        // Skip extra sign byte added by BigInteger.
        padded = Arrays.copyOfRange(value, 1, value.length);
    } else if (value.length < resourceTypeByteSize) {
        // Pad with leading zero bytes (e.g. 0.12.0.0)
        padded = new byte[resourceTypeByteSize];
        System.arraycopy(value, 0, padded, resourceTypeByteSize - value.length, value.length);
    } else {/*from  w  ww .  ja va2s  .c o m*/
        padded = value;
    }

    assert padded.length == resourceTypeByteSize : "incorrect padded length";

    int byteCount = (bitCount + Byte.SIZE - 1) / Byte.SIZE;
    int unusedBits = Byte.SIZE - 1 - ((bitCount + Byte.SIZE - 1) % Byte.SIZE);
    return new DERBitString(ArrayUtils.subarray(padded, 0, byteCount), unusedBits);
}

From source file:com.delphix.session.impl.sasl.PlainSaslServer.java

public String[] parse(byte[] message) throws SaslException {
    // Validate the SASL message
    PlainSasl.validate(message);//from   w w w. jav a  2  s.c o  m

    // Append separator to the end of the message
    message = ArrayUtils.add(message, PlainSasl.SEPARATOR_BYTE);

    // Parse the user info formatted as value + SEPARATOR
    String[] userInfo = new String[3];

    byte[] segment;
    int beginIndex = 0;
    int endIndex;

    for (int i = 0; i < userInfo.length; i++) {
        endIndex = ArrayUtils.indexOf(message, PlainSasl.SEPARATOR_BYTE, beginIndex);

        if (endIndex < 0) {
            throw new SaslException("invalid sasl message");
        } else {
            segment = ArrayUtils.subarray(message, beginIndex, endIndex);
            userInfo[i] = fromUTF(segment);
        }

        beginIndex = endIndex + 1;
    }

    // Check if there is anything else beyond the last separator
    if (beginIndex < message.length) {
        throw new SaslException("invalid sasl message");
    }

    // Validate the user info
    PlainSasl.validate(userInfo);

    return userInfo;
}

From source file:mitm.common.util.MiscArrayUtils.java

/**
 * Converts the input string which is encoded in MAX_RADIX to a byte array (this function 
 * is the complement of ArrayUtils#toMaxRadix) 
 *//*w  w w. j a va  2s.c  o  m*/
public static byte[] fromMaxRadix(String inputMaxRadix) {
    Check.notNull(inputMaxRadix, "inputMaxRadix");

    BigInteger bigInt = new BigInteger(inputMaxRadix, Character.MAX_RADIX);

    byte[] bytes = bigInt.toByteArray();

    /*
     * We need to remove the first byte added by toMaxRadix.
     */
    return ArrayUtils.subarray(bytes, 1, bytes.length);
}

From source file:de.codesourcery.jasm16.compiler.io.FileObjectCodeWriterTest.java

public void testSkipToOffsetSevenBeforeWrite() throws Exception {

    final byte[] input = "test".getBytes();
    final int offset = 7;

    writer.advanceToWriteOffset(Address.byteAddress(offset));

    writer.writeObjectCode(input);// ww w. j a va  2  s  . c  o  m
    assertEquals(Address.byteAddress(offset + input.length), writer.getCurrentWriteOffset());
    writer.close();

    final byte[] data = writer.getBytes();
    //        System.out.println( Misc.toHexDumpWithAddresses( offset , data , 8 ) );
    assertEquals(offset + input.length, data.length);
    byte[] zeros = new byte[offset];
    assertTrue(ArrayUtils.isEquals(zeros, ArrayUtils.subarray(data, 0, offset)));
    assertTrue(ArrayUtils.isEquals(input, ArrayUtils.subarray(data, offset, data.length)));
}

From source file:ee.ria.xroad.proxy.clientproxy.AuthTrustVerifier.java

private static void verifyAuthCert(ClientId serviceProvider, X509Certificate[] certs, URI address)
        throws Exception {
    CertChain chain;//w w w  . j  a  va2  s  .c  o m
    List<OCSPResp> ocspResponses;
    try {
        List<X509Certificate> additionalCerts = Arrays
                .asList((X509Certificate[]) ArrayUtils.subarray(certs, 1, certs.length));
        chain = CertChain.create(serviceProvider.getXRoadInstance(), certs[0], additionalCerts);
        ocspResponses = getOcspResponses(chain.getAllCertsWithoutTrustedRoot(), address.getHost());
    } catch (CodedException e) {
        throw e.withPrefix(X_SSL_AUTH_FAILED);
    }

    CertHelper.verifyAuthCert(chain, ocspResponses, serviceProvider);
}

From source file:com.tesora.dve.server.connectionmanager.loaddata.LoadDataBlockExecutor.java

public static List<List<byte[]>> processDataBlock(ChannelHandlerContext ctx, SSConnection connMgr,
        byte[] dataBlock) throws Throwable {

    MyLoadDataInfileContext loadDataInfileContext = ctx
            .attr(MyLoadDataInfileContext.LOAD_DATA_INFILE_CONTEXT_KEY).get();
    if (loadDataInfileContext == null) {
        throw new PEException(
                "Cannot process Load Data Infile data block because load data infile context is missing.");
    }/*from   www .  j  a va  2s  . co  m*/

    //TODO: this is the only place we touch the session during the parse.  As long as this isn't sensitive to being in the session context, we can move the decode into the netty thread. -sgossard
    if (loadDataInfileContext.getCharset() == null) {
        loadDataInfileContext
                .setCharset(KnownVariables.CHARACTER_SET_CLIENT.getSessionValue(connMgr).getJavaCharset());
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Processing datablock: line prefix[" + loadDataInfileContext.getLineOption().getStarting()
                + "],  line term[" + loadDataInfileContext.getLineOption().getTerminated() + "],  col enclosed["
                + loadDataInfileContext.getColOption().getEnclosed() + "],  col escaped["
                + loadDataInfileContext.getColOption().getEscaped() + "],  col term["
                + loadDataInfileContext.getColOption().getTerminated() + "]");
        //            logger.debug("Processing datablock: data[" + query + "]" );
    }

    byte[] newDataBlock = appendPartialBlockData(loadDataInfileContext, dataBlock);
    LoadDataBlockParser parser = new LoadDataBlockParser(loadDataInfileContext);
    parser.parse(newDataBlock);

    // determine partial block
    if (dataBlock.length > 0) {
        int lastlineindex = parser.getLastLineEndIndex();
        loadDataInfileContext.appendPartialInfileDataBlock(
                ArrayUtils.subarray(newDataBlock, lastlineindex, newDataBlock.length));
        parser.getRows().remove(parser.getRows().size() - 1);
    }

    return parser.getRows();
}

From source file:com.github.tojo.session.cookies.SignatureStrategyDefaultImpl.java

@Override
public byte[] validate(byte[] signedSessionData) throws SignatureException {
    assertNotNullAndEmpty(signedSessionData);
    assertMinLength(signedSessionData, SIGNATURE_LENGTH);

    byte[] signature = ArrayUtils.subarray(signedSessionData, 0, SIGNATURE_LENGTH);
    byte[] sessionData = ArrayUtils.subarray(signedSessionData, SIGNATURE_LENGTH, signedSessionData.length);

    byte[] newSignature = ArrayUtils.subarray(sign(sessionData), 0, SIGNATURE_LENGTH);
    if (!Arrays.equals(newSignature, signature)) {
        throw new SignatureException("Invalid signature!");
    }/*from  ww w .  j ava 2s.com*/
    return sessionData;
}

From source file:com.iwgame.iwcloud.baidu.task.util.DownloadUtil.java

/**
 * url// w  ww .ja  v  a  2s. c o  m
 * @param strUrl
 *            The Url to be downloaded.
 * @param connectTimeout
 *            Connect timeout in milliseconds.
 * @param readTimeout
 *            Read timeout in milliseconds.
 * @param maxFileSize
 *            Max file size in BYTE.
 * @return The file content as byte array.
 */
public static byte[] downloadFile(String strUrl, int connectTimeout, int readTimeout, int maxFileSize)
        throws IOException {
    InputStream in = null;
    try {
        URL url = new URL(strUrl); // URL?
        URLConnection ucon = url.openConnection();
        ucon.setConnectTimeout(connectTimeout);
        ucon.setReadTimeout(readTimeout);
        ucon.connect();
        if (ucon.getContentLength() > maxFileSize) {
            String msg = "File " + strUrl + " size [" + ucon.getContentLength()
                    + "] too large, download stoped.";
            logger.error(msg);
            throw new ClientInternalException(msg);
        }
        if (ucon instanceof HttpURLConnection) {
            HttpURLConnection httpCon = (HttpURLConnection) ucon;
            if (httpCon.getResponseCode() > 399) {
                String msg = "Failed to download file " + strUrl + " server response "
                        + httpCon.getResponseMessage();
                logger.error(msg);
                throw new ClientInternalException(msg);
            }
        }
        in = ucon.getInputStream(); // ?
        byte[] byteBuf = new byte[BUFFER_SIZE];
        byte[] ret = null;
        int count, total = 0;
        // ??
        while ((count = in.read(byteBuf, total, BUFFER_SIZE - total)) > 0) {
            total += count;
            if (total + 124 >= BUFFER_SIZE)
                break;
        }
        if (total < BUFFER_SIZE - 124) {
            ret = ArrayUtils.subarray(byteBuf, 0, total);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream(MATERIAL_SIZE);
            count = total;
            total = 0;
            do {
                bos.write(byteBuf, 0, count);
                total += count;
                if (total > maxFileSize) {
                    String msg = "File " + strUrl + " size exceed [" + maxFileSize + "] download stoped.";
                    logger.error(msg);
                    throw new ClientInternalException(msg);
                }
            } while ((count = in.read(byteBuf)) > 0);
            ret = bos.toByteArray();
        }
        if (ret.length < MIN_SIZE) {
            String msg = "File " + strUrl + " size [" + maxFileSize + "] too small.";
            logger.error(msg);
            throw new ClientInternalException(msg);
        }
        return ret;
    } catch (IOException e) {
        String msg = "Failed to download file " + strUrl + " msg=" + e.getMessage();
        logger.error(msg);
        throw e;
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            logger.error("Exception while close url - ", e);
            throw e;
        }
    }
}

From source file:mitm.common.security.otp.HMACOTPGenerator.java

@Override
public String generate(byte[] secret, byte[] counter, int byteLength) throws OTPException {
    Mac mac = createMAC(secret);/*w w  w.ja  v  a 2s .  c o m*/

    /*
     * Convert the password to base32 to make it easier for end users to read and
     * limit the number of bytes to make the password not too long
     */
    return Base32.encode(ArrayUtils.subarray(mac.doFinal(counter), 0, byteLength));
}