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:com.itemanalysis.psychometrics.irt.model.IrmGPCM2.java

private double numer(double theta, double[] iparam, int category, double D) {
    double Zk = 0;
    double a = iparam[0];
    double b = iparam[1];
    double[] t = Arrays.copyOfRange(iparam, 2, iparam.length);

    //first category
    Zk = D * a * (theta - b);//from  ww  w  . j a v  a  2  s  . c  o  m

    for (int k = 0; k < category; k++) {
        Zk += D * a * (theta - b + t[k]);
    }
    return Math.exp(Zk);
}

From source file:my.adam.smo.common.SymmetricEncryptionBox.java

public byte[] getIV(byte[] cryptogram) {
    return Arrays.copyOfRange(cryptogram, 0, ivLength);
}

From source file:com.facebook.presto.accumulo.examples.Main.java

@SuppressWarnings("unchecked")
@Override//from  ww w . j  a va 2 s .co m
public int run(String[] args) throws Exception {
    // If no arguments, print help
    if (args.length == 0) {
        printTools();
        return 1;
    }

    // Validate PRESTO_HOME is set to pull accumulo properties from config path
    String prestoHome = System.getenv("PRESTO_HOME");
    if (prestoHome == null) {
        System.err.println("PRESTO_HOME is not set.  This is required to locate the "
                + "etc/catalog/accumulo.properties file");
        System.exit(1);
    }

    // Create an AccumuloConfig from the accumulo properties file
    AccumuloConfig config = com.facebook.presto.accumulo.tools.Main
            .fromFile(new File(System.getenv("PRESTO_HOME"), "etc/catalog/accumulo.properties"));

    // Get the tool name from the first argument
    String toolName = args[0];
    Task t = Main.getTask(toolName);
    if (t == null) {
        System.err.println(format("Unknown tool %s", toolName));
        printTools();
        return 1;
    }

    // Add the help option and all options for the tool
    Options opts = new Options();
    opts.addOption(HELP);
    for (Option o : (Collection<Option>) t.getOptions().getOptions()) {
        opts.addOption(o);
    }

    // Parse command lines
    CommandLine cmd;
    try {
        cmd = new GnuParser().parse(opts, Arrays.copyOfRange(args, 1, args.length));
    } catch (ParseException e) {
        printHelp(t);
        return 1;
    }

    // Print help if the option is set
    if (cmd.hasOption(HELP.getLongOpt())) {
        printHelp(t);
        return 0;
    } else {
        // Run the tool and print help if anything bad happens
        int code = t.run(config, cmd);
        if (code != 0) {
            printHelp(t);
        }
        return code;
    }
}

From source file:com.asakusafw.runtime.io.text.directio.AbstractTextStreamFormatTest.java

/**
 * input - w/ splitter./*  www  .  j a v a  2 s .c  o  m*/
 * @throws Exception if failed
 */
@Test
public void input_splitter_trim_lead() throws Exception {
    MockFormat format = format(3).withInputSplitter(InputSplitters.byLineFeed());
    String[][] data = { { "A", "B", "C", }, { "D", "E", "F", }, { "G", "H", "I", }, };
    try (ModelInput<String[]> in = format.createInput(String[].class, "dummy", input(data), 1,
            Long.MAX_VALUE)) {
        String[][] result = collect(3, in);
        assertThat(result, is(Arrays.copyOfRange(data, 1, 3)));
    }
}

From source file:net.fenyo.mail4hotspot.dns.Msg.java

private byte[] process(final AdvancedServices advancedServices, final Inet4Address address)
        throws GeneralException {
    // log.debug("processing message of type " + input_buffer[0]);
    // for (byte b : input_buffer) log.debug("received byte: [" + b + "]");

    if (input_buffer.length == 0)
        throw new GeneralException("invalid size");
    if (input_buffer[0] == 0) {
        // UTF-8 message type

        final ByteBuffer bb = ByteBuffer.allocate(input_buffer.length - 1);
        bb.put(input_buffer, 1, input_buffer.length - 1);
        bb.position(0);/*from   w w w . jav  a  2s  .c  o  m*/
        final String query = Charset.forName("UTF-8").decode(bb).toString();
        // log.debug("RECEIVED query: [" + query + "]");

        final String reply = advancedServices.processQueryFromClient(query, address);

        // this buffer may not be backed by an accessible byte array, so we do not use Charset.forName("UTF-8").encode(reply).array() to fill output_buffer
        final ByteBuffer ob = Charset.forName("UTF-8").encode(reply);
        ob.get(output_buffer = new byte[ob.limit()]);

        output_size = output_buffer.length;

    } else {
        // binary message type
        // log.debug("processing binary message");

        final ByteBuffer bb = ByteBuffer.allocate(input_buffer[0]);
        bb.put(input_buffer, 1, input_buffer[0]);
        bb.position(0);
        final String query = Charset.forName("UTF-8").decode(bb).toString();
        //      log.debug("RECEIVED query: [" + query + "]");

        final BinaryMessageReply reply = advancedServices.processBinaryQueryFromClient(query,
                Arrays.copyOfRange(input_buffer, input_buffer[0] + 1, input_buffer.length), address);

        // this buffer may not be backed by an accessible byte array, so we do not use Charset.forName("UTF-8").encode(reply).array() to fill string_part
        final ByteBuffer ob = Charset.forName("UTF-8").encode(reply.reply_string);
        final byte[] string_part = new byte[ob.limit()];
        ob.get(string_part);

        if (string_part.length > 255)
            throw new GeneralException("string_part too long");
        output_buffer = new byte[string_part.length + reply.reply_data.length + 1];
        output_buffer[0] = (byte) string_part.length;
        for (int i = 0; i < string_part.length; i++)
            output_buffer[i + 1] = string_part[i];
        for (int i = 0; i < reply.reply_data.length; i++)
            output_buffer[string_part.length + i + 1] = reply.reply_data[i];
        output_size = output_buffer.length;
    }

    synchronized (compressed) {
        // http://docs.oracle.com/javase/7/docs/api/java/util/zip/Deflater.html#deflate(byte[])
        // log.debug("processing binary message: length before compressing: " + output_buffer.length);
        final Deflater compresser = new Deflater();
        compresser.setInput(output_buffer);
        compresser.finish();
        final int nbytes = compresser.deflate(compressed);
        //         log.debug("RET: " + nbytes);
        //         log.debug("COMPRESSED: " + compressed.length);
        // log.debug("processing binary message: length after compressing: " + nbytes);
        if (compressed.length == nbytes) {
            log.error("compressed buffer too small...");
            throw new GeneralException("compressed buffer too small...");
        }
        output_buffer = Arrays.copyOf(compressed, nbytes);
        output_size = output_buffer.length;
    }

    synchronized (is_processed) {
        is_processed = true;
    }

    return new byte[] { 'E', 0 }; // 'E'rror 0 == OK
}

From source file:com.goncalomb.bukkit.mylib.command.MySubCommand.java

void execute(CommandSender sender, String label, String[] args, int argsIndex) {
    // Find sub-command.
    if (argsIndex < args.length) {
        MySubCommand subCommand = _subCommands.get(args[argsIndex].toLowerCase());
        if (subCommand != null) {
            subCommand.execute(sender, label, args, argsIndex + 1);
            return;
        }/*from w  w  w .j a  va 2  s  . c o  m*/
    }
    // Sub-command not found or no more arguments, let's try to run this one.
    if (_exeMethod != null) {
        if (_type.isValidSender(sender)) {
            if (sender.hasPermission(_perm)) {
                int argsLeft = args.length - argsIndex;
                if (argsLeft >= _minArgs && argsLeft <= _maxArgs) {
                    if (invokeExeMethod(sender, Arrays.copyOfRange(args, argsIndex, args.length))) {
                        return;
                    }
                }
            } else {
                sender.sendMessage("cYou don't have permission to use that command!");
                return;
            }
        } else {
            sender.sendMessage(_type.INVALID_MESSAGE);
            return;
        }
    }
    // Missing arguments or failed command, let's send usage and sub-commands!
    String prefix = "/" + label + " "
            + (argsIndex > 0 ? StringUtils.join(args, ' ', 0, argsIndex).toLowerCase() + " " : "");
    boolean sentUsage = false;
    if (_exeMethod != null && sender.hasPermission(_perm)) {
        sender.sendMessage(ChatColor.RESET + prefix + _usage);
        sentUsage = true;
    }
    if (sendAllSubCommands(sender, this, prefix) == 0 && !sentUsage) {
        sender.sendMessage("cYou don't have permission to use that command!");
    }
}

From source file:com.tinspx.util.io.ChannelSourceTest.java

@Test
public void testByteBufferSource() throws IOException {
    int off = 443, len = 17167;
    ByteBuffer buf, direct;/*from   ww  w .j  av a2 s  . c om*/
    direct = ByteBuffer.allocateDirect(INPUT.length);
    assertTrue(direct.isDirect());
    direct.put(INPUT);
    byte[] sub = Arrays.copyOfRange(INPUT, off, off + len);

    //full input
    buf = ByteBuffer.wrap(INPUT);
    ByteSourceTests.testByteSource(ChannelSource.of(buf), INPUT);
    assertEquals(0, buf.position());
    assertEquals(INPUT.length, buf.limit());

    buf = ByteBuffer.wrap(INPUT).asReadOnlyBuffer();
    ByteSourceTests.testByteSource(ChannelSource.of(buf), INPUT);
    assertEquals(0, buf.position());
    assertEquals(INPUT.length, buf.limit());

    direct.clear();
    buf = direct;
    ByteSourceTests.testByteSource(ChannelSource.of(buf), INPUT);
    assertEquals(0, buf.position());
    assertEquals(INPUT.length, buf.limit());

    //sub range of input
    buf = ByteBuffer.wrap(INPUT);
    buf.clear().position(off).limit(off + len);
    ByteSourceTests.testByteSource(ChannelSource.of(buf), sub);
    assertEquals(off, buf.position());
    assertEquals(off + len, buf.limit());

    buf = ByteBuffer.wrap(INPUT).asReadOnlyBuffer();
    buf.clear().position(off).limit(off + len);
    ByteSourceTests.testByteSource(ChannelSource.of(buf), sub);
    assertEquals(off, buf.position());
    assertEquals(off + len, buf.limit());

    direct.clear();
    buf = direct;
    buf.clear().position(off).limit(off + len);
    ByteSourceTests.testByteSource(ChannelSource.of(buf), sub);
    assertEquals(off, buf.position());
    assertEquals(off + len, buf.limit());
}

From source file:com.goncalomb.bukkit.bkglib.bkgcommand.BKgSubCommand.java

void execute(CommandSender sender, String label, String[] args, int argsIndex) {
    // Find sub-command.
    if (argsIndex < args.length) {
        BKgSubCommand subCommand = _subCommands.get(args[argsIndex].toLowerCase());
        if (subCommand != null) {
            subCommand.execute(sender, label, args, argsIndex + 1);
            return;
        }/* www . j  a v  a 2s .c  o  m*/
    }
    // Sub-command not found or no more arguments, let's try to run this one.
    if (_exeMethod != null) {
        if (_type.isValidSender(sender)) {
            if (sender.hasPermission(_perm)) {
                int argsLeft = args.length - argsIndex;
                if (argsLeft >= _minArgs && argsLeft <= _maxArgs) {
                    if (invokeExeMethod(sender, Arrays.copyOfRange(args, argsIndex, args.length))) {
                        return;
                    }
                }
            } else {
                sender.sendMessage(Lang._(null, "commands.no-perm"));
                return;
            }
        } else {
            sender.sendMessage(_type.getInvalidSenderMessage());
            return;
        }
    }
    // Missing arguments or failed command, let's send usage and sub-commands!
    String prefix = "/" + label + " "
            + (argsIndex > 0 ? StringUtils.join(args, ' ', 0, argsIndex).toLowerCase() + " " : "");
    boolean sentUsage = false;
    if (_exeMethod != null && sender.hasPermission(_perm)) {
        sender.sendMessage(ChatColor.RESET + prefix + _usage);
        sentUsage = true;
    }
    if (sendAllSubCommands(sender, this, prefix) == 0 && !sentUsage) {
        sender.sendMessage(Lang._(null, "commands.no-perm"));
    }
}

From source file:com.yahoo.storm.yarn.Client.java

/**
 * @param args the command line arguments
 * @throws Exception  //from w ww .j a v a  2 s.  c om
 */
@SuppressWarnings("rawtypes")
public void execute(String[] args) throws Exception {
    HashMap<String, ClientCommand> commands = new HashMap<String, ClientCommand>();
    HelpCommand help = new HelpCommand(commands);
    commands.put("help", help);
    commands.put("launch", new LaunchCommand());
    commands.put("setStormConfig", new StormMasterCommand(StormMasterCommand.COMMAND.SET_STORM_CONFIG));
    commands.put("getStormConfig", new StormMasterCommand(StormMasterCommand.COMMAND.GET_STORM_CONFIG));
    commands.put("addSupervisors", new StormMasterCommand(StormMasterCommand.COMMAND.ADD_SUPERVISORS));
    commands.put("startNimbus", new StormMasterCommand(StormMasterCommand.COMMAND.START_NIMBUS));
    commands.put("stopNimbus", new StormMasterCommand(StormMasterCommand.COMMAND.STOP_NIMBUS));
    commands.put("startUI", new StormMasterCommand(StormMasterCommand.COMMAND.START_UI));
    commands.put("stopUI", new StormMasterCommand(StormMasterCommand.COMMAND.STOP_UI));
    commands.put("startSupervisors", new StormMasterCommand(StormMasterCommand.COMMAND.START_SUPERVISORS));
    commands.put("stopSupervisors", new StormMasterCommand(StormMasterCommand.COMMAND.STOP_SUPERVISORS));
    commands.put("shutdown", new StormMasterCommand(StormMasterCommand.COMMAND.SHUTDOWN));
    commands.put("version", new VersionCommand());

    String commandName = null;
    String[] commandArgs = null;
    if (args.length < 1) {
        commandName = "help";
        commandArgs = new String[0];
    } else {
        commandName = args[0];
        commandArgs = Arrays.copyOfRange(args, 1, args.length);
    }
    ClientCommand command = commands.get(commandName);
    if (command == null) {
        LOG.error("ERROR: " + commandName + " is not a supported command.");
        help.printHelpFor(null);
        System.exit(1);
    }
    Options opts = command.getOpts();
    if (!opts.hasOption("h")) {
        opts.addOption("h", "help", false, "print out a help message");
    }
    CommandLine cl = new GnuParser().parse(command.getOpts(), commandArgs);
    if (cl.hasOption("help")) {
        help.printHelpFor(Arrays.asList(commandName));
    } else {

        command.process(cl);
    }
}

From source file:com.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java

/**
 * {@inheritDoc}//w w  w. j  av a2 s .c o m
 */
@Override
public final byte[] mac(byte[] dataToMac, byte[] key) throws McbpCryptoException {
    // First create an array of MAC BLOCK Size all set to 0x00
    int macSize = (int) Math.ceil(((double) dataToMac.length + 1) / 8) * 8;
    byte[] mac = new byte[macSize];
    System.arraycopy(dataToMac, 0, mac, 0, dataToMac.length);

    // Add the padding at the relevant location. The padding is defined 0x80, 0x00 ... 0x00
    mac[dataToMac.length] = (byte) 0x80;

    final byte[] keyL = Arrays.copyOfRange(key, 0, key.length / 2);
    final byte[] keyR = Arrays.copyOfRange(key, key.length / 2, key.length);

    // ----- Perform DES3 Encryption to Calculate MAC ---------
    byte[] desResult = new byte[8];
    // The the 8 most right bytes of the first desCbc encryption
    System.arraycopy(desCbc(mac, keyL, Mode.ENCRYPT), macSize - 8, desResult, 0, 8);
    byte[] bMac = des(desResult, keyR, Mode.DECRYPT);
    byte[] result = des(bMac, keyL, Mode.ENCRYPT);

    // Clear temporary data structures
    Utils.clearByteArray(bMac);
    Utils.clearByteArray(mac);
    Utils.clearByteArray(keyL);
    Utils.clearByteArray(keyR);
    Utils.clearByteArray(desResult);

    return result;
}