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:org.tacografo.file.CardBlockFile.java

/**
 * Constructor que leera los bytes del fichero pasado como array de bytes para interpretar los
 * datos y asignarlo a los bloque correspondientes
 * @throws Exception //from   www .  j  a  v a 2 s .c o  m
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public CardBlockFile(byte[] bytes) throws Exception {
    HashMap<String, Block> lista = new HashMap();
    this.listBlock = new HashMap();
    try {
        int start = 0;
        while (start < bytes.length) {
            int fid = Number.getNumber(Arrays.copyOfRange(bytes, start, start += 2));
            if (this.existe_Fid(fid)) {
                byte tipo = bytes[start];
                start += 1;
                Integer longitud = (int) Number.getNumber(Arrays.copyOfRange(bytes, start, start += 2));
                byte[] datos = new byte[longitud];
                datos = Arrays.copyOfRange(bytes, start, start += longitud);
                // tipo de archivo 0 = bloque de dato -- 1 = certificado
                if (tipo == 0) {
                    Block block = (Block) FactoriaBloques.getFactoria(fid, datos);
                    if (block != null) {
                        this.listBlock.put(block.getFID(), (Block) block);

                    }
                }
            } else {
                throw new Error("Block not found");
            }

        }

    } catch (IOException e) {
        System.out.println(e.getMessage());
    }

    this.asignarBloques();

}

From source file:com.glaf.core.util.BinaryUtils.java

/**
 * Returns a copy of the bytes from the given <code>ByteBuffer</code>,
 * ranging from the the buffer's current position to the buffer's limit; or
 * null if the input is null./*from ww  w .  ja  va  2  s .c  om*/
 * <p>
 * The internal states of the given byte buffer will be restored when this
 * method completes execution.
 * <p>
 * When handling <code>ByteBuffer</code> from user's input, it's typical to
 * call the {@link #copyBytesFrom(ByteBuffer)} instead of
 * {@link #copyAllBytesFrom(ByteBuffer)} so as to account for the position
 * of the input <code>ByteBuffer</code>. The opposite is typically true,
 * however, when handling <code>ByteBuffer</code> from withint the
 * unmarshallers of the low-level clients.
 */
public static byte[] copyBytesFrom(ByteBuffer bb) {
    if (bb == null)
        return null;
    if (bb.hasArray())
        return Arrays.copyOfRange(bb.array(), bb.position(), bb.limit());
    bb.mark();
    try {
        byte[] dst = new byte[bb.remaining()];
        bb.get(dst);
        return dst;
    } finally {
        bb.reset();
    }
}

From source file:edu.msu.cme.rdp.readseq.utils.SequenceTrimmer.java

public static TrimStats getStats(Sequence seq, int trimStart, int trimStop) {
    if (trimStart >= trimStop) {
        throw new IllegalArgumentException("Trim start has to come before trim end");
    }/*from  www. jav  a  2 s.  co m*/

    TrimStats ret = new TrimStats();
    int modelPos = 0;
    int seqPos = 0;
    int index;
    int filled = 0;
    char b;
    boolean ischar, isgap, ismodel, isupper, intrim;

    int alnStart = -1;

    char[] bases = seq.getSeqString().toCharArray();

    for (index = 0; index < bases.length; index++) {
        b = bases[index];

        ischar = Character.isLetter(b);
        isupper = ischar && Character.isUpperCase(b);
        isgap = !ischar && (b == '.' || b == '~' || b == '-');
        ismodel = (b == '-') || isupper;
        intrim = (modelPos >= trimStart && modelPos < trimStop);

        if (ischar) {
            seqPos++;

            if (b == 'n' || b == 'N') {
                ret.numNs++;

                if (intrim) {
                    ret.nsInTrim++;
                }
            }

            if (intrim) {
                ret.trimmedLength++;
            }
        }

        if (ismodel) {
            if (modelPos == trimStart) {
                ret.seqTrimStart = seqPos;
                alnStart = index;
            }
            if (modelPos >= trimStart && modelPos < trimStop) {
                filled++;
                if (ischar) {
                    ret.filledRatio++;
                }
            }

            if (modelPos == trimStop) {
                ret.seqTrimStop = seqPos;
                ret.trimmedBases = Arrays.copyOfRange(bases, alnStart, index);
            }

            if (!isgap) {
                if (ret.seqStart == -1) {
                    ret.seqStart = modelPos;
                }
                ret.seqStop = modelPos;
            }

            modelPos++;
        }
    }

    ret.seqLength = seqPos;
    ret.modelLength = modelPos;
    ret.filledRatio /= filled;

    return ret;
}

From source file:com.atomicleopard.thundr.gae.channels.ChannelService.java

private static final String limitTo64Bytes(String clientId) {
    try {/*www  . j a  va  2  s.  c  o m*/
        byte[] bytes = clientId.getBytes("UTF-8");
        byte[] newBytes = Arrays.copyOfRange(bytes, Math.max(0, bytes.length - 64), bytes.length);
        return new String(newBytes, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        Logger.warn(
                "Unsupported encoding exception while determining clientId, making a best guess and continuing: %s",
                e.getMessage());
        return StringUtils.reverse(StringUtils.reverse(clientId).substring(0, 64));
    }
}

From source file:com.bunjlabs.fuga.templates.TemplateApi.java

/**
 *
 * @param args Input arguments/*from  w w  w  .  jav  a  2  s .c  om*/
 * @return Produced string
 */
public String format(Object... args) {
    if (args.length == 0) {
        return "";
    }
    if (args.length == 1) {
        return args[0] != null ? args[0].toString() : "";
    }

    return String.format(args[0].toString(), Arrays.copyOfRange(args, 1, args.length));
}

From source file:hivemall.anomaly.SingularSpectrumTransform.java

@Override
public void update(@Nonnull final Object arg, @Nonnull final double[] outScores) throws HiveException {
    double x = PrimitiveObjectInspectorUtils.getDouble(arg, oi);
    xRing.add(x).toArray(xSeries, true /* FIFO */);

    // need to wait until the buffer is filled
    if (!xRing.isFull()) {
        outScores[0] = 0.d;/*from w  w w. j av a  2s .  co m*/
    } else {
        // create past trajectory matrix and find its left singular vectors
        RealMatrix H = new Array2DRowRealMatrix(window, nPastWindow);
        for (int i = 0; i < nPastWindow; i++) {
            H.setColumn(i, Arrays.copyOfRange(xSeries, i, i + window));
        }

        // create current trajectory matrix and find its left singular vectors
        RealMatrix G = new Array2DRowRealMatrix(window, nCurrentWindow);
        int currentHead = pastSize + currentOffset;
        for (int i = 0; i < nCurrentWindow; i++) {
            G.setColumn(i, Arrays.copyOfRange(xSeries, currentHead + i, currentHead + i + window));
        }

        switch (scoreFunc) {
        case svd:
            outScores[0] = computeScoreSVD(H, G);
            break;
        case ika:
            outScores[0] = computeScoreIKA(H, G);
            break;
        default:
            throw new IllegalStateException("Unexpected score function: " + scoreFunc);
        }
    }
}

From source file:com.zack6849.irc.bridgebot.BukkitHandler.java

@EventHandler
public void onCommand(PlayerCommandPreprocessEvent event) {
    String command = event.getMessage().substring(1);
    String[] args = event.getMessage().split(" ");
    if (command.startsWith("me") && args.length > 1) {
        String username = event.getPlayer().getDisplayName();
        String playername = event.getPlayer().getName();
        String message = StringUtils.join(Arrays.copyOfRange(args, 1, args.length), " ");
        String format = config.getProperty("MC-ACTION-FORMAT").replace("%MESSAGE%", message)
                .replace("%PLAYER%", username).replace("%PLAYERNAME%", playername);
        sendMessage(Utils.bukkitcolorize(format));
    }//from ww  w. j  ava2 s.  co  m
}

From source file:com.epam.dlab.Help.java

/** Print help screen for billing tool. 
 * @throws InitializationException */
public static void usage(String... args) throws InitializationException {
    if (args == null || args.length == 0) {
        printHelp("usage", null);
    } else if (args[0].equalsIgnoreCase("conf")) {
        printHelp("conf", findModules());
    } else {/*  w  ww  .  j  a  va 2s .  c o  m*/
        ModuleType type = ModuleType.of(args[0]);
        if (type == null) {
            System.out.println("Unknown --help " + args[0] + " command.");
        } else if (args.length < 2) {
            System.out.println("Missing the type of module.");
            String typeNames = findModules().get(type.toString() + "s");
            if (typeNames != null) {
                System.out.println("Must be one of next: " + typeNames);
            }
        } else if (args.length > 2) {
            System.out.println("Extra arguments in command: "
                    + StringUtils.join(Arrays.copyOfRange(args, 2, args.length), " "));
        } else {
            System.out.println(findModuleHelp(type, args[1]));
        }
    }
}

From source file:com.bitbreeds.webrtc.stun.StunMessage.java

public void validate(String pass, byte[] data) {
    StunAttribute fingerprint = this.attributeSet.remove(StunAttributeTypeEnum.FINGERPRINT);
    String finger = new String(fingerprint.getData());
    byte[] fingerprintData = Arrays.copyOfRange(data, 0, data.length - fingerprint.getLength() - 4);
    final CRC32 crc = new CRC32();
    crc.update(fingerprintData);/*from   w  w w.j  av  a  2 s. co m*/
    String comp = new String(SignalUtil.xor(SignalUtil.fourBytesFromInt((int) crc.getValue()),
            new byte[] { 0x53, 0x54, 0x55, 0x4e }));

    if (!comp.equals(finger)) {
        throw new StunError("Fingerprint bad, computed=" + comp + " sent=" + finger);
    }

    StunAttribute integrity = attributeSet.remove(StunAttributeTypeEnum.MESSAGE_INTEGRITY);

    byte[] integrityData = Arrays.copyOfRange(data, 0,
            data.length - fingerprint.getLength() - integrity.getLength() - 8);
    byte[] lgt = SignalUtil.twoBytesFromInt(fingerprintData.length - 20);
    integrityData[2] = lgt[0];
    integrityData[3] = lgt[1];

    byte[] mac = SignalUtil.hmacSha1(integrityData, pass.getBytes());

    if (!Arrays.equals(mac, integrity.getData())) {
        throw new StunError("Integrity bad, computed=" + Hex.encodeHexString(mac) + " sent="
                + Hex.encodeHexString(integrity.getData()));
    }
}

From source file:dev.maisentito.suca.commands.BotCommands.java

public static String[] parseCommandArgs(String message) {
    String[] parts = message.trim().substring(1).split("\\s+");
    if (parts.length > 1) {
        return Arrays.copyOfRange(parts, 1, parts.length);
    } else {//from   w w w  .j a  va2  s  .  c  o m
        return new String[0];
    }
}