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.lightboxtechnologies.io.IOUtilsTest.java

@Test
public void testReadShort() throws IOException {
    final byte[] expected = new byte[50];
    Arrays.fill(expected, (byte) 1);

    final InputStream in = new ByteArrayInputStream(expected);
    final byte[] actual = new byte[100];
    final int count = IOUtils.read(in, actual);

    assertEquals(50, count);/*from   w ww.  j ava2  s.  com*/
    assertArrayEquals(expected, Arrays.copyOfRange(actual, 0, count));
    assertArrayEquals(new byte[50], Arrays.copyOfRange(actual, count, 100));
}

From source file:io.github.dsheirer.record.wave.WaveWriter.java

/**
 * Writes the buffer contents to the file.  Assumes that the buffer is full
 * and the first byte of data is at position 0.
 *//* w w w.ja v  a 2  s .  c  o m*/
public void writeData(ByteBuffer buffer) throws IOException {
    buffer.position(0);

    openDataChunk();

    /* Write the full buffer if there is room, respecting the max file size */
    if (mFileChannel.size() + buffer.capacity() < mMaxSize) {
        while (buffer.hasRemaining()) {
            mDataChunkSize += mFileChannel.write(buffer);
        }

        updateTotalSize();
        updateDataChunkSize();
    } else {
        /* Split the buffer to finish filling the current file and then put
         * the leftover into a new file */
        int remaining = (int) (mMaxSize - mFileChannel.size());

        /* Ensure we write full frames to fill up the remaining size */
        remaining -= (int) (remaining % mAudioFormat.getFrameSize());

        byte[] bytes = buffer.array();

        ByteBuffer current = ByteBuffer.wrap(Arrays.copyOf(bytes, remaining));

        ByteBuffer next = ByteBuffer.wrap(Arrays.copyOfRange(bytes, remaining, bytes.length));

        while (current.hasRemaining()) {
            mDataChunkSize += mFileChannel.write(current);
        }

        updateTotalSize();
        updateDataChunkSize();

        rollover();

        openDataChunk();

        while (next.hasRemaining()) {
            mDataChunkSize += mFileChannel.write(next);
        }

        updateTotalSize();
        updateDataChunkSize();
    }
}

From source file:com.cloudera.sqoop.tool.JobTool.java

private int createJob(SqoopOptions options) throws IOException {
    // In our extraArguments array, we should have a '--' followed by
    // a tool name, and any tool-specific arguments.
    // Create an instance of the named tool and then configure it to
    // get a SqoopOptions out which we will serialize into a job.
    int dashPos = getDashPosition(extraArguments);
    int toolArgPos = dashPos + 1;
    if (null == extraArguments || toolArgPos < 0 || toolArgPos >= extraArguments.length) {
        LOG.error("No tool specified; cannot create a job.");
        LOG.error("Use: sqoop job --create <job-name> " + "-- <tool-name> [tool-args]");
        return 1;
    }//from ww w  .ja va2s.  co m

    String jobToolName = extraArguments[toolArgPos];
    SqoopTool jobTool = SqoopTool.getTool(jobToolName);
    if (null == jobTool) {
        LOG.error("No such tool available: " + jobToolName);
        return 1;
    }

    // Create a SqoopOptions and Configuration based on the current one,
    // but deep-copied. This will be populated within the job.
    SqoopOptions jobOptions = new SqoopOptions();
    jobOptions.setConf(new Configuration(options.getConf()));

    // Get the arguments to feed to the child tool.
    String[] childArgs = Arrays.copyOfRange(extraArguments, toolArgPos + 1, extraArguments.length);

    int confRet = configureChildTool(jobOptions, jobTool, childArgs);
    if (0 != confRet) {
        // Error.
        return confRet;
    }

    // Now that the tool is fully configured, materialize the job.
    JobData jobData = new JobData(jobOptions, jobTool);
    this.storage.create(jobName, jobData);
    return 0; // Success.
}

From source file:com.google.sample.beaconservice.MainActivityFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    sharedPreferences = getActivity().getSharedPreferences(Constants.PREFS_NAME, 0);
    arrayList = new ArrayList<>();
    arrayAdapter = new BeaconArrayAdapter(getActivity(), R.layout.beacon_list_item, arrayList);

    scanCallback = new ScanCallback() {
        @Override/*  www .  ja v a  2s . co m*/
        public void onScanResult(int callbackType, ScanResult result) {
            ScanRecord scanRecord = result.getScanRecord();
            if (scanRecord == null) {
                Log.w(TAG, "Null ScanRecord for device " + result.getDevice().getAddress());
                return;
            }

            byte[] serviceData = scanRecord.getServiceData(EDDYSTONE_SERVICE_UUID);
            if (serviceData == null) {
                return;
            }

            // We're only interested in the UID frame time since we need the beacon ID to register.
            if (serviceData[0] != EDDYSTONE_UID_FRAME_TYPE) {
                return;
            }

            // Extract the beacon ID from the service data. Offset 0 is the frame type, 1 is the
            // Tx power, and the next 16 are the ID.
            // See https://github.com/google/eddystone/eddystone-uid for more information.
            byte[] id = Arrays.copyOfRange(serviceData, 2, 18);
            if (arrayListContainsId(arrayList, id)) {
                return;
            }

            // Draw it immediately and kick off a async request to fetch the registration status,
            // redrawing when the server returns.
            Log.i(TAG, "id " + Utils.toHexString(id) + ", rssi " + result.getRssi());

            Beacon beacon = new Beacon("EDDYSTONE", id, Beacon.STATUS_UNSPECIFIED, result.getRssi());
            insertIntoListAndFetchStatus(beacon);
        }

        @Override
        public void onScanFailed(int errorCode) {
            Log.e(TAG, "onScanFailed errorCode " + errorCode);
        }
    };

    createScanner();
}

From source file:alluxio.shell.AlluxioShell.java

/**
 * Method which determines how to handle the user's request, will display usage help to the user
 * if command format is incorrect.// www  .java  2s.  co m
 *
 * @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
 */
public int run(String... argv) {
    if (argv.length == 0) {
        printUsage();
        return -1;
    }

    // Sanity check on the number of arguments
    String cmd = argv[0];
    ShellCommand command = mCommands.get(cmd);

    if (command == null) { // Unknown command (we didn't find the cmd in our dict)
        String[] replacementCmd = getReplacementCmd(cmd);
        if (replacementCmd == null) {
            System.out.println(cmd + " is an unknown command.\n");
            printUsage();
            return -1;
        }
        // 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);
        LOG.warn(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 = command.parseAndValidateArgs(args);
    if (cmdline == null) {
        printUsage();
        return -1;
    }

    // Handle the command
    try {
        command.run(cmdline);
        return 0;
    } catch (IOException e) {
        System.out.println(e.getMessage());
        LOG.error("Error running " + StringUtils.join(argv, " "), e);
        return -1;
    }
}

From source file:com.tc.utils.DxlUtils.java

public static byte[] findSSJS(Database db, String resourceName) {
    Document docLib = null;//w w w. j  a  va  2 s.  c  o m
    byte[] byteMe = null;
    NoteCollection nc = null;
    try {

        if (db == null || resourceName == null) {
            return null;
        }

        nc = db.createNoteCollection(false);
        nc.setSelectDocuments(false);
        nc.selectAllCodeElements(true);
        nc.buildCollection();

        docLib = null;

        //now lets find the lib that matches the name
        String noteId = nc.getFirstNoteID();
        while (!"".equals(noteId)) {
            docLib = db.getDocumentByID(noteId);
            String title = docLib.getItemValueString("$Title");
            if (docLib != null && resourceName.equals(title)) {
                byteMe = extractData(docLib, SSJS_LIB_START, SSJS_LIB_END);

                //now lets drop the first 50 bytes, and the last byte (seems to have an illegal character in there).
                byteMe = Arrays.copyOfRange(byteMe, 50, byteMe.length - 1);

                break;
            }

            noteId = nc.getNextNoteID(noteId);
            if (docLib != null) {
                docLib.recycle();
            }
        }

    } catch (NotesException e) {
        logger.log(Level.SEVERE, null, e);
    } finally {
        try {
            nc.recycle();
        } catch (NotesException e) {
            logger.log(Level.SEVERE, null, e);
        }
    }
    return byteMe;
}

From source file:io.warp10.continuum.gts.GTSDecoder.java

/**
 * @param baseTimestamp Base timestamp for computing deltas.
 * @param key AES Wrapping key to use for unwrapping encrypted data
 * @param bb ByteBuffer containing the encoded GTS. Only remaining data will be read.
 *                      Encrypted data that cannot be decrypted will be silently ignored.
 *                      If the buffer contains encrypted data which could be decrypted,
 *                      reallocation will take place therefore 'bb' and the internal buffer
 *                      used by this instance of GTSDecoder will
 *                      differ after the first encrypted chunk is encountered.
 *///  w ww. j  a  va2s .c o m
public GTSDecoder(long baseTimestamp, byte[] key, ByteBuffer bb) {
    this.baseTimestamp = baseTimestamp;
    this.buffer = bb;
    if (null != key) {
        this.wrappingKey = Arrays.copyOfRange(key, 0, key.length);
    } else {
        this.wrappingKey = null;
    }
    this.position = bb.position();
}

From source file:com.aperigeek.dropvault.web.dao.MongoFileService.java

public Resource mkcol(String username, String resource)
        throws ResourceAlreadyExistsException, ResourceNotFoundException {
    String[] path = resource.split("/");
    Resource parent = getResourceAt(getRootFolder(username), Arrays.copyOfRange(path, 0, path.length - 2));

    if (getChild(parent, path[path.length - 1]) != null) {
        throw new ResourceAlreadyExistsException();
    }//  w w  w  .  ja v a  2 s. co  m

    DBCollection col = mongo.getDataBase().getCollection("files");

    DBObject obj = new BasicDBObject();
    obj.put("type", Resource.ResourceType.FOLDER.toString());
    obj.put("user", username);
    obj.put("name", path[path.length - 1]);
    obj.put("creationDate", new Date());
    obj.put("modificationDate", new Date());
    obj.put("parent", parent.getId());

    col.insert(obj);

    col.update(new BasicDBObject("_id", parent.getId()),
            new BasicDBObject("$set", new BasicDBObject("modificationDate", new Date())));

    return buildResource(obj);
}

From source file:de.ii.ldproxy.gml2json.BufferedTransformingCoordinatesWriter.java

protected double[] postProcessCoordinates(double[] in, int numPts) {
    double[] out;
    if (transformer != null) {
        out = transformer.transform(in, numPts);
    } else {/*from ww w  .j a  v  a 2 s .com*/
        if (this.swap) {
            out = new double[numPts * 2];
            for (int i = 0; i < numPts * 2; i += 2) {
                out[i] = in[i + 1];
                out[i + 1] = in[i];
            }
        } else {
            out = in;
        }
    }
    // das Array das in den Buffer geht muss eine Kopie sein Fall: out = in;
    // Revere Arrays ... [#430]
    if (this.reversepolygon) {
        double[] out2 = new double[numPts * 2];
        for (int i = 0; i < numPts * 2; i++) {
            out2[numPts * 2 - i - 1] = out[i];
        }
        for (int i = 0; i < numPts * 2; i += 2) {
            out[i] = out2[i + 1];
            out[i + 1] = out2[i];
        }
    }

    // just to be shure not returning the full buffer ...
    if (out.length == numPts * 2) {
        return out;
    }
    // else: just the valid range
    return Arrays.copyOfRange(out, 0, numPts * 2);
}

From source file:io.hops.security.TestUsersGroups.java

public void testUsersGroupsCache(int cacheTime, int cacheSize) throws Exception {
    Configuration conf = new Configuration();
    conf.set(CommonConfigurationKeys.HOPS_UG_CACHE_SECS, Integer.toString(cacheTime));
    conf.set(CommonConfigurationKeys.HOPS_UG_CACHE_SIZE, Integer.toString(cacheSize));
    HdfsStorageFactory.resetDALInitialized();
    HdfsStorageFactory.setConfiguration(conf);
    HdfsStorageFactory.formatStorage();/*from   w  w w . j  ava  2  s  .c om*/
    UsersGroups.createSyncRow();

    String currentUser = "user0";

    String[] groups = new String[3];
    for (int i = 0; i < 3; i++) {
        groups[i] = "group" + i;
    }

    try {
        UsersGroups.getUserID(currentUser);
    } catch (UserNotFoundException e) {
    }

    for (String group : groups) {
        try {
            UsersGroups.getGroupID(group);
        } catch (GroupNotFoundException e) {
        }
    }

    UsersGroups.addUser(currentUser);

    for (String group : groups) {
        UsersGroups.addGroup(group);
    }

    for (String group : groups) {
        try {
            UsersGroups.addGroup(group);
        } catch (GroupAlreadyExistsException e) {
        }
    }

    try {
        UsersGroups.addUser(currentUser);
    } catch (UserAlreadyExistsException e) {
    }

    //user0 -> {group0, group1}
    UsersGroups.addUserToGroups(currentUser, Arrays.copyOfRange(groups, 0, 2));

    try {
        UsersGroups.addUserToGroup(currentUser, groups[0]);
    } catch (UserAlreadyInGroupException e) {
    }

    int userId = UsersGroups.getUserID(currentUser);
    assertNotEquals(userId, 0);
    assertEquals(currentUser, UsersGroups.getUser(userId));
    List<String> cachedGroups = UsersGroups.getGroups(currentUser);
    assertNotNull(cachedGroups);
    assertTrue(cachedGroups.equals(Arrays.asList(groups[0], groups[1])));

    for (int i = 0; i < 2; i++) {
        int groupId = UsersGroups.getGroupID(groups[i]);
        assertNotEquals(groupId, 0);
        assertEquals(groups[i], UsersGroups.getGroup(groupId));
    }

    assertNotEquals(UsersGroups.getGroupID(groups[2]), 0);

    //remove group group0
    UsersGroups.removeGroup(groups[0]);

    try {
        UsersGroups.getGroupID(groups[0]);
    } catch (GroupNotFoundException e) {
    }

    cachedGroups = UsersGroups.getGroups(currentUser);
    assertNotNull(cachedGroups);
    assertTrue(cachedGroups.equals(Arrays.asList(groups[1])));

    //remover user from group1
    UsersGroups.removeUserFromGroup(currentUser, groups[1]);

    UsersGroups.getGroupID(groups[1]);
    UsersGroups.getUserID(currentUser);
    try {
        UsersGroups.getGroups(currentUser);
    } catch (GroupsNotFoundForUserException e) {
    }

    //remove group1
    UsersGroups.removeGroup(groups[1]);

    try {
        UsersGroups.getGroupID(groups[1]);
    } catch (GroupNotFoundException e) {
    }

    try {
        UsersGroups.getGroups(currentUser);
    } catch (GroupsNotFoundForUserException e) {
    }

    // append group to user: user0 -> {group2}
    UsersGroups.addUserToGroup(currentUser, groups[2]);

    cachedGroups = UsersGroups.getGroups(currentUser);
    assertNotNull(cachedGroups);
    assertTrue(cachedGroups.equals(Arrays.asList(groups[2])));

    // remove user and group
    UsersGroups.removeUser(currentUser);
    UsersGroups.removeGroup(groups[2]);
    try {
        UsersGroups.getUserID(currentUser);
    } catch (UserNotFoundException e) {
    }
    try {
        UsersGroups.getGroupID(groups[2]);
    } catch (GroupNotFoundException e) {
    }
    try {
        UsersGroups.getGroups(currentUser);
    } catch (UserNotFoundException e) {
    }
}