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:eu.europeana.querylog.learn.Evaluate.java

private float[] getBoosts(float[] params) {
    return Arrays.copyOfRange(params, 1, 1 + nFields);
}

From source file:com.ruizhan.hadoop.hdfs.FsShell.java

/**
 * run// w  w w  . j  a  va 2  s .c om
 */
public int run(String argv[]) throws Exception {
    // initialize FsShell
    init();

    int exitCode = -1;
    if (argv.length < 1) {
        printUsage(System.err);
    } else {
        String cmd = argv[0];
        Command instance = null;
        try {
            instance = commandFactory.getInstance(cmd);
            if (instance == null) {
                throw new UnknownCommandException();
            }
            exitCode = instance.run(Arrays.copyOfRange(argv, 1, argv.length));
        } catch (IllegalArgumentException e) {
            displayError(cmd, e.getLocalizedMessage());
            if (instance != null) {
                printInstanceUsage(System.err, instance);
            }
        } catch (Exception e) {
            // instance.run catches IOE, so something is REALLY wrong if here
            LOG.debug("Error", e);
            displayError(cmd, "Fatal internal error");
            e.printStackTrace(System.err);
        }
    }
    return exitCode;
}

From source file:net.bluehornreader.model.ReadArticlesColl.java

private void trimBitmap(int maxBitmapSize) {
    int firstToKeep = bitmap.length > maxBitmapSize ? bitmap.length - maxBitmapSize : 0;
    while (firstToKeep < bitmap.length - 1 && bitmap[firstToKeep] == (byte) 0xff) {
        ++firstToKeep;//  w  w w . java 2s. c om
        first += 8;
    }
    if (firstToKeep > 0) {
        bitmap = Arrays.copyOfRange(bitmap, firstToKeep, bitmap.length);
    }
}

From source file:com.kentdisplays.synccardboarddemo.Page.java

/**
 * Decodes an input stream from a file into Path objects that can be used to draw the page.
 *//*w w w. java  2  s.  c o  m*/
private static ArrayList<Path> pathsFromSamplePageInputStream(InputStream inputStream) {
    ArrayList<Path> paths = new ArrayList<Path>();
    try {
        // Retrieve a byte array from the sample page.
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) > -1) {
            baos.write(buffer, 0, len);
        }
        baos.flush();
        byte[] byteArray = baos.toByteArray();

        // Decode the path data from the sample page.
        String rawString = EncodingUtils.getAsciiString(byteArray);
        int startIndex = rawString.indexOf("<</Length 13 0 R/Filter /FlateDecode>>") + 46;
        int endIndex = rawString.indexOf("endstream", startIndex) - 1;
        byte[] flateEncodedByteArray = Arrays.copyOfRange(byteArray, startIndex, endIndex);
        net.sf.andpdf.nio.ByteBuffer flateEncodedBuffer = net.sf.andpdf.nio.ByteBuffer
                .NEW(flateEncodedByteArray);
        net.sf.andpdf.nio.ByteBuffer decodedBuffer = FlateDecode.decode(null, flateEncodedBuffer, null);
        String decodedString = new String(decodedBuffer.array(), "UTF-8");

        // Break every line of the decoded string into usable objects.
        String[] stringArray = decodedString.split("\\r?\\n");
        for (int i = 0; i < stringArray.length; i++) {
            String[] components = stringArray[i].split(" ");
            Path path = new Path();
            path.y1 = Float.valueOf(components[2]);
            path.x1 = Float.valueOf(components[3]);
            path.y2 = Float.valueOf(components[5]);
            path.x2 = Float.valueOf(components[6]);
            path.width = Float.valueOf(components[0]);
            paths.add(path);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return paths;
}

From source file:com.intellectualcrafters.plot.commands.Set.java

@SuppressWarnings("deprecation")
@Override//from   w w  w. j ava  2s. c om
public boolean execute(final Player plr, final String... args) {
    if (!PlayerFunctions.isInPlot(plr)) {
        PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
        return false;
    }
    final Plot plot = PlayerFunctions.getCurrentPlot(plr);
    if (!plot.hasOwner()) {
        sendMessage(plr, C.PLOT_NOT_CLAIMED);
        return false;
    }
    if (!plot.hasRights(plr) && !PlotMain.hasPermission(plr, "plots.admin")) {
        PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
        return false;
    }
    if (args.length < 1) {
        PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + getArgumentList(values));
        return false;
    }
    for (int i = 0; i < aliases.length; i++) {
        if (aliases[i].equalsIgnoreCase(args[0])) {
            args[0] = values[i];
            break;
        }
    }
    /* TODO: Implement option */
    // final boolean advanced_permissions = true;
    if (!PlotMain.hasPermission(plr, "plots.set." + args[0].toLowerCase())) {
        PlayerFunctions.sendMessage(plr, C.NO_PERMISSION, "plots.set." + args[0].toLowerCase());
        return false;
    }

    if (args[0].equalsIgnoreCase("flag")) {
        if (args.length < 2) {
            String message = StringUtils.join(FlagManager.getFlags(plr), "&c, &6");
            if (PlotMain.worldGuardListener != null) {
                if (message.equals("")) {
                    message = StringUtils.join(PlotMain.worldGuardListener.str_flags, "&c, &6");
                } else {
                    message += "," + StringUtils.join(PlotMain.worldGuardListener.str_flags, "&c, &6");
                }
            }
            PlayerFunctions.sendMessage(plr, C.NEED_KEY.s().replaceAll("%values%", message));
            return false;
        }

        AbstractFlag af;

        try {
            af = FlagManager.getFlag(args[1].toLowerCase());
        } catch (final Exception e) {
            af = new AbstractFlag(args[1].toLowerCase());
        }

        if (!FlagManager.getFlags().contains(af) && ((PlotMain.worldGuardListener == null)
                || !PlotMain.worldGuardListener.str_flags.contains(args[1].toLowerCase()))) {
            PlayerFunctions.sendMessage(plr, C.NOT_VALID_FLAG);
            return false;
        }
        if (!PlotMain.hasPermission(plr, "plots.set.flag." + args[1].toLowerCase())) {
            PlayerFunctions.sendMessage(plr, C.NO_PERMISSION);
            return false;
        }
        if (args.length == 2) {
            if (plot.settings.getFlag(args[1].toLowerCase()) == null) {
                if (PlotMain.worldGuardListener != null) {
                    if (PlotMain.worldGuardListener.str_flags.contains(args[1].toLowerCase())) {
                        PlotMain.worldGuardListener.removeFlag(plr, plr.getWorld(), plot, args[1]);
                        return false;
                    }
                }
                PlayerFunctions.sendMessage(plr, C.FLAG_NOT_IN_PLOT);
                return false;
            }
            final Flag flag = plot.settings.getFlag(args[1].toLowerCase());
            final PlotFlagRemoveEvent event = new PlotFlagRemoveEvent(flag, plot);
            Bukkit.getServer().getPluginManager().callEvent(event);
            if (event.isCancelled()) {
                PlayerFunctions.sendMessage(plr, C.FLAG_NOT_REMOVED);
                event.setCancelled(true);
                return false;
            }
            final java.util.Set<Flag> newflags = plot.settings.getFlags();
            final Flag oldFlag = plot.settings.getFlag(args[1].toLowerCase());
            if (oldFlag != null) {
                newflags.remove(oldFlag);
            }
            plot.settings.setFlags(newflags.toArray(new Flag[newflags.size()]));
            DBFunc.setFlags(plr.getWorld().getName(), plot, newflags.toArray(new Flag[newflags.size()]));
            PlayerFunctions.sendMessage(plr, C.FLAG_REMOVED);
            PlotListener.plotEntry(plr, plot);
            return true;
        }
        try {
            String value = StringUtils.join(Arrays.copyOfRange(args, 2, args.length), " ");
            value = af.parseValue(value);
            if (value == null) {
                PlayerFunctions.sendMessage(plr, af.getValueDesc());
                return false;
            }

            if ((FlagManager.getFlag(args[1].toLowerCase()) == null) && (PlotMain.worldGuardListener != null)) {
                PlotMain.worldGuardListener.addFlag(plr, plr.getWorld(), plot, args[1], value);
                return false;
            }

            final Flag flag = new Flag(FlagManager.getFlag(args[1].toLowerCase(), true), value);
            final PlotFlagAddEvent event = new PlotFlagAddEvent(flag, plot);
            Bukkit.getServer().getPluginManager().callEvent(event);
            if (event.isCancelled()) {
                PlayerFunctions.sendMessage(plr, C.FLAG_NOT_ADDED);
                event.setCancelled(true);
                return false;
            }
            plot.settings.addFlag(flag);
            java.util.Set<Flag> flags = plot.settings.getFlags();
            DBFunc.setFlags(plr.getWorld().getName(), plot, flags.toArray(new Flag[flags.size()]));
            PlayerFunctions.sendMessage(plr, C.FLAG_ADDED);
            PlotListener.plotEntry(plr, plot);
            return true;
        } catch (final Exception e) {
            PlayerFunctions.sendMessage(plr, "&c" + e.getMessage());
            return false;
        }
    }

    if (args[0].equalsIgnoreCase("home")) {
        if (args.length < 2) {
            PlayerFunctions.sendMessage(plr, C.MISSING_POSITION);
            return false;
        }
        PlotHomePosition position = null;
        for (final PlotHomePosition p : PlotHomePosition.values()) {
            if (p.isMatching(args[1])) {
                position = p;
            }
        }
        if (position == null) {
            PlayerFunctions.sendMessage(plr, C.INVALID_POSITION);
            return false;
        }
        DBFunc.setPosition(plr.getWorld().getName(), plot, position.toString());
        PlayerFunctions.sendMessage(plr, C.POSITION_SET);
        return true;
    }

    if (args[0].equalsIgnoreCase("alias")) {
        if (args.length < 2) {
            PlayerFunctions.sendMessage(plr, C.MISSING_ALIAS);
            return false;
        }
        final String alias = args[1];
        for (final Plot p : PlotMain.getPlots(plr.getWorld()).values()) {
            if (p.settings.getAlias().equalsIgnoreCase(alias)) {
                PlayerFunctions.sendMessage(plr, C.ALIAS_IS_TAKEN);
                return false;
            }
            if (Bukkit.getOfflinePlayer(alias).hasPlayedBefore()) {
                PlayerFunctions.sendMessage(plr, C.ALIAS_IS_TAKEN);
                return false;
            }
        }
        DBFunc.setAlias(plr.getWorld().getName(), plot, alias);
        PlayerFunctions.sendMessage(plr, C.ALIAS_SET_TO.s().replaceAll("%alias%", alias));
        return true;
    }
    if (args[0].equalsIgnoreCase("biome")) {
        if (args.length < 2) {
            PlayerFunctions.sendMessage(plr, C.NEED_BIOME);
            return true;
        }
        if (args[1].length() < 2) {
            sendMessage(plr, C.NAME_LITTLE, "Biome", args[1].length() + "", "2");
            return true;
        }

        final Biome biome = Biome.valueOf(new StringComparison(args[1], Biome.values()).getBestMatch());
        /*
         * for (Biome b : Biome.values()) {
         * if (b.toString().equalsIgnoreCase(args[1])) {
         * biome = b;
         * break;
         * }
         * }
         */

        if (biome == null) {
            PlayerFunctions.sendMessage(plr, getBiomeList(Arrays.asList(Biome.values())));
            return true;
        }
        PlotHelper.setBiome(plr.getWorld(), plot, biome);
        PlayerFunctions.sendMessage(plr, C.BIOME_SET_TO.s() + biome.toString().toLowerCase());
        return true;
    }
    if (args[0].equalsIgnoreCase("wall")) {
        final PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld());
        if (plotworld == null) {
            PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
            return true;
        }
        if (args.length < 2) {
            PlayerFunctions.sendMessage(plr, C.NEED_BLOCK);
            return true;
        }
        if (args[1].length() < 2) {
            sendMessage(plr, C.NAME_LITTLE, "Material", args[1].length() + "", "2");
            return true;
        }
        Material material;
        try {
            material = getMaterial(args[1], PlotWorld.BLOCKS);
        } catch (NullPointerException e) {
            material = null;
        }
        /*
         * for (Material m : PlotWorld.BLOCKS) {
         * if (m.toString().equalsIgnoreCase(args[1])) {
         * material = m;
         * break;
         * }
         * }
         */
        if (material == null) {
            PlayerFunctions.sendMessage(plr, getBlockList(PlotWorld.BLOCKS));
            return true;
        }
        byte data = 0;

        if (args.length > 2) {
            try {
                data = (byte) Integer.parseInt(args[2]);
            } catch (final Exception e) {
                PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA);
                return true;
            }
        }
        PlayerFunctions.sendMessage(plr, C.GENERATING_WALL);
        PlotHelper.adjustWall(plr, plot, new PlotBlock((short) material.getId(), data));
        return true;
    }
    if (args[0].equalsIgnoreCase("floor")) {
        if (args.length < 2) {
            PlayerFunctions.sendMessage(plr, C.NEED_BLOCK);
            return true;
        }
        final PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld());
        if (plotworld == null) {
            PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
            return true;
        }
        //
        @SuppressWarnings("unchecked")
        final ArrayList<Material> materials = (ArrayList<Material>) PlotWorld.BLOCKS.clone();
        materials.add(Material.AIR);
        //
        final String[] strings = args[1].split(",");
        //
        int index = 0;
        //
        Material m;
        //
        final PlotBlock[] blocks = new PlotBlock[strings.length];

        for (String s : strings) {
            s = s.replaceAll(",", "");
            final String[] ss = s.split(";");
            ss[0] = ss[0].replaceAll(";", "");
            if (ss[0].length() < 2) {
                sendMessage(plr, C.NAME_LITTLE, "Material", ss[0].length() + "", "2");
                return true;
            }
            m = getMaterial(ss[0], materials);
            /*
             * for (Material ma : materials) {
             * if (ma.toString().equalsIgnoreCase(ss[0])) {
             * m = ma;
             * }
             * }
             */
            if (m == null) {
                PlayerFunctions.sendMessage(plr, C.NOT_VALID_BLOCK);
                return true;
            }
            if (ss.length == 1) {

                blocks[index] = new PlotBlock((short) m.getId(), (byte) 0);
            } else {
                byte b;
                try {
                    b = (byte) Integer.parseInt(ss[1]);
                } catch (final Exception e) {
                    PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA);
                    return true;
                }
                blocks[index] = new PlotBlock((short) m.getId(), b);
            }
            index++;
        }
        PlotHelper.setFloor(plr, plot, blocks);
        return true;
    }
    if (args[0].equalsIgnoreCase("wall_filling")) {
        if (args.length < 2) {
            PlayerFunctions.sendMessage(plr, C.NEED_BLOCK);
            return true;
        }
        final PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld());
        if (plotworld == null) {
            PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
            return true;
        }
        if (args[1].length() < 2) {
            sendMessage(plr, C.NAME_LITTLE, "Material", args[1].length() + "", "2");
            return true;
        }
        final Material material = getMaterial(args[1], PlotWorld.BLOCKS);
        /*
         * for (Material m : PlotWorld.BLOCKS) {
         * if (m.toString().equalsIgnoreCase(args[1])) {
         * material = m;
         * break;
         * }
         * }
         */

        if (material == null) {
            PlayerFunctions.sendMessage(plr, getBlockList(PlotWorld.BLOCKS));
            return true;
        }
        byte data = 0;

        if (args.length > 2) {
            try {
                data = (byte) Integer.parseInt(args[2]);
            } catch (final Exception e) {
                PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA);
                return true;
            }
        }
        PlotHelper.adjustWallFilling(plr, plot, new PlotBlock((short) material.getId(), data));
        return true;
    }
    {
        AbstractFlag af;
        try {
            af = new AbstractFlag(args[0].toLowerCase());
        } catch (final Exception e) {
            af = new AbstractFlag("");
        }
        if (FlagManager.getFlags().contains(af)) {
            final StringBuilder a = new StringBuilder();
            if (args.length > 1) {
                for (int x = 1; x < args.length; x++) {
                    a.append(" ").append(args[x]);
                }
            }
            plr.performCommand("plot set flag " + args[0] + a.toString());
            return true;
        }
    }
    PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + getArgumentList(values));
    return false;
}

From source file:org.auraframework.integration.test.http.AuraFrameworkServletHttpTest.java

/**
 * Verify that incomplete resource path returns SC_NOT_FOUND(404). Subsequent requests for valid resource on the
 * same path are successful.//from   w w  w  .  j a  v  a 2 s .c  o  m
 *
 * @throws Exception
 */
@Test
public void testRequestingFolderAsFileNotAllowed() throws Exception {
    String[] parts = sampleBinaryResourcePath.split("/");
    // Accessing folder(which might have had previous valid access) as file
    String incompletePath = StringUtils.join(Arrays.copyOfRange(parts, 0, parts.length - 1), "/");
    verifyResourceAccess(incompletePath, HttpStatus.SC_NOT_FOUND,
            "Expected server to return a 404 status for folder as file.");

    // Accessing a valid folder
    verifyResourceAccess(incompletePath + "/", HttpStatus.SC_NOT_FOUND,
            "Expected server to return a 404 status for folders(incomplete paths).");

    // Subsequent requests for filed on same path are accepted and serviced
    verifyResourceAccess(sampleBinaryResourcePath, HttpStatus.SC_OK,
            "Expected server to return a 200 status for valid resource.");

}

From source file:com.gargoylesoftware.htmlunit.javascript.host.xml.XMLHttpRequest2Test.java

/**
 * XHR.open throws an exception if URL parameter is null or empty string.
 * @throws Exception if an error occurs/*from  w ww  .j  ava2s .  co  m*/
 */
@Test
@Alerts(DEFAULT = { "5", "pass", "pass", "pass", "pass" }, IE = { "1", "exception", "exception", "pass",
        "pass" })
@NotYetImplemented(IE)
// real IE11 invokes just one request and returns the other two responses from it's cache
public void openThrowOnEmptyUrl() throws Exception {
    final String html = "<html><head>\n" + "<script>\n" + "var xhr = " + XHRInstantiation_ + ";\n"
            + "var values = [null, '', ' ', '  \\t  '];\n" + "for (var i = 0; i < values.length; i++) {\n"
            + "  try {\n" + "    xhr.open('GET', values[i], false);\n" + "    xhr.send('');\n"
            + "    alert('pass');\n" + "  } catch(e) { alert('exception') }\n" + "}\n" + "</script>\n"
            + "</head>\n" + "<body></body>\n</html>";

    final int expectedRequests = Integer.parseInt(getExpectedAlerts()[0]);
    setExpectedAlerts(Arrays.copyOfRange(getExpectedAlerts(), 1, getExpectedAlerts().length));

    loadPageWithAlerts2(html);

    assertEquals(expectedRequests, getMockWebConnection().getRequestCount());
}

From source file:de.elomagic.carafile.client.CaraFileClientTest.java

@Test
public void testDownload2() throws Exception {
    Random random = new Random();
    random.nextBytes(data0);/*from  w w w.  j a  v a  2  s . c o  m*/
    random.nextBytes(data1);

    chunkId0 = Hex.encodeHexString(DigestUtils.sha1(data0));
    chunkId1 = Hex.encodeHexString(DigestUtils.sha1(data1));

    MessageDigest messageDigest = DigestUtils.getSha1Digest();
    messageDigest.update(data0);
    messageDigest.update(data1);

    id = Hex.encodeHexString(messageDigest.digest());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    client.setRegistryURI(getURI()).downloadFile(id, baos);

    Assert.assertArrayEquals(data0, Arrays.copyOf(baos.toByteArray(), DEFAULT_PIECE_SIZE));
    Assert.assertArrayEquals(data1,
            Arrays.copyOfRange(baos.toByteArray(), DEFAULT_PIECE_SIZE, DEFAULT_PIECE_SIZE + 128));
}

From source file:com.datatorrent.contrib.hdht.HDHTReader.java

@Override
public synchronized byte[] get(long bucketKey, Slice key) throws IOException {
    // this method is synchronized to support asynchronous reads outside operator thread
    for (int i = 0; i < 10; i++) {
        BucketReader bucket = getReader(bucketKey);
        BucketMeta bucketMeta = bucket.bucketMeta;
        if (bucketMeta == null) {
            // meta data invalidated
            continue;
        }/*from  w  ww .j av a2  s. c  o m*/

        Map.Entry<Slice, BucketFileMeta> floorEntry = bucket.bucketMeta.files.floorEntry(key);
        if (floorEntry == null) {
            // no file for this key
            return null;
        }

        try {
            FileAccess.FileReader reader = bucket.readers.get(floorEntry.getValue().name);
            if (reader == null) {
                LOG.debug("Opening file {} {}", bucketKey, floorEntry.getValue().name);
                bucket.readers.put(floorEntry.getValue().name,
                        reader = store.getReader(bucketKey, floorEntry.getValue().name));
            }
            Slice value = new Slice(null, 0, 0);
            if (reader.seek(key)) {
                reader.next(GET_KEY, value);
            }
            if (value.offset == 0) {
                return value.buffer;
            } else {
                // this is inefficient, should return Slice
                return Arrays.copyOfRange(value.buffer, value.offset, value.offset + value.length);
            }
        } catch (IOException e) {
            // check for meta file update
            this.buckets.remove(bucketKey);
            bucket.close();
            bucket = getReader(bucketKey);
            Map.Entry<Slice, BucketFileMeta> newEntry = bucket.bucketMeta.files.floorEntry(key);
            if (newEntry != null && newEntry.getValue().name.compareTo(floorEntry.getValue().name) == 0) {
                // file still the same - error unrelated to rewrite
                throw e;
            }
            // retry
            LOG.debug("Retry after meta data change bucket {} from {} to {}", bucketKey, floorEntry, newEntry);
            continue;
        }
    }
    return null;
}

From source file:bachelorthesis.methods.detection.bayesian.BayesianDetection.java

private Value[] copyOfRange(Value[] array, int from, int to) {
    return Arrays.copyOfRange(array, from, Math.min(to, array.length));
}