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.cloudera.sqoop.tool.JobTool.java

private int execJob(SqoopOptions opts) throws IOException {
    JobData data = this.storage.read(jobName);
    if (null == data) {
        LOG.error("No such job: " + jobName);
        return 1;
    }/* www.j a va 2  s .  c  om*/

    SqoopOptions childOpts = data.getSqoopOptions();
    SqoopTool childTool = data.getSqoopTool();

    // Don't overwrite the original SqoopOptions with the
    // arguments; make a child options.

    SqoopOptions clonedOpts = (SqoopOptions) childOpts.clone();
    clonedOpts.setParent(childOpts);

    int dashPos = getDashPosition(extraArguments);
    String[] childArgv;
    if (dashPos >= extraArguments.length) {
        childArgv = new String[0];
    } else {
        childArgv = Arrays.copyOfRange(extraArguments, dashPos + 1, extraArguments.length);
    }

    int confRet = configureChildTool(clonedOpts, childTool, childArgv);
    if (0 != confRet) {
        // Error.
        return confRet;
    }

    return childTool.run(clonedOpts);
}

From source file:com.netflix.imfutility.ttmltostl.stl.StlGsiTest.java

@Test
public void testGsiAllEmpty() throws Exception {
    TimedTextObject tto = StlTestUtil.buildTto();
    byte[][] stl = StlTestUtil.build(tto, StlTestUtil.getMetadataXml());
    byte[] gsi = stl[0];

    assertArrayEquals(new byte[] { 0x38, 0x35, 0x30, // 850
            0x53, 0x54, 0x4c, 0x32, 0x35, 0x2e, 0x30, 0x31, // STL25.01
            0x31, // 1 - teletext
            0x30, 0x30, // 00 - latin
            0x30, 0x39 // 09 - English
    }, Arrays.copyOfRange(gsi, 0, 16));

    assertArrayEquals(new byte[] { 0x50, 0x72, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x6d, 0x65, // 'Programme' as in metadata.xml
            0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
            0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 }, Arrays.copyOfRange(gsi, 16, 48));

    assertArrayEquals(new byte[] { 0x45, 0x70, 0x69, 0x73, 0x6f, 0x64, 0x65, // 'Episode' as in metadata.xml
            0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
            0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 }, Arrays.copyOfRange(gsi, 48, 80));

    byte[] translated = new byte[128];
    Arrays.fill(translated, (byte) 0x20);
    assertArrayEquals(translated, Arrays.copyOfRange(gsi, 80, 208));

    byte[] slr = new byte[16];
    Arrays.fill(slr, (byte) 0x20);
    assertArrayEquals(slr, Arrays.copyOfRange(gsi, 208, 224));

    assertArrayEquals(new byte[] { 0x31, 0x36, 0x30, 0x37, 0x30, 0x38 // creation date as in metadata.xml:
    }, Arrays.copyOfRange(gsi, 224, 230));
    assertArrayEquals(new byte[] { 0x31, 0x36, 0x30, 0x37, 0x30, 0x38 // revision date as in metadata.xml:
    }, Arrays.copyOfRange(gsi, 230, 236));

    assertArrayEquals(new byte[] { 0x30, 0x31 // revision number = 01
    }, Arrays.copyOfRange(gsi, 236, 238));

    assertArrayEquals(new byte[] { 0x30, 0x30, 0x30, 0x30, 0x31 // 1 subtitle zero
    }, Arrays.copyOfRange(gsi, 238, 243));

    assertArrayEquals(new byte[] { 0x30, 0x30, 0x30, 0x30, 0x31 // 1 subtitle zero
    }, Arrays.copyOfRange(gsi, 243, 248));

    assertArrayEquals(new byte[] { 0x30, 0x30, 0x31 // number of subtitle groups - 1
    }, Arrays.copyOfRange(gsi, 248, 251));

    assertArrayEquals(new byte[] { 0x35, 0x38 // number of displayable chars - 58
    }, Arrays.copyOfRange(gsi, 251, 253));

    assertArrayEquals(new byte[] { 0x31, 0x31 // number of displayable rows - 11
    }, Arrays.copyOfRange(gsi, 253, 255));

    assertArrayEquals(new byte[] { 0x31 // tc status - 1
    }, Arrays.copyOfRange(gsi, 255, 256));

    assertArrayEquals(new byte[] { 0x31, 0x30, 0x30, 0x30, 0x30, 0x30, 0x32, 0x30 // start time of program: 10:00:00:20 (as in metadata.xml)
    }, Arrays.copyOfRange(gsi, 256, 264));

    assertArrayEquals(new byte[] { 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30 // start time of subtitles: 00:00:00:00 (zero subtitle)
    }, Arrays.copyOfRange(gsi, 264, 272));

    assertArrayEquals(new byte[] { 0x31 // number of disks - 1
    }, Arrays.copyOfRange(gsi, 272, 273));

    assertArrayEquals(new byte[] { 0x31 // disk seq number - 1
    }, Arrays.copyOfRange(gsi, 273, 274));

    assertArrayEquals(new byte[] { 0x47, 0x42, 0x52 // country - GBR
    }, Arrays.copyOfRange(gsi, 274, 277));

    assertArrayEquals(new byte[] { 0x4f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x74, 0x6f, 0x72, // Publisher: Originator (as in metadata.xml)
            0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
            0x20, 0x20, 0x20, 0x20, 0x20, 0x20 }, Arrays.copyOfRange(gsi, 277, 309));

    assertArrayEquals(new byte[] { 0x44, 0x69, 0x73, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x6f, 0x72, // Editor: Distributor (as in metadata.xml)
            0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
            0x20, 0x20, 0x20, 0x20, 0x20 }, Arrays.copyOfRange(gsi, 309, 341));

    assertArrayEquals(new byte[] { 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x40, // Contact: account@myemail.com (as in metadata.xml)
            0x6d, 0x79, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x20, 0x20, 0x20, 0x20,
            0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 }, Arrays.copyOfRange(gsi, 341, 373));

    byte[] spare = new byte[651];
    Arrays.fill(spare, (byte) 0x20);
    assertArrayEquals(spare, Arrays.copyOfRange(gsi, 373, 1024));

}

From source file:de.micromata.genome.gwiki.plugin.rogmp3_1_0.CsvTable.java

public List<String[]> findMultiEquals(Pair<Integer, String>... keys) {
    if (keys.length > 0) {
        TreeMap<String, List<String[]>> idx = indices.get(keys[0].getFirst());
        if (idx != null) {
            Pair<Integer, String>[] sk = Arrays.copyOfRange(keys, 1, keys.length);
            List<String[]> res = idx.get(keys[0].getValue());
            if (res == null) {
                return Collections.emptyList();
            }//  w w  w .j  av  a2 s  .  c o m
            return findMultiEquals(res, sk);
        }
    }
    return findMultiEquals(table, keys);
}

From source file:model.PayloadSegment.java

/**
 * Copy the encapsulation file to the restoration directory first, to be
 * sure that you won't touch the file in the encapsulation output directory.
 * /*w ww.ja  v  a 2s. c  o  m*/
 * @param encapsulatedData
 * @return altered carrier file...
 */
public static byte[] removeLeastPayloadSegment(byte[] encapsulatedData) {
    try {
        int endIndex = -1;
        for (int index = encapsulatedData.length - 1; index >= 0; index--) {
            if (PayloadSequences.isEndSequence(encapsulatedData, index)) {
                endIndex = index;
            } else if (PayloadSequences.isStartSequence(encapsulatedData, index)) {
                if (endIndex == -1) {
                    return null;
                }
                ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
                byteOut.write(Arrays.copyOfRange(encapsulatedData, 0, index));
                if (endIndex + END_SEQ.length > encapsulatedData.length) {
                    byte[] afterPayload = Arrays.copyOfRange(encapsulatedData, endIndex + END_SEQ.length,
                            encapsulatedData.length - 1);
                    byteOut.write(afterPayload);
                }
                byte[] dataWithRemovedPayload = byteOut.toByteArray();
                byteOut.close();
                return dataWithRemovedPayload;
            }
        }
    } catch (IOException e) {
    }
    return null;
}

From source file:com.opengamma.analytics.financial.model.volatility.smile.fitting.interpolation.SmileInterpolator.java

/**
 * Use this for models that can be expressed as having 3 parameters (e.g. SABR with beta fixed). It picks out 3 consecutive strike-volatility pairs for the 3 parameter fit (so the chi^2 should be
 * zero if the model is capable of fitting the data)
 *
 * @param index Index of first strike/*from  ww  w  .  j ava2s. c  o  m*/
 * @param strikes Array of all strikes
 * @param impliedVols Array of all vols
 * @param errors Array of all errors
 * @return array containing the 3 strikes, vols and errors
 */
protected static double[][] getStrikesVolsAndErrorsForThreePoints(final int index, final double[] strikes,
        final double[] impliedVols, final double[] errors) {
    ArgumentChecker.notNull(strikes, "strikes");
    ArgumentChecker.notNull(impliedVols, "implied vols");
    ArgumentChecker.notNull(errors, "errors");
    double[] tStrikes = new double[3];
    double[] tVols = new double[3];
    double[] tErrors = new double[3];
    tStrikes = Arrays.copyOfRange(strikes, index, index + 3);
    tVols = Arrays.copyOfRange(impliedVols, index, index + 3);
    tErrors = Arrays.copyOfRange(errors, index, index + 3);
    final double[][] res = new double[][] { tStrikes, tVols, tErrors };
    return res;
}

From source file:be.fedict.eid.idp.protocol.openid.StatelessServerAssociationStore.java

private Association loadFromHandle(String handle)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
        BadPaddingException, IOException, InvalidAlgorithmParameterException {
    byte[] encodedHandle = Base64.decodeBase64(handle);
    if (null != this.macSecretKeySpec) {
        byte[] signature = new byte[32];
        System.arraycopy(encodedHandle, 0, signature, 0, 32);
        byte[] toBeSigned = new byte[encodedHandle.length - 32];
        System.arraycopy(encodedHandle, 32, toBeSigned, 0, encodedHandle.length - 32);
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(this.macSecretKeySpec);
        byte[] actualSignature = mac.doFinal(toBeSigned);
        if (false == Arrays.equals(actualSignature, signature)) {
            return null;
        }//w  ww .java 2  s  .c om
        encodedHandle = toBeSigned;
    }
    byte[] iv = new byte[16];
    System.arraycopy(encodedHandle, 0, iv, 0, iv.length);
    byte[] encodedData = Arrays.copyOfRange(encodedHandle, 16, encodedHandle.length);
    Cipher cipher = Cipher.getInstance(CIPHER_ALGO);
    IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
    cipher.init(Cipher.DECRYPT_MODE, this.secretKeySpec, ivParameterSpec);
    byte[] associationBytes = cipher.doFinal(encodedData);
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(associationBytes);
    int typeByte = byteArrayInputStream.read();
    if (typeByte == 1) {
        byte[] macKeyBytes = new byte[160 / 8];
        byteArrayInputStream.read(macKeyBytes);
        DataInputStream dataInputStream = new DataInputStream(byteArrayInputStream);
        long exp = dataInputStream.readLong();
        Date expDate = new Date(exp);
        return Association.createHmacSha1(handle, macKeyBytes, expDate);
    } else if (typeByte == 2) {
        byte[] macKeyBytes = new byte[256 / 8];
        byteArrayInputStream.read(macKeyBytes);
        DataInputStream dataInputStream = new DataInputStream(byteArrayInputStream);
        long exp = dataInputStream.readLong();
        Date expDate = new Date(exp);
        return Association.createHmacSha256(handle, macKeyBytes, expDate);
    } else {
        return null;
    }
}

From source file:com.bolatu.gezkoncsvlogger.GyroOrientation.GyroscopeOrientation.java

/**
 * Calculates a rotation vector from the gyroscope angular speed values.
 * //from w  ww .jav a2s  . c  o m
 * @param gyroValues
 * @param deltaRotationVector
 * @param timeFactor
 * @see http://developer.android
 *      .com/reference/android/hardware/SensorEvent.html#values
 */
private void getRotationVectorFromGyro() {
    // Calculate the angular speed of the sample
    float magnitude = (float) Math
            .sqrt(Math.pow(vGyroscope[0], 2) + Math.pow(vGyroscope[1], 2) + Math.pow(vGyroscope[2], 2));

    // Normalize the rotation vector if it's big enough to get the axis
    if (magnitude > EPSILON) {
        vGyroscope[0] /= magnitude;
        vGyroscope[1] /= magnitude;
        vGyroscope[2] /= magnitude;
    }

    // Integrate around this axis with the angular speed by the timestep
    // in order to get a delta rotation from this sample over the timestep
    // We will convert this axis-angle representation of the delta rotation
    // into a quaternion before turning it into the rotation matrix.
    float thetaOverTwo = magnitude * dT / 2.0f;
    float sinThetaOverTwo = (float) Math.sin(thetaOverTwo);
    float cosThetaOverTwo = (float) Math.cos(thetaOverTwo);

    deltaVGyroscope[0] = sinThetaOverTwo * vGyroscope[0];
    deltaVGyroscope[1] = sinThetaOverTwo * vGyroscope[1];
    deltaVGyroscope[2] = sinThetaOverTwo * vGyroscope[2];
    deltaVGyroscope[3] = cosThetaOverTwo;

    // Create a new quaternion object base on the latest rotation
    // measurements...
    qGyroscopeDelta = new Quaternion(deltaVGyroscope[3], Arrays.copyOfRange(deltaVGyroscope, 0, 3));

    // Since it is a unit quaternion, we can just multiply the old rotation
    // by the new rotation delta to integrate the rotation.
    qGyroscope = qGyroscope.multiply(qGyroscopeDelta);
}

From source file:edu.msu.cme.rdp.readseq.readers.core.SFFCore.java

@Override
public QSequence readNextSeq() throws IOException {
    ReadBlock readBlock = readReadBlock();
    if (readBlock == null) {
        return null;
    }/*from  w  ww  . j  ava2 s . c  om*/

    int clipLeft = Math.max(readBlock.clipAdapterLeft, readBlock.clipQualLeft);
    int clipRight = readBlock.numBases;

    if (readBlock.clipAdapterRight > 0 && readBlock.clipAdapterRight < clipRight) {
        clipRight = readBlock.clipAdapterRight;
    }

    if (readBlock.clipQualRight != 0 && readBlock.clipQualRight < clipRight) {
        clipRight = readBlock.clipQualRight;
    }
    if (clipLeft > clipRight)
        return readNextSeq();
    String seq = readBlock.seq.substring(clipLeft - 1, clipRight);

    return new QSequence(readBlock.name, "", seq, Arrays.copyOfRange(readBlock.qual, clipLeft - 1, clipRight));
}

From source file:dylemator.UserList.java

private void filenameComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filenameComboActionPerformed
    Object item = this.filenameCombo.getSelectedItem();
    exportData = new ArrayList<String[]>();
    File file = new File(item.toString());
    if (file.exists()) {
        String datePattern = "(\\d+-\\d+-\\d+)";
        Pattern r = Pattern.compile(datePattern);
        Matcher m = r.matcher(file.getName());
        String fileDate;/*from  w  w w . j  a  va 2s.  c  om*/
        if (m.find()) {
            fileDate = m.group(0);
        } else
            fileDate = new Date(file.lastModified()).toString();

        DefaultTableModel model = (DefaultTableModel) this.personsTable.getModel();
        model.setRowCount(0);
        model.setColumnCount(0);
        try {
            InputStreamReader input = new FileReader(file);
            BufferedReader bufferReader;
            bufferReader = new BufferedReader(input);
            // headers
            String headerLine = bufferReader.readLine();
            String[] headers = headerLine.split(";");
            // kod osoby i data badania
            String[] userHeaders = new String[] { headers[0], headers[1] };
            String[] valueHeaders = Arrays.copyOfRange(headers, 4, headers.length);
            Object[] allHeaders = ArrayUtils.addAll(userHeaders, valueHeaders);

            for (int header = 0; header < allHeaders.length; header++) {
                model.addColumn(allHeaders[header]);

            }
            exportData.add((String[]) allHeaders);

            String line;
            while ((line = bufferReader.readLine()) != null) {
                String[] fields = line.split(";");
                String[] userFields = new String[] { fields[0], fileDate };
                String[] valueFields = Arrays.copyOfRange(fields, 4, fields.length);
                Object[] allValues = ArrayUtils.addAll(userFields, valueFields);
                model.addRow(allValues);
                exportData.add((String[]) allValues);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(FindDialog.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FindDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.joyent.manta.client.crypto.AesCtrCipherDetailsTest.java

protected void canRandomlyReadPlaintextPositionFromCiphertext(final SecretKey secretKey,
        final SupportedCipherDetails cipherDetails) throws IOException, GeneralSecurityException {
    String text = "A SERGEANT OF THE LAW, wary and wise, " + "That often had y-been at the Parvis, <26> "
            + "There was also, full rich of excellence. " + "Discreet he was, and of great reverence: "
            + "He seemed such, his wordes were so wise, " + "Justice he was full often in assize, "
            + "By patent, and by plein* commission; " + "For his science, and for his high renown, "
            + "Of fees and robes had he many one. " + "So great a purchaser was nowhere none. "
            + "All was fee simple to him, in effect " + "His purchasing might not be in suspect* "
            + "Nowhere so busy a man as he there was " + "And yet he seemed busier than he was "
            + "In termes had he case' and doomes* all " + "That from the time of King Will. were fall. "
            + "Thereto he could indite, and make a thing " + "There coulde no wight *pinch at* his writing. "
            + "And every statute coud* he plain by rote " + "He rode but homely in a medley* coat, "
            + "Girt with a seint* of silk, with barres small; " + "Of his array tell I no longer tale.";

    byte[] plaintext = text.getBytes(StandardCharsets.US_ASCII);

    ContentType contentType = ContentType.APPLICATION_OCTET_STREAM;
    ExposedByteArrayEntity entity = new ExposedByteArrayEntity(plaintext, contentType);
    EncryptingEntity encryptingEntity = new EncryptingEntity(secretKey, cipherDetails, entity);

    final byte[] ciphertext;
    final byte[] iv = encryptingEntity.getCipher().getIV();
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        encryptingEntity.writeTo(out);//w ww  .  j  ava2s .co  m
        ciphertext = Arrays.copyOf(out.toByteArray(),
                out.toByteArray().length - cipherDetails.getAuthenticationTagOrHmacLengthInBytes());
    }

    for (long startPlaintextRange = 0; startPlaintextRange < plaintext.length - 1; startPlaintextRange++) {
        for (long endPlaintextRange = startPlaintextRange; endPlaintextRange < plaintext.length; endPlaintextRange++) {

            byte[] adjustedPlaintext = Arrays.copyOfRange(plaintext, (int) startPlaintextRange,
                    (int) endPlaintextRange + 1);

            ByteRangeConversion ranges = cipherDetails.translateByteRange(startPlaintextRange,
                    endPlaintextRange);
            long startCipherTextRange = ranges.getCiphertextStartPositionInclusive();
            long endCipherTextRange = ranges.getCiphertextEndPositionInclusive();
            long adjustedPlaintextLength = ranges.getLengthOfPlaintextIncludingSkipBytes();

            Cipher decryptor = cipherDetails.getCipher();

            decryptor.init(Cipher.DECRYPT_MODE, secretKey, cipherDetails.getEncryptionParameterSpec(iv));
            long adjustedPlaintextRange = cipherDetails.updateCipherToPosition(decryptor, startPlaintextRange);

            byte[] adjustedCipherText = Arrays.copyOfRange(ciphertext, (int) startCipherTextRange,
                    (int) Math.min(ciphertext.length, endCipherTextRange + 1));
            byte[] out = decryptor.doFinal(adjustedCipherText);
            byte[] decrypted = Arrays.copyOfRange(out, (int) adjustedPlaintextRange,
                    (int) Math.min(out.length, adjustedPlaintextLength));

            String decryptedText = new String(decrypted, StandardCharsets.UTF_8);
            String adjustedText = new String(adjustedPlaintext, StandardCharsets.UTF_8);

            Assert.assertEquals(adjustedText, decryptedText,
                    "Random read output from ciphertext doesn't match expectation " + "[cipher="
                            + cipherDetails.getCipherId() + "]");
        }
    }
}