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:ca.appbox.monitoring.jmx.jmxbox.commons.context.parser.JmxContextParserImpl.java

private void addInvokeOperationCommands(JmxContext context, CommandLine commandLine) throws JmxException {

    String[] invokeCommands = commandLine.getOptionValues(CommandLineOptions.INVOKE);

    if (invokeCommands != null) {

        for (String invokeCommandParameter : Arrays.asList(invokeCommands)) {

            String[] splittedReadCommand = invokeCommandParameter.split(";");

            // Has to be at least mBean;operationName
            if (splittedReadCommand.length < 2) {
                throw new JmxException(
                        "MBean invoke operation has to specifty at least the name of the mBean and the operation to invoke.");
            } else {

                JmxCommand invokeCommand = new JmxInvokeOperationCommandImpl(splittedReadCommand[0],
                        splittedReadCommand[1]);

                List<String> mBeanAttributes = Arrays
                        .asList(Arrays.copyOfRange(splittedReadCommand, 2, splittedReadCommand.length));

                for (String commandAttribute : mBeanAttributes) {
                    ((JmxInvokeOperationCommandImpl) invokeCommand).addParameter(commandAttribute);
                }/*from   w ww .j  av a 2 s  . c  o  m*/

                context.addCommand(invokeCommand);
            }
        }
    }
}

From source file:de.csdev.ebus.utils.EBusConsoleUtils.java

/**
 * Returns telegram analyze data//from w  w w.  ja va 2  s  .com
 *
 * @param registry
 * @param data
 * @return
 */
public static String analyzeTelegram(EBusCommandRegistry registry, byte[] data) {

    StringBuilder sb = new StringBuilder();
    try {
        byte[] edata = null;

        sb.append("\n");

        try {
            edata = EBusCommandUtils.checkRawTelegram(data);
        } catch (EBusDataException e) {

            String msg = String.format("** Error on checking telegram: %s **", e.getMessage());
            int len = msg.length();

            sb.append("\n");
            sb.append(StringUtils.repeat("*", len) + "\n");
            sb.append(msg + "\n");

            msg = "**     !!! Warning: All following results are wrong and only displayed for information purpose !!!";
            msg += StringUtils.repeat(" ", len - msg.length() - 2) + "**";

            sb.append(msg + "\n");
            sb.append(StringUtils.repeat("*", len) + "\n");
            sb.append("\n");

            return sb.toString();
        }

        sb.append("\n");
        sb.append("Check and unescape telegram\n");
        sb.append("***************************\n");
        sb.append("\n");

        sb.append(String.format("Original data : %s\n", EBusUtils.toHexDumpString(data)));
        sb.append(String.format("Unescaped data: %s\n", EBusUtils.toHexDumpString(edata)));

        byte[] command = Arrays.copyOfRange(edata, 2, 4);

        boolean isMasterMaster = EBusUtils.isMasterAddress(edata[1]);
        boolean isBroadcast = edata[1] == EBusConsts.BROADCAST_ADDRESS;
        boolean isMasterSlave = !isMasterMaster && !isBroadcast;

        int masterDataLenPos = 4;
        int masterDataLen = edata[masterDataLenPos];
        byte[] masterData = Arrays.copyOfRange(edata, 5, 5 + masterDataLen);

        int masterCrcPos = 5 + masterDataLen;
        int slaveACKPos = masterCrcPos + 1;

        String dataString = EBusUtils.toHexDumpString(edata).toString();
        int dataLen = dataString.length();

        sb.append("\n");
        sb.append("Analyse the telegram\n");
        sb.append("********************\n");

        sb.append("\n");
        sb.append(dataString + "\n");

        final String FORMAT = "%-20s | %-20s | %s";

        sb.append(createTelegramResoverRow(0, 1, dataLen,
                String.format(FORMAT, "Source address", "Type: " + addressType(edata[0]), hex(edata[0]))));

        sb.append(createTelegramResoverRow(1, 1, dataLen,
                String.format(FORMAT, "Destination address", "Type: " + addressType(edata[1]), hex(edata[1]))));

        sb.append(createTelegramResoverRow(2, 2, dataLen, String.format(FORMAT, "Command", "", hex(command))));

        sb.append(createTelegramResoverRow(4, 1, dataLen,
                String.format(FORMAT, "Master Data Length", "Length: " + edata[4], hex(edata[4]))));

        sb.append(createTelegramResoverRow(5, masterDataLen, dataLen,
                String.format(FORMAT, "Master Data", "", hex(masterData))));

        sb.append(createTelegramResoverRow(masterCrcPos, 1, dataLen,
                String.format(FORMAT, "Master CRC", "", hex(edata[masterCrcPos]))));

        if (isMasterMaster) {
            sb.append(
                    createTelegramResoverRow(slaveACKPos, 1, dataLen, hex(edata[slaveACKPos]) + " Slave ACK"));
            // SYN

        } else if (isBroadcast) {
            // SYN

        } else if (isMasterSlave) {

            int slaveDataLenPos = slaveACKPos + 1;
            int slaveDataLen = edata[slaveDataLenPos];

            int slaveDataPos = slaveDataLenPos + 1;
            int slaveCRCPos = slaveDataPos + slaveDataLen;

            int masterACKPos = slaveCRCPos + 1;

            byte[] slaveData = Arrays.copyOfRange(edata, slaveDataPos, slaveDataPos + slaveDataLen);

            sb.append(createTelegramResoverRow(slaveACKPos, 1, dataLen,
                    String.format(FORMAT, "Slave ACK", "", hex(edata[slaveACKPos]))));

            sb.append(createTelegramResoverRow(slaveDataLenPos, 1, dataLen, String.format(FORMAT,
                    "Slave Data Length", "Length: " + edata[slaveDataLenPos], hex(edata[slaveDataLenPos]))));

            sb.append(createTelegramResoverRow(slaveDataPos, slaveDataLen, dataLen,
                    String.format(FORMAT, "Slave Data", "", hex(slaveData))));

            sb.append(createTelegramResoverRow(slaveCRCPos, 1, dataLen,
                    String.format(FORMAT, "Slave CRC", "", hex(edata[slaveCRCPos]))));

            sb.append(createTelegramResoverRow(masterACKPos, 1, dataLen,
                    String.format(FORMAT, "Master ACK", "", hex(edata[masterACKPos]))));

        }

        List<IEBusCommandMethod> methods = registry.find(edata);

        sb.append("\n");
        sb.append("Resolve the telegram\n");
        sb.append("********************\n");
        sb.append("\n");
        sb.append(String.format("Found %s command method(s) for this telegram.\n", methods.size()));
        sb.append("\n");

        for (IEBusCommandMethod method : methods) {
            try {
                Map<String, Object> result = EBusCommandUtils.decodeTelegram(method, data);

                sb.append(String.format("Values from command '%s' with method '%s' from collection '%s'\n",
                        method.getParent().getId(), method.getMethod(),
                        method.getParent().getParentCollection().getId()));

                for (Entry<String, Object> entry : result.entrySet()) {
                    Object value = entry.getValue();

                    if (value instanceof byte[]) {
                        value = EBusUtils.toHexDumpString((byte[]) value);
                    }

                    sb.append(String.format("  %-20s = %s\n", entry.getKey(),
                            value != null ? value.toString() : "NULL"));
                }

            } catch (EBusTypeException e) {
                logger.error("error!", e);
            }
        }
        sb.append("\n");
    } catch (Exception e) {
        logger.error("error!", e);
    }

    return sb.toString();

}

From source file:cpcc.ros.services.RosImageConverterTest.java

@Test
public void shouldReturnAnEmptyImageForACorruptedPNG() throws IOException {
    int height = 90;
    int width = 120;
    String encoding = "PNG";
    String imageName = "data/test-image.png";

    InputStream stream = RosImageConverterTest.class.getResourceAsStream(imageName);
    byte[] saneImageData = IOUtils.toByteArray(stream);
    byte[] imageData = Arrays.copyOfRange(saneImageData, 0, saneImageData.length - 100);

    when(buffer.array()).thenReturn(imageData);

    when(message.getEncoding()).thenReturn(encoding);
    when(message.getHeight()).thenReturn(height);
    when(message.getWidth()).thenReturn(width);
    when(message.getData()).thenReturn(ChannelBuffers.copiedBuffer(ByteOrder.nativeOrder(), imageData));

    BufferedImage result = conv.messageToBufferedImage(message);
    assertThat(result).isNotNull();//from   w  ww .jav  a 2 s  .  c  o m

    assertThat(result.getHeight()).isEqualTo(height);
    assertThat(result.getWidth()).isEqualTo(width);

    assertThatImageIsEmpty(result);
}

From source file:com.cloudera.sqoop.Sqoop.java

/**
 * SqoopTools sometimes pass arguments to a child program (e.g., mysqldump).
 * Users can specify additional args to these programs by preceeding the
 * additional arguments with a standalone '--'; but
 * ToolRunner/GenericOptionsParser will cull out this argument. We remove
 * the child-program arguments in advance, and store them to be readded
 * later.//from   www  . j a va2s  .  c  o m
 * @param argv the argv in to the SqoopTool
 * @return the argv with a "--" and any subsequent arguments removed.
 */
private String[] stashChildPrgmArgs(String[] argv) {
    for (int i = 0; i < argv.length; i++) {
        if ("--".equals(argv[i])) {
            this.childPrgmArgs = Arrays.copyOfRange(argv, i, argv.length);
            return Arrays.copyOfRange(argv, 0, i);
        }
    }

    // Didn't find child-program arguments.
    return argv;
}

From source file:com.itemanalysis.jmetrik.stats.irt.linking.CommonItemSummaryStatistics.java

private void createArrays() {
    xAMean = new Mean();
    yAMean = new Mean();
    xBMean = new Mean();
    yBMean = new Mean();
    xCMean = new Mean();
    yCMean = new Mean();

    xASd = new StandardDeviation();
    yASd = new StandardDeviation();
    xBSd = new StandardDeviation();
    yBSd = new StandardDeviation();
    xCSd = new StandardDeviation();
    yCSd = new StandardDeviation();

    int xBinary = 0;
    int xPolytomous = 0;
    int xTotalSteps = 0;
    ItemResponseModel irm;//w  w  w  .java 2 s .c om
    for (String s : irmX.keySet()) {
        irm = irmX.get(s);
        if (irm.getNcat() == 2) {
            xBinary++;
        } else {
            xPolytomous++;
        }
        xTotalSteps += (irm.getNcat() - 1);
    }

    aX = new double[xBinary + xPolytomous];
    bX = new double[xTotalSteps];
    cX = new double[xBinary];

    int yBinary = 0;
    int yPolytomous = 0;
    int yTotalSteps = 0;
    for (String s : irmY.keySet()) {
        irm = irmY.get(s);
        if (irm.getNcat() == 2) {
            yBinary++;
        } else {
            yPolytomous++;
        }
        yTotalSteps += (irm.getNcat() - 1);
    }

    aY = new double[yBinary + yPolytomous];
    bY = new double[yTotalSteps];
    cY = new double[yBinary];

    //populate arrays for Form X
    int itemIndex = 0;
    int binaryIndex = 0;
    int polyIndex = 0;
    int ncat = 0;
    for (String s : irmX.keySet()) {
        irm = irmX.get(s);
        ncat = irm.getNcat();

        varNamesA.add(new VariableName(s));

        aX[itemIndex] = irm.getDiscrimination();
        xAMean.increment(aX[itemIndex]);
        xASd.increment(aX[itemIndex]);

        if (ncat == 2) {
            cX[binaryIndex] = irm.getGuessing();
            xCMean.increment(cX[binaryIndex]);
            xCSd.increment(cX[binaryIndex]);

            bX[polyIndex] = irm.getDifficulty();
            xBMean.increment(bX[polyIndex]);
            xBSd.increment(bX[polyIndex]);

            binaryIndex++;
            polyIndex++;
            varNamesB.add(new VariableName(s));
        } else {
            double[] steps;
            if (irm.getType() == IrmType.GPCM || irm.getType() == IrmType.PCM2) {
                steps = irm.getStepParameters();
                steps = Arrays.copyOfRange(steps, 1, steps.length);//Omit first step since it is zero.
            } else {
                steps = irm.getStepParameters();
            }

            for (int k = 0; k < steps.length; k++) {
                bX[polyIndex] = steps[k];
                xBMean.increment(bX[polyIndex]);
                xBSd.increment(bX[polyIndex]);

                polyIndex++;
                varNamesB.add(new VariableName(s + "_" + (k + 1)));
            }
        }
        itemIndex++;

    } //end loop over items

    //populate arrays for Form Y
    itemIndex = 0;
    binaryIndex = 0;
    polyIndex = 0;
    ncat = 0;
    for (String s : irmY.keySet()) {
        irm = irmY.get(s);
        ncat = irm.getNcat();

        aY[itemIndex] = irm.getDiscrimination();
        yAMean.increment(aY[itemIndex]);
        yASd.increment(aY[itemIndex]);

        if (ncat == 2) {
            cY[binaryIndex] = irm.getGuessing();
            yCMean.increment(cY[binaryIndex]);
            yCSd.increment(cY[binaryIndex]);

            bY[polyIndex] = irm.getDifficulty();
            yBMean.increment(bY[polyIndex]);
            yBSd.increment(bY[polyIndex]);

            binaryIndex++;
            polyIndex++;
        } else {
            double[] steps;
            if (irm.getType() == IrmType.GPCM || irm.getType() == IrmType.PCM2) {
                steps = irm.getStepParameters();
                steps = Arrays.copyOfRange(steps, 1, steps.length);//Omit first step since it is zero.
            } else {
                steps = irm.getStepParameters();
            }

            for (int k = 0; k < steps.length; k++) {
                bY[polyIndex] = steps[k];
                yBMean.increment(bY[polyIndex]);
                yBSd.increment(bY[polyIndex]);

                polyIndex++;
            }
        }
        itemIndex++;

    } //end loop over items

}

From source file:com.platform.middlewares.HTTPFileMiddleware.java

private boolean handlePartialRequest(org.eclipse.jetty.server.Request request, HttpServletResponse response,
        File file) {//  ww  w  .  ja v  a2s .co  m
    try {
        String rangeHeader = request.getHeader("range");
        String rangeValue = rangeHeader.trim().substring("bytes=".length());
        int fileLength = (int) file.length();
        int start, end;
        if (rangeValue.startsWith("-")) {
            end = fileLength - 1;
            start = fileLength - 1 - Integer.parseInt(rangeValue.substring("-".length()));
        } else {
            String[] range = rangeValue.split("-");
            start = Integer.parseInt(range[0]);
            end = range.length > 1 ? Integer.parseInt(range[1]) : fileLength - 1;
        }
        if (end > fileLength - 1) {
            end = fileLength - 1;
        }
        if (start <= end) {
            int contentLength = end - start + 1;
            response.setHeader("Content-Length", contentLength + "");
            response.setHeader("Content-Range", "bytes " + start + "-" + end + "/" + fileLength);
            byte[] respBody = Arrays.copyOfRange(FileUtils.readFileToByteArray(file), start, contentLength);
            return BRHTTPHelper.handleSuccess(206, respBody, request, response, detectContentType(file));
        }
    } catch (Exception e) {
        e.printStackTrace();
        try {
            request.setHandled(true);
            response.getWriter().write("Invalid Range Header");
            response.sendError(400, "Bad Request");
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        return true;
    }
    return BRHTTPHelper.handleError(500, "unknown error", request, response);
}

From source file:mongrel2.Request.java

protected void parse(final byte[] raw) {

    // Mongrel2 sends requests formatted as follows:
    // UUID ID PATH SIZE:HEADERS,SIZE:BODY,

    try {//  w w  w  .  jav a  2 s . com
        System.out.write(raw);
        System.out.println();
    } catch (final Exception x) {
        // ignore
    }

    int p0 = -1;
    int p1 = -1;
    int length = 0;

    // sender addr
    p1 = findNextDelimiter(raw, p0, ' ');
    setSenderAddr(new String(raw, p0 + 1, p1 - p0 - 1, ASCII));

    // request-id
    p0 = p1;
    p1 = findNextDelimiter(raw, p0, ' ');
    setRequestId(new String(raw, p0 + 1, p1 - p0 - 1, ASCII));

    // matching path
    p0 = p1;
    p1 = findNextDelimiter(raw, p0, ' ');
    // ignore: matching path is the whole path,
    // not the handler path definied in the mongrel2 config

    // headers
    p0 = p1;
    p1 = findNextDelimiter(raw, p0, ':');
    length = Integer.parseInt(new String(raw, p0 + 1, p1 - p0 - 1));
    final String jsonHeaders = new String(raw, p1 + 1, length, UTF8);
    try {
        final JSONObject headers = new JSONObject(jsonHeaders);
        @SuppressWarnings("unchecked")
        final Iterator<String> i = headers.keys();
        while (i.hasNext()) {
            final String key = i.next();
            final String value = headers.getString(key);
            // System.out.printf("%s: %s%n", key, value);
            addHeader(key, value);
        }
    } catch (final JSONException x) {
        throw new RuntimeException("Cannot parse Json headers: " + jsonHeaders);
    }

    // content
    p0 = p1 + length + 1;
    p1 = findNextDelimiter(raw, p0, ':');
    length = Integer.parseInt(new String(raw, p0 + 1, p1 - p0 - 1));
    setContent(Arrays.copyOfRange(raw, p1 + 1, p1 + 1 + length));

}

From source file:model.PayloadSegment.java

/**
 * This method parses the bytes of an encapsulated file from least to first
 * for the least payload section of the file. Beware that the parentCarrier
 * can contain additional payload sections!
 * /*from   w w w.j  a  v  a  2 s.com*/
 * This method will return null, if no payload sections are left and
 * otherwise a {@link PayloadSegment} class which contains the restored
 * payload and the restoration metadata.
 * 
 * @param encapsulatedBytes
 * 
 * @return PayloadSegment class, or null if no payload section available
 */
public static PayloadSegment getPayloadSegment(byte[] encapsulatedBytes) {
    try {
        byte[] payloadSection = null;
        int endIndex = -1;
        for (int index = encapsulatedBytes.length - 1; index >= 0; index--) {
            if (PayloadSequences.isEndSequence(encapsulatedBytes, index)) {
                endIndex = index; // first byte of end sequence
            } else if (PayloadSequences.isStartSequence(encapsulatedBytes, index)) {
                if (endIndex == -1) {
                    return null;
                }
                // The payload section bytes are after the start sequence
                // and before the end sequence:
                payloadSection = Arrays.copyOfRange(encapsulatedBytes, index + START_SEQ.length, endIndex);
                break;
            }
        }
        if (payloadSection == null) {
            // no payload section in file.
            return null;
        }
        // Now get the restoration metadata bytes out of the payload section
        // bytes:
        byte[] restorationMetadataBytes = null;
        byte[] payloadBytes = null;
        for (int index = 0; index < payloadSection.length - 1; index++) {
            if (PayloadSequences.isEndHeader(payloadSection, index)) {
                restorationMetadataBytes = Arrays.copyOfRange(payloadSection, 0, index - 1);
                payloadBytes = Arrays.copyOfRange(payloadSection, index + END_HEADER_SEQ.length,
                        payloadSection.length);
            }
        }
        Properties properties = new Properties();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(restorationMetadataBytes);
        properties.load(inputStream);
        return new PayloadSegment(payloadBytes, properties);
    } catch (IOException e) {
    }
    return null;
}

From source file:com.titankingdoms.dev.titanchat.TitanChat.java

@Override
public boolean onCommand(CommandSender sender, org.bukkit.command.Command cmd, String lbl, String[] args) {
    if (sender == null || cmd == null || lbl == null || args == null)
        return false;

    if (cmd.getName().equals("titanchat")) {
        db.debug(Level.INFO, "Command by " + sender.getName() + ":");
        db.debug(Level.INFO, lbl + " " + StringUtils.join(args, " "));

        if (args.length < 1) {
            Messaging.sendMessage(sender, "&5You are running &6" + this);
            Messaging.sendMessage(sender, "&6\"/titanchat help [topic/page]\" for help");
            return true;
        }/*from   w w w.  ja  v  a  2s.  co  m*/

        String cmdName = args[0];
        args = Arrays.copyOfRange(args, 1, args.length);

        List<String> arguments = new ArrayList<String>();

        Matcher match = Pattern.compile("([^\"]\\S*|\".+?\")\\s*").matcher(StringUtils.join(args, " "));

        while (match.find())
            arguments.add(match.group().replace("\"", ""));

        args = arguments.toArray(new String[0]);

        db.debug(Level.INFO, "Command: " + cmdName);
        db.debug(Level.INFO, "Arguments:" + ((args != null) ? " " + StringUtils.join(args, ", ") : ""));

        onCommand(sender, cmdName, args);
        return true;

    } else if (cmd.getName().equalsIgnoreCase("chat")) {
        onCommand(sender, "chat", args);
        return true;

    } else if (cmd.getName().equalsIgnoreCase("pm")) {
        onCommand(sender, "pm", args);
        return true;
    }

    return false;
}

From source file:cn.edu.suda.core.stats.StatsUtils.java

public static StringMatrix pearsonCor(DataMatrix nm1, DataMatrix nm2, int m, int n, double r) {
    List<String> result = new ArrayList<>();
    for (int i = 0; i < nm1.getDrow(); i++) {
        for (int j = 0; j < nm2.getDrow(); j++) {
            double[] a1 = Arrays.copyOfRange(nm1.getRow(i), 0, m);
            double[] a2 = Arrays.copyOfRange(nm2.getRow(j), 0, n);
            PairedData pd = new PairedData(a1, a2);
            double cor = new PearsonCorrelation(pd).getR();
            if (cor <= r) {
                result.add(nm1.getRowname(i) + "\t" + nm2.getRowname(j) + "\t" + cor);
            }//from w w  w . jav  a 2 s  . co  m
        }
    }

    StringMatrix out = new StringMatrix(result.size(), 3);
    for (int i = 0; i < result.size(); i++) {
        String[] s = result.get(i).split("\t");
        for (int j = 0; j < s.length; j++) {
            out.setValue(i, j, s[j]);
        }
    }
    return out;
}