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:de.l3s.archivepig.DataEvalFunc.java

public <T> T get(Tuple tuple, Schema schema, String field) {
    String[] fields = field.split("\\.");
    for (int i = 0; i < fields.length; i++) {
        boolean wildcard = fields[i].equals("");
        if (wildcard)
            i++;//from  w ww . jav a 2 s.  c  om
        boolean last = (i == (fields.length - 1));
        try {
            FieldSchema fieldSchema = schema.getField(fields[i]);
            if (fieldSchema == null) {
                if (wildcard) {
                    String subWildcardQuery = "."
                            + StringUtils.join(Arrays.copyOfRange(fields, i, fields.length), ".");
                    for (FieldSchema wildField : schema.getFields()) {
                        if (wildField.type != DataType.TUPLE)
                            continue;
                        try {
                            T wildValue = get((Tuple) tuple.get(schema.getPosition(wildField.alias)),
                                    wildField.schema, subWildcardQuery);
                            if (wildValue != null)
                                return wildValue;
                        } catch (Exception e) {
                            continue;
                        }
                    }
                }
                return null;
            }
            if (last) {
                Object value = tuple.get(schema.getPosition(fields[i]));
                if (fieldSchema.type == DataType.TUPLE
                        && fieldSchema.schema.getAliases().contains(ArchivePigConst.VALUE_FIELDNAME)) {
                    return (T) ((Tuple) value)
                            .get(fieldSchema.schema.getPosition(ArchivePigConst.VALUE_FIELDNAME));
                } else {
                    return (T) value;
                }
            }
            if (fieldSchema.schema == null)
                return null;
            tuple = (Tuple) tuple.get(schema.getPosition(fields[i]));
            schema = fieldSchema.schema;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    return null;
}

From source file:com.haulmont.cuba.web.app.folders.FoldersBean.java

@Override
public void openFolder(AbstractSearchFolder folder) {
    if (StringUtils.isBlank(folder.getFilterComponentId())) {
        log.warn("Unable to open folder: componentId is blank");
        return;/*from  w w w.  j  a  v  a  2 s. c  o  m*/
    }

    String[] strings = ValuePathHelper.parse(folder.getFilterComponentId());
    String screenId = strings[0];

    WindowConfig windowConfig = AppBeans.get(WindowConfig.NAME);
    WindowInfo windowInfo = windowConfig.getWindowInfo(screenId);

    Map<String, Object> params = new HashMap<>();

    WindowParams.DISABLE_AUTO_REFRESH.set(params, true);
    WindowParams.DISABLE_RESUME_SUSPENDED.set(params, true);

    if (!StringUtils.isBlank(folder.getTabName())) {
        WindowParams.DESCRIPTION.set(params, messages.getMainMessage(folder.getTabName()));
    } else {
        WindowParams.DESCRIPTION.set(params, messages.getMainMessage(folder.getName()));
    }

    WindowParams.FOLDER_ID.set(params, folder.getId());

    com.haulmont.cuba.gui.components.Window window = App.getInstance().getWindowManager().openWindow(windowInfo,
            OpenType.NEW_TAB, params);

    Filter filterComponent = null;

    if (strings.length > 1) {
        String filterComponentId = StringUtils.join(Arrays.copyOfRange(strings, 1, strings.length), '.');

        filterComponent = (Filter) window.getComponentNN(filterComponentId);

        FilterEntity filterEntity = metadata.create(FilterEntity.class);
        filterEntity.setFolder(folder);
        filterEntity.setComponentId(folder.getFilterComponentId());
        filterEntity.setName(folder.getLocName());

        filterEntity.setXml(folder.getFilterXml());
        filterEntity.setApplyDefault(BooleanUtils.isNotFalse(folder.getApplyDefault()));
        if (folder instanceof SearchFolder) {
            filterEntity.setIsSet(((SearchFolder) folder).getIsSet());
        }
        filterComponent.setFilterEntity(filterEntity);
        filterComponent.switchFilterMode(FilterDelegate.FilterMode.GENERIC_MODE);
    }

    if (filterComponent != null && folder instanceof SearchFolder) {
        final SearchFolder searchFolder = (SearchFolder) folder;
        if (searchFolder.getPresentation() != null) {
            ((com.haulmont.cuba.gui.components.Component.HasPresentations) filterComponent.getApplyTo())
                    .applyPresentation(searchFolder.getPresentation().getId());
        }
    }

    ((DsContextImplementation) window.getDsContext()).resumeSuspended();
}

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

@Override
public boolean execute(final Player plr, final String... args) {
    if (!PlayerFunctions.isInPlot(plr)) {
        return sendMessage(plr, C.NOT_IN_PLOT);
    }//from w w w .  j  a v a2s  .  c  o  m
    final Plot plot = PlayerFunctions.getCurrentPlot(plr);
    if (!plot.hasOwner()) {
        return sendMessage(plr, C.NOT_IN_PLOT);
    }

    final List<String> recipients = Arrays.asList("admin", "owner", "helper", "trusted", "everyone");

    if ((args.length == 2) && recipients.contains(args[0].toLowerCase())) {

        if (PlotMain.hasPermission(plr, "plots.comment." + args[0].toLowerCase())) {
            final String text = StringUtils.join(Arrays.copyOfRange(args, 1, args.length), " ");
            final PlotComment comment = new PlotComment(text, plr.getName(),
                    recipients.indexOf(args[0].toLowerCase()));
            plot.settings.addComment(comment);

            DBFunc.setComment(plr.getWorld().getName(), plot, comment);

            return true;
        } else {
            return sendMessage(plr, C.NO_PERMISSION, "plots.comment." + args[0].toLowerCase());
        }
    }
    return sendMessage(plr, C.COMMENT_SYNTAX);
}

From source file:com.opengamma.maths.lowlevelapi.datatypes.primitive.CompressedSparseColumnFormatMatrix.java

/**
 * Construct from DoubleMatrix2D type// w w  w . j a  v a2  s  . c  om
 * @param m is a DoubleMatrix2D
 */
public CompressedSparseColumnFormatMatrix(DoubleMatrix2D m) {
    Validate.notNull(m);

    //get number of elements
    _els = m.getNumberOfElements();

    // tmp arrays, in case we get in a fully populated matrix, intelligent design upstream should ensure that this is overkill!
    double[] dataTmp = new double[_els];
    int[] colPtrTmp = new int[_els + 1];
    int[] rowIdxTmp = new int[_els];

    // we need unwind the array m into coordinate form
    int ptr = 0;
    int i;
    int localMaxEntrisInACol;
    _maxEntriesInAColumn = -1;
    for (i = 0; i < m.getNumberOfColumns(); i++) {
        colPtrTmp[i] = ptr;
        localMaxEntrisInACol = 0;
        for (int j = 0; j < m.getNumberOfRows(); j++) {
            if (Double.doubleToLongBits(m.getEntry(j, i)) != 0L) {
                rowIdxTmp[ptr] = j;
                dataTmp[ptr] = m.getEntry(j, i);
                ptr++;
                localMaxEntrisInACol++;
            }
        }
        if (localMaxEntrisInACol > _maxEntriesInAColumn) {
            _maxEntriesInAColumn = localMaxEntrisInACol;
        }
    }
    colPtrTmp[i] = ptr;

    // return correct 0 to correct length of the vector buffers
    _values = Arrays.copyOfRange(dataTmp, 0, ptr);
    _colPtr = Arrays.copyOfRange(colPtrTmp, 0, i + 1); // yes, the +1 is correct, it allows the computation of the number of elements in the final row!
    _rowIdx = Arrays.copyOfRange(rowIdxTmp, 0, ptr);
    _rows = m.getNumberOfRows();
    _cols = m.getNumberOfColumns();
}

From source file:io.dfox.junit.http.JUnitHttpServlet.java

/**
 * Join the path components after the first element, which is the dispatch prefix.
 * /*from ww  w  .j a  v a  2 s  . com*/
 * @param pathComponents The path components
 * @return The joined path
 */
private String joinPathAfterPrefix(final String[] pathComponents) {
    final String[] dataPathComponents = Arrays.copyOfRange(pathComponents, 1, pathComponents.length);
    return StringUtils.join(dataPathComponents, "/");
}

From source file:cn.guoyukun.spring.SpeedUpSpringProcessor.java

/**
 * ?bean???  bean@property/*  w ww .j  a  v  a2s . c o  m*/
 * 
 * ??bean???  bean@property=123
 * @param removeOrReplaceBeanProperties
 */
public void setRemoveOrReplaceBeanProperties(String[] removeOrReplaceBeanProperties) {
    this.removedBeanProperties = new HashMap<String, Set<String[]>>(removeOrReplaceBeanProperties.length);
    for (String removeOrReplaceBeanProperty : removeOrReplaceBeanProperties) {

        int equalIndex = removeOrReplaceBeanProperty.indexOf('=');
        boolean isReplace = equalIndex >= 0;

        String removeBeanProperty = removeOrReplaceBeanProperty;
        if (isReplace) {
            removeBeanProperty = removeBeanProperty.substring(0, equalIndex);
        }

        String[] properties = removeBeanProperty.split("@");
        String beanName = properties[0];

        Set<String[]> propertiesSet = this.removedBeanProperties.get(beanName);

        if (propertiesSet == null) {
            propertiesSet = new HashSet<String[]>();
            this.removedBeanProperties.put(beanName, propertiesSet);
        }
        propertiesSet.add(Arrays.copyOfRange(properties, 1, properties.length));

        if (isReplace) {
            this.replaceBeanProperties = new HashMap<String, String>();
            String[] props = removeOrReplaceBeanProperty.split("=");
            this.replaceBeanProperties.put(props[0], props[1]);
        }

    }

}

From source file:cc.arduino.plugins.wifi101.flashers.java.WINCFlasher.java

@Override
public void updateFirmware(String port) throws Exception {
    FlasherSerialClient client = null;/*from  www  .j a  v  a 2  s.c om*/
    try {
        file = openFirmwareFile();
        progress(10, "Connecting to programmer...");
        client = new FlasherSerialClient();
        client.open(port, this.baudrate);
        client.hello();
        int maxPayload = client.getMaximumPayload();

        byte[] fwData = this.getData();
        int size = fwData.length;
        int address = 0x00000000;
        int written = 0;

        progress(20, "Erasing target...");
        client.eraseFlash(address, size);

        while (written < size) {
            progress(20 + written * 40 / size, "Programming " + size + " bytes ...");
            int len = maxPayload;
            if (written + len > size) {
                len = size - written;
            }
            client.writeFlash(address, Arrays.copyOfRange(fwData, written, written + len));
            written += len;
            address += len;
        }
        int readed = 0;
        address = 0x00000000;
        while (readed < size) {
            progress(60 + readed * 40 / size, "Verifying...");
            int len = maxPayload;
            if (readed + len > size) {
                len = size - readed;
            }
            byte[] data = client.readFlash(address, len);
            if (!Arrays.equals(data, Arrays.copyOfRange(fwData, readed, readed + len))) {
                throw new Exception("Error during verify at address " + address);
            }
            readed += len;
            address += len;
        }
        progress(100, "Done!");
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:com.willetinc.hadoop.mapreduce.dynamodb.BinarySplitter.java

@Override
void generateRangeKeySplits(Configuration conf, List<InputSplit> splits, Types hashKeyType,
        AttributeValue hashKeyValue, Types rangeKeyType, AttributeValue minRangeKeyValue,
        AttributeValue maxRangeKeyValue, int numRangeSplits) {

    byte[] minBytes = minRangeKeyValue.getB().array();
    byte[] maxBytes = maxRangeKeyValue.getB().array();

    // If there is a common prefix between minString and maxString,
    // establish it
    // and pull it out of minString and maxString.
    int maxPrefixLen = Math.min(minBytes.length, maxBytes.length);
    int sharedLen;
    for (sharedLen = 0; sharedLen < maxPrefixLen; sharedLen++) {
        byte b1 = minBytes[sharedLen];
        byte b2 = maxBytes[sharedLen];
        if (b1 != b2) {
            break;
        }//from w w  w  .  j a va2  s. c  o  m
    }

    // The common prefix has length 'sharedLen'. Extract it from both.
    byte[] commonPrefix = Arrays.copyOfRange(minBytes, 0, sharedLen);
    minBytes = Arrays.copyOfRange(minBytes, sharedLen, minBytes.length);
    maxBytes = Arrays.copyOfRange(maxBytes, sharedLen, maxBytes.length);

    List<BigDecimal> splitValues = split(numRangeSplits, minBytes, maxBytes);

    // Convert the list of split point strings into an actual set of
    // InputSplits.
    byte[] start = ArrayUtils.addAll(commonPrefix, bigDecimalToByteArray(splitValues.get(0), MAX_BYTES));
    for (int i = 1; i < splitValues.size(); i++) {
        byte[] end = ArrayUtils.addAll(commonPrefix, bigDecimalToByteArray(splitValues.get(i), MAX_BYTES));

        //if (compareBytes(start, end) >= 0)
        //   continue;

        List<AttributeValue> rangeKeyValues = new ArrayList<AttributeValue>();
        rangeKeyValues.add(new AttributeValue().withB(ByteBuffer.wrap(start)));
        rangeKeyValues.add(new AttributeValue().withB(ByteBuffer.wrap(end)));

        splits.add(new DynamoDBQueryInputFormat.DynamoDBQueryInputSplit(hashKeyType, hashKeyValue, rangeKeyType,
                rangeKeyValues, ComparisonOperator.BETWEEN));

        start = ArrayUtils.addAll(end, new byte[] { 0x0 });
    }
}

From source file:com.chiorichan.console.CommandDispatch.java

public static void handleCommands() {
    for (Entry<InteractiveConsole, List<Interviewer>> entry : interviewers.entrySet()) {
        if (activeInterviewer.get(entry.getKey()) == null) {
            if (entry.getValue().isEmpty()) {
                interviewers.remove(entry.getKey());
                entry.getKey().resetPrompt();
            } else {
                Interviewer i = entry.getValue().remove(0);
                activeInterviewer.put(entry.getKey(), i);
                entry.getKey().setPrompt(i.getPrompt());
            }//w  ww.  jav a2  s .co  m
        }
    }

    while (!pendingCommands.isEmpty()) {
        CommandRef command = pendingCommands.remove(0);

        try {
            Interviewer i = activeInterviewer.get(command.handler);
            InteractivePermissible permissible = command.handler.getPersistence();

            if (i != null) {
                if (i.handleInput(command.command))
                    activeInterviewer.remove(command.handler);
                else
                    command.handler.prompt();
            } else {
                CommandIssuedEvent event = new CommandIssuedEvent(command.command, permissible);

                Loader.getEventBus().callEvent(event);

                if (event.isCancelled()) {
                    permissible.sendMessage(ConsoleColor.RED + "Your entry was cancelled by the event system.");
                    return;
                }

                String[] args = PATTERN_ON_SPACE.split(command.command);

                if (args.length > 0) {
                    String sentCommandLabel = args[0].toLowerCase();
                    Command target = getCommand(sentCommandLabel);

                    if (target != null) {
                        try {
                            if (target.testPermission(permissible))
                                target.execute(command.handler, sentCommandLabel,
                                        Arrays.copyOfRange(args, 1, args.length));

                            return;
                        } catch (CommandException ex) {
                            throw ex;
                        } catch (Throwable ex) {
                            command.handler.sendMessage(
                                    ConsoleColor.RED + "Unhandled exception executing '" + command.command
                                            + "' in " + target + "\n" + ExceptionUtils.getStackTrace(ex));

                            throw new CommandException(
                                    "Unhandled exception executing '" + command.command + "' in " + target, ex);
                        }
                    }
                }

                permissible.sendMessage(
                        ConsoleColor.YELLOW + "Your entry was unrecognized, type \"help\" for help.");
            }
        } catch (Exception ex) {
            Loader.getLogger().warning(
                    "Unexpected exception while parsing console command \"" + command.command + '"', ex);
        }
    }
}

From source file:cache.PathCacheExample.java

private static void processCommands(CuratorFramework client, PathChildrenCache cache) throws Exception {
    // More scaffolding that does a simple command line processor

    printHelp();/*from www  .j a  v  a2 s  .  c  om*/

    List<ExampleServer> servers = Lists.newArrayList();
    try {
        addListener(cache);

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        boolean done = false;
        while (!done) {
            System.out.print("> ");

            String command = in.readLine().trim();
            String[] parts = command.split("\\s");
            if (parts.length == 0) {
                continue;
            }
            String operation = parts[0];
            String args[] = Arrays.copyOfRange(parts, 1, parts.length);

            if (operation.equalsIgnoreCase("help") || operation.equalsIgnoreCase("?")) {
                printHelp();
            } else if (operation.equalsIgnoreCase("q") || operation.equalsIgnoreCase("quit")) {
                done = true;
            } else if (operation.equals("set")) {
                setValue(client, command, args);
            } else if (operation.equals("remove")) {
                remove(client, command, args);
            } else if (operation.equals("list")) {
                list(cache);
            }

            Thread.sleep(1000); // just to allow the console output to catch up
        }
    } finally {
        for (ExampleServer server : servers) {
            IOUtils.closeQuietly(server);
        }
    }
}