Java Code Examples for java.util.Arrays.copyOfRange()

The following are Jave code examples for showing how to use copyOfRange() of the java.util.Arrays class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: java-coap   File: TLVDeserializer.java   View Source Code Vote up 6 votes
private static List<LWM2MObjectInstance> deserializeObjectInstances(byte[] tlv, int offset, List<LWM2MObjectInstance> list) {
    TypeIdLength til = TypeIdLength.createTypeIdLength(tlv, offset).deserialize();
    offset = til.offset;

    if (til.type == TYPE_OBJECT_INSTANCE) {
        List<LWM2MResource> instances = new ArrayList<>();
        byte[] nested = Arrays.copyOfRange(tlv, offset, offset + til.length);
        deserializeResources(nested, 0, instances);
        list.add (new LWM2MObjectInstance(LWM2MID.from(til.id), instances));
    } else {
        throw new IllegalArgumentException("Object instance is expected at index:" + offset);
    }

    offset += til.length;

    return offset < tlv.length ? deserializeObjectInstances(tlv, offset, list) : list;
}
 
Example 2
Project: Daedalus   File: UdpProvider.java   View Source Code Vote up 6 votes
void readPacketFromDevice(FileInputStream inputStream, byte[] packet) throws DaedalusVpnService.VpnNetworkException, SocketException {
    // Read the outgoing packet from the input stream.
    int length;

    try {
        length = inputStream.read(packet);
    } catch (IOException e) {
        throw new DaedalusVpnService.VpnNetworkException("Cannot read from device", e);
    }


    if (length == 0) {
        Log.w(TAG, "Got empty packet!");
        return;
    }

    final byte[] readPacket = Arrays.copyOfRange(packet, 0, length);

    handleDnsRequest(readPacket);
}
 
Example 3
Project: BassNES   File: MMC1.java   View Source Code Vote up 6 votes
@Override
protected void setCHR(byte[] chr){
	if(chr.length>0){
	CHRbanks = new byte[chr.length/0x1000][0x1000];
	for(int i=0;i*0x1000<chr.length;i++)
		CHRbanks[i]= Arrays.copyOfRange(chr, i*0x1000, (i*0x1000)+0x1000);
	CHR_ROM[0]=CHRbanks[0];
	CHR_ROM[1]=CHRbanks[1];
	}
	else{
		CHR_ROM[0]= new byte[0x1000];
		CHR_ROM[1]= new byte[0x1000];
		CHR_ram = true;
	}
	smallchrrom = CHR_ram || CHRbanks.length==2;
	
}
 
Example 4
Project: BassNES   File: AxROM.java   View Source Code Vote up 5 votes
@Override
protected void setCHR(byte[] chr){
	if(chr.length>0){
		CHRbanks = new byte[chr.length/0x1000][0x1000];
	for(int i=0;i*0x1000<chr.length;i++)
		CHRbanks[i]= Arrays.copyOfRange(chr, i*0x1000, (i*0x1000)+0x1000);
	CHR_ROM[0]=CHRbanks[0];
	CHR_ROM[1]=CHRbanks[1];
	}
	else{
		CHR_ROM[0]= new byte[0x1000];
		CHR_ROM[1]= new byte[0x1000];
		CHR_ram = true;
	}
}
 
Example 5
Project: encdroidMC   File: EncFSVolume.java   View Source Code Vote up 5 votes
private byte[] copyIVdata(byte[] keyData, int keyLength)
		throws EncFSInvalidConfigException {
	int ivLength = keyData.length - keyLength;
	if (ivLength != IV_LENGTH_IN_BYTES) {
		throw new EncFSInvalidConfigException("Non-standard IV length");
	}
	return Arrays.copyOfRange(keyData, keyLength, keyLength + ivLength);
}
 
Example 6
Project: Exoplayer2Radio   File: Id3Decoder.java   View Source Code Vote up 5 votes
private static ApicFrame decodeApicFrame(ParsableByteArray id3Data, int frameSize,
    int majorVersion) throws UnsupportedEncodingException {
  int encoding = id3Data.readUnsignedByte();
  String charset = getCharsetName(encoding);

  byte[] data = new byte[frameSize - 1];
  id3Data.readBytes(data, 0, frameSize - 1);

  String mimeType;
  int mimeTypeEndIndex;
  if (majorVersion == 2) {
    mimeTypeEndIndex = 2;
    mimeType = "image/" + Util.toLowerInvariant(new String(data, 0, 3, "ISO-8859-1"));
    if (mimeType.equals("image/jpg")) {
      mimeType = "image/jpeg";
    }
  } else {
    mimeTypeEndIndex = indexOfZeroByte(data, 0);
    mimeType = Util.toLowerInvariant(new String(data, 0, mimeTypeEndIndex, "ISO-8859-1"));
    if (mimeType.indexOf('/') == -1) {
      mimeType = "image/" + mimeType;
    }
  }

  int pictureType = data[mimeTypeEndIndex + 1] & 0xFF;

  int descriptionStartIndex = mimeTypeEndIndex + 2;
  int descriptionEndIndex = indexOfEos(data, descriptionStartIndex, encoding);
  String description = new String(data, descriptionStartIndex,
      descriptionEndIndex - descriptionStartIndex, charset);

  int pictureDataStartIndex = descriptionEndIndex + delimiterLength(encoding);
  byte[] pictureData = Arrays.copyOfRange(data, pictureDataStartIndex, data.length);

  return new ApicFrame(mimeType, description, pictureType, pictureData);
}
 
Example 7
Project: marathonv5   File: LevelData.java   View Source Code Vote up 5 votes
public static String[] getLevelData(int level) {
    initLevelsOffsets();
    if (level < 1 || level > getLevelsCount()) {
        return null;
    } else {
        return Arrays.copyOfRange(LEVELS_DATA, levelsOffsets.get(level - 1) + 1, levelsOffsets.get(level));
    }
}
 
Example 8
Project: BassNES   File: VRC1.java   View Source Code Vote up 5 votes
@Override
protected void setPRG(byte[] prg){
	PRG_ROM = new byte[4][0x2000];
	PRGbanks = new byte[prg.length/0x2000][0x2000];
	for(int i=0;i*0x2000<prg.length;i++){
		PRGbanks[i]=Arrays.copyOfRange(prg, i*0x2000, (i*0x2000)+0x2000);
	}
	PRG_ROM[0]=PRGbanks[0];
	PRG_ROM[1]=PRGbanks[1];
	PRG_ROM[2]=PRGbanks[PRGbanks.length-2];
	PRG_ROM[3]=PRGbanks[PRGbanks.length-1];
}
 
Example 9
Project: JWaves   File: Address.java   View Source Code Vote up 5 votes
/**
 * Generate address from private key.
 *
 * @param keys  private and public keys.
 * @param seed  seed.
 * @param chain chain.
 * @return address.
 */
private static Address generate(KeyPair keys, @Nullable final String seed, @NotNull final String chain) {
    final byte[] privKey = keys.getPrivate().getEncoded();
    final byte[] pubKey = keys.getPublic().getEncoded();

    final byte[] hashPubKey = Arrays.copyOfRange(Crypto.hashChain(pubKey), 0, 20);
    final byte[] unhashedAddress = ByteUtils.concat(new byte[]{(char) 1}, chain.getBytes(), hashPubKey);
    final byte[] addressHash = Arrays.copyOfRange(Crypto.hashChain(unhashedAddress), 0, 4);

    final String address = Base58.encode(ByteUtils.concat(unhashedAddress, addressHash));
    final String publicKey = Base58.encode(pubKey);
    final String privateKey = Base58.encode(privKey);
    return createRaw(address, publicKey, privateKey, seed);
}
 
Example 10
Project: bitbreeds-webrtc   File: SignalUtil.java   View Source Code Vote up 5 votes
public static byte[] copyRange(byte[] bytes,ByteRange range) {
    if(range.a < 0) {
        throw new ArrayIndexOutOfBoundsException("Range.a must be 0 or higher, was: " + range.a);
    }
    if(range.b > bytes.length) {
        throw new ArrayIndexOutOfBoundsException("Range.b must be smaller then array length "+bytes.length+", was: " + range.b);
    }
    return Arrays.copyOfRange(bytes,range.a,range.b);
}
 
Example 11
Project: jdk8u-jdk   File: NTLM.java   View Source Code Vote up 5 votes
byte[] readBytes(int offset, int len) throws NTLMException {
    try {
        return Arrays.copyOfRange(internal, offset, offset + len);
    } catch (ArrayIndexOutOfBoundsException ex) {
        throw new NTLMException(NTLMException.PACKET_READ_ERROR,
                "Input message incorrect size");
    }
}
 
Example 12
Project: POPBL_V   File: Frame.java   View Source Code Vote up 5 votes
/** Constructor: Receive data frame */
public Frame(byte[] frame) {
	this.preamble = Arrays.copyOfRange(frame, 0, 1);
	this.type = frame[2] >> 4;
	this.id = 0x07 & frame[2];
	this.typeId = frame[2];
	this.dataLength = frame[3];
	this.data = Arrays.copyOfRange(frame, 4, dataLength);
	this.checksum = frame[36];

	this.frame = frame;
}
 
Example 13
Project: mDL-ILP   File: BasicCard.java   View Source Code Vote up 5 votes
protected byte[] processSelectFile(final byte[] command) {
    byte cla = command[0];
    byte ins = command[1];
    byte p1 = command[2];
    byte p2 = command[3];
    byte length = command[4];
    byte[] aid = Arrays.copyOfRange(command, 5, 5+length);

    if (Arrays.equals(aid, getAID())) {
        return SUCCESS;
    } else {
        return FAIL_FILE_NOT_FOUND;
    }
}
 
Example 14
Project: febit   File: IpSeeker.java   View Source Code Vote up 4 votes
public static IpSeeker create(final byte[] buffer) {

        //Head
        final ByteBuffer headBuf = ByteBuffer.wrap(buffer, 0, 4 * 258);
        final int headPos = headBuf.getInt();
        // we have 256 segments, and last is the end position
        final int[] segmentPos = new int[257];
        for (int i = 0; i < 257; i++) {
            segmentPos[i] = headBuf.getInt();
        }

        //Dict
        final String dictRaw = new String(Arrays.copyOfRange(buffer, headPos, segmentPos[0]), UTF_8);
        final String[] dict = StringUtil.splitc(dictRaw, '\001');

        dict[0] = null; // "None" => null

        //Segments
        final int[][] segments = new int[256][];
        final long[][] segmentIndexers = new long[256][];

        for (int i = 0; i < 256; i++) {
            int start = segmentPos[i];
            int end = segmentPos[i + 1];

            int len = (end - start) / 12; //(1 int + 1 long = 12 byte)

            int[] segment = new int[len];
            long[] segmentIndexer = new long[len];

            ByteBuffer buf = ByteBuffer.wrap(buffer, start, end - start);

            for (int j = 0; j < len; j++) {
                segment[j] = buf.getInt();
                segmentIndexer[j] = buf.getLong();
            }
            segments[i] = segment;
            segmentIndexers[i] = segmentIndexer;
        }

        //XXX 校验
        return new IpSeeker(dict, segments, segmentIndexers);
    }
 
Example 15
Project: kuber   File: Encrypt.java   View Source Code Vote up 4 votes
public int run(String[] args) throws Exception {
	if (args.length < 2) {
        System.err.println("HdfsWriter [local input path] [hdfs output path]");
        return 1;
    }
    
	// Get the filename out of the file path
 String filename = args[0].substring(args[0].lastIndexOf('/') + 1,args[0].length());

 String dest = args[1];
 // Create the destination path including the filename.
 if (dest.charAt(dest.length() - 1) != '/') {
   dest = dest + "/" + filename;
 } else {
   dest = dest + filename;
 }
 
    String localInputPath = args[0];
    
    File inputPath = new File(localInputPath);
    Path outputPath = new Path(dest);
    
    if(!inputPath.exists()){
    	System.err.println("Input file does not exist!");
        return 1;
    }
    
    Configuration conf = getConf();
    System.out.println("configured filesystem = " + conf.get(FS_PARAM_NAME));
    
    FileSystem fs = FileSystem.get(conf);
    
    if (fs.exists(outputPath)) {
        System.err.println("Output path exists!");
        return 1;
    }
    
    InputStream is = new BufferedInputStream(new FileInputStream(localInputPath));
    OutputStream os = fs.create(outputPath);
    
    System.out.println("\nKuber encryption started!\n");
    
    byte[] b = new byte[1024*100];
    
 int numBytes = 0;
 
 while ((numBytes = is.read(b)) > 0) {
   byte[] block = Arrays.copyOfRange(b, 0, numBytes);
   byte[] encrypted = encrypt(block);
   os.write(encrypted, 0, numBytes);
 }
 
 is.close();
 os.close();
 
    return 0;
}
 
Example 16
Project: JWT4B   File: ITokenPosition.java   View Source Code Vote up 4 votes
protected byte[] getBody() {
	return Arrays.copyOfRange(message, getBodyOffset(), message.length);
}
 
Example 17
Project: guava-mock   File: ImmutableIntArray.java   View Source Code Vote up 4 votes
/** Returns a new, mutable copy of this array's values, as a primitive {@code int[]}. */
public int[] toArray() {
  return Arrays.copyOfRange(array, start, end);
}
 
Example 18
Project: BaseClient   File: ConnectedParser.java   View Source Code Vote up 4 votes
public MatchBlock[] parseMatchBlock(String p_parseMatchBlock_1_)
{
    if (p_parseMatchBlock_1_ == null)
    {
        return null;
    }
    else
    {
        p_parseMatchBlock_1_ = p_parseMatchBlock_1_.trim();

        if (p_parseMatchBlock_1_.length() <= 0)
        {
            return null;
        }
        else
        {
            String[] astring = Config.tokenize(p_parseMatchBlock_1_, ":");
            String s = "minecraft";
            int i = 0;

            if (astring.length > 1 && this.isFullBlockName(astring))
            {
                s = astring[0];
                i = 1;
            }
            else
            {
                s = "minecraft";
                i = 0;
            }

            String s1 = astring[i];
            String[] astring1 = (String[])Arrays.copyOfRange(astring, i + 1, astring.length);
            Block[] ablock = this.parseBlockPart(s, s1);

            if (ablock == null)
            {
                return null;
            }
            else
            {
                MatchBlock[] amatchblock = new MatchBlock[ablock.length];

                for (int j = 0; j < ablock.length; ++j)
                {
                    Block block = ablock[j];
                    int k = Block.getIdFromBlock(block);
                    int[] aint = null;

                    if (astring1.length > 0)
                    {
                        aint = this.parseBlockMetadatas(block, astring1);

                        if (aint == null)
                        {
                            return null;
                        }
                    }

                    MatchBlock matchblock = new MatchBlock(k, aint);
                    amatchblock[j] = matchblock;
                }

                return amatchblock;
            }
        }
    }
}
 
Example 19
Project: mDL-ILP   File: CardIOUtils.java   View Source Code Vote up 4 votes
public static byte[] getSW(byte[] resp) {
    return Arrays.copyOfRange(resp, resp.length-2, resp.length);
}
 
Example 20
Project: SparkSeq   File: ConsensusAlleleCounter.java   View Source Code Vote up 4 votes
private List<Allele> consensusCountsToAlleles(final ReferenceContext ref,
                                              final Map<String, Integer> consensusIndelStrings) {
    final GenomeLoc loc = ref.getLocus();
    final Collection<VariantContext> vcs = new ArrayList<VariantContext>();
    int maxAlleleCnt = 0;
    Allele refAllele, altAllele;

    for (final Map.Entry<String, Integer> elt : consensusIndelStrings.entrySet()) {
        final String s = elt.getKey();
        final int curCnt = elt.getValue();
        int stop = 0;

        // if observed count if above minimum threshold, we will genotype this allele
        if (curCnt < minIndelCountForGenotyping)
            continue;

        if (s.startsWith("D")) {
            // get deletion length
            final int dLen = Integer.valueOf(s.substring(1));
            // get ref bases of accurate deletion
            final int startIdxInReference = 1 + loc.getStart() - ref.getWindow().getStart();
            stop = loc.getStart() + dLen;
            final byte[] refBases = Arrays.copyOfRange(ref.getBases(), startIdxInReference - 1, startIdxInReference + dLen);   // add reference padding

            if (Allele.acceptableAlleleBases(refBases, false)) {
                refAllele = Allele.create(refBases, true);
                altAllele = Allele.create(ref.getBase(), false);
            }
            else continue; // don't go on with this allele if refBases are non-standard
        } else {
            // insertion case
            final String insertionBases = (char)ref.getBase() + s;  // add reference padding
            if (Allele.acceptableAlleleBases(insertionBases, false)) { // don't allow N's in insertions
                refAllele = Allele.create(ref.getBase(), true);
                altAllele = Allele.create(insertionBases, false);
                stop = loc.getStart();
            }
            else continue; // go on to next allele if consensus insertion has any non-standard base.
        }


        final VariantContextBuilder builder = new VariantContextBuilder().source("");
        builder.loc(loc.getContig(), loc.getStart(), stop);
        builder.alleles(Arrays.asList(refAllele, altAllele));
        builder.noGenotypes();
        if (doMultiAllelicCalls) {
            vcs.add(builder.make());
            if (vcs.size() >= GenotypeLikelihoods.MAX_ALT_ALLELES_THAT_CAN_BE_GENOTYPED)
                break;
        } else if (curCnt > maxAlleleCnt) {
            maxAlleleCnt = curCnt;
            vcs.clear();
            vcs.add(builder.make());
        }
    }

    if (vcs.isEmpty())
        return Collections.emptyList(); // nothing else to do, no alleles passed minimum count criterion

    final VariantContext mergedVC = GATKVariantContextUtils.simpleMerge(vcs, null, GATKVariantContextUtils.FilteredRecordMergeType.KEEP_IF_ANY_UNFILTERED, GATKVariantContextUtils.GenotypeMergeType.UNSORTED, false, false, null, false, false);
    return mergedVC.getAlleles();
}