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:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.handlers.impl.PacketHandlerImpl.java

@Override
@Transactional/*from  www  .j  a  v a2 s  . c  o  m*/
public boolean processPacket(RelayServer relayServer, DatagramPacket packet) {
    try {
        this.txChecker.checkInTx("PacketHandler::processPacket");
    } catch (Throwable e) {
        e.printStackTrace();
    }

    long utcTimestamp = System.currentTimeMillis();
    boolean updated = false;

    if (this.logger.isDebugEnabled()) {
        this.logger.debug("[" + utcTimestamp + "] Received " + packet.getLength() + " bytes from "
                + packet.getAddress().getHostAddress() + ":" + packet.getPort());
    }

    try {
        InetAddress srcIp = packet.getAddress();
        int srcPort = packet.getPort();

        /* get sender or create */
        Sender sender = this.senders.getSender(srcIp, srcPort);
        if (sender == null) {
            sender = new Sender(srcIp, Integer.valueOf(srcPort), relayServer);
        }

        /* make sure the sender is linked to this relayServer */
        sender.setRelayServer(relayServer);

        /* get packet data */
        byte[] packetData = packet.getData();
        int packetLength = packet.getLength();

        /* parse the uplink packet for messages */
        int messageOffset = 0;
        while (messageOffset < packetLength) {
            int messageType = UplinkMessage.getUplinkMessageType(packetData, messageOffset);
            int messageLength = UplinkMessage.getUplinkMessageHeaderLength()
                    + UplinkMessage.getUplinkMessageLength(packetData, messageOffset);

            if ((messageType != UplinkMessage.getUplinkMessageTypePosition())
                    && (messageType != UplinkMessage.getUplinkMessageTypeClusterLeader())) {
                this.logger.warn("Uplink message type " + messageType + " not supported: ignored");
            } else {
                byte[] messageData = Arrays.copyOfRange(packetData, messageOffset,
                        messageOffset + messageLength);
                DumpUtil.dumpUplinkMessage(this.logger, Level.DEBUG, messageData, srcIp, srcPort, messageType,
                        utcTimestamp, "  ");

                Object msg = null;
                boolean msgCausedUpdate = false;
                if (messageType == UplinkMessage.getUplinkMessageTypePosition()) {
                    msg = new PositionUpdate(messageData, messageLength);
                    msgCausedUpdate = this.positionUpdateHandler.handlePositionMessage(sender, utcTimestamp,
                            (PositionUpdate) msg);
                } else /* if (messageType == UplinkMessage.getUplinkMessageTypeClusterLeader()) */ {
                    msg = new ClusterLeader(messageData, messageLength);
                    msgCausedUpdate = this.clusterLeaderHandler.handleClusterLeaderMessage(sender, utcTimestamp,
                            (ClusterLeader) msg);
                }
                if (msgCausedUpdate && this.useFaker) {
                    this.faker.fakeit(sender, utcTimestamp, msg);
                }
                updated = msgCausedUpdate || updated;
            }

            messageOffset += messageLength;
        }

        return updated;
    } catch (Throwable e) {
        this.logger.error("error during packet handling", e);
        return updated;
    } finally {
        if (this.useFaker) {
            this.faker.setFirstFake(false);
        }
    }
}

From source file:com.asakusafw.runtime.io.text.directio.AbstractTextStreamFormatTest.java

/**
 * input - w/ splitter./*from   w w w.j  a  v  a  2 s  .  co  m*/
 * @throws Exception if failed
 */
@Test
public void input_splitter_trim_around() throws Exception {
    MockFormat format = format(3).withInputSplitter(InputSplitters.byLineFeed());
    String[][] data = { { "A", "B", "C", }, { "D", "E", "F", }, { "G", "H", "I", }, };
    try (ModelInput<String[]> in = format.createInput(String[].class, "dummy", input(data), 1, 6)) {
        String[][] result = collect(3, in);
        assertThat(result, is(Arrays.copyOfRange(data, 1, 2)));
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.jazzy.CorrectionsContextualizer.java

protected double getSentenceProbability(List<String> words) throws AnalysisEngineProcessException {
    double sentenceProbability = 0.0;

    if (words.size() < 1) {
        return 0.0;
    }/*from   w ww . j  a  v a  2s .c om*/

    long nrOfUnigrams;
    try {
        nrOfUnigrams = provider.getNrOfTokens();
    } catch (Exception e) {
        throw new AnalysisEngineProcessException(e);
    }

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

    // in the google n-grams this is not represented (only single BOS markers)
    // but I leave it in place in case we add another n-gram provider
    trigrams.add(getTrigram(BOS, BOS, words.get(0)));

    if (words.size() > 1) {
        trigrams.add(getTrigram(BOS, words.get(0), words.get(1)));
    }

    for (String trigram : new NGramStringIterable(words, 3, 3)) {
        trigrams.add(trigram);
    }

    // FIXME - implement backoff or linear interpolation

    for (String trigram : trigrams) {
        long trigramFreq = getNGramCount(trigram);

        String[] parts = StringUtils.split(trigram, " ");

        String bigram = StringUtils.join(Arrays.copyOfRange(parts, 0, 2), " ");
        long bigramFreq = getNGramCount(bigram);

        String unigram = StringUtils.join(Arrays.copyOfRange(parts, 0, 1), " ");
        long unigramFreq = getNGramCount(unigram);

        if (trigramFreq < 1) {
            trigramFreq = 1;
        }
        if (bigramFreq < 1) {
            bigramFreq = 1;
        }
        if (unigramFreq < 1) {
            unigramFreq = 1;
        }

        double trigramProb = Math.log((double) trigramFreq / bigramFreq);
        double bigramProb = Math.log((double) bigramFreq / unigramFreq);
        double unigramProb = Math.log((double) unigramFreq / nrOfUnigrams);

        double interpolated = (trigramProb + bigramProb + unigramProb) / 3.0;

        sentenceProbability += interpolated;
    }

    return Math.exp(sentenceProbability);
}

From source file:net.centro.rtb.monitoringcenter.MetricCollectorImpl.java

@Override
public void registerMetricSet(MetricSet metricSet, String... names) {
    Preconditions.checkNotNull(metricSet, "metricSet cannot be null");

    String namespace = null;//w  w w . ja v a2 s . c o m
    if (names != null && names.length > 0) {
        namespace = buildFullName(names[0], Arrays.copyOfRange(names, 1, names.length), null);
    }

    registerMetricSetImpl(metricSet, namespace);
}

From source file:co.rsk.asm.EVMDissasembler.java

void printPush(OpCode op) {
    sb.append(' ').append(op.name()).append(' ');
    int nPush = op.val() - OpCode.PUSH1.val() + 1;
    String name = null;//from w ww  .  j a v  a 2s .  co  m
    if ((block != null) && (helper != null) && (nPush == 4)) { // optimization, only find int32 label refs
        int labelId = block.getTagIdByPos(pc + 1, tagIterator);
        if (labelId >= 0) {
            name = getVisualLabelName(labelId);
            sb.append(name);
            if (printOffsets)
                sb.append(" ;");
        }
    }

    if ((printOffsets) || (name == null)) {
        byte[] data = Arrays.copyOfRange(code, pc + 1, pc + nPush + 1);
        BigInteger bi = new BigInteger(1, data);
        sb.append("0x").append(bi.toString(16));
        if (bi.bitLength() <= 32) {
            sb.append(" (").append(new BigInteger(1, data).toString()).append(") ");
        }
    }
}

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

@Override
public void uploadCertificates(String port, List<String> websites) throws Exception {
    FlasherSerialClient client = null;/*from   w  ww  .  j  a va 2  s . c o m*/
    try {
        progress(10, "Connecting to programmer...");
        client = new FlasherSerialClient();
        client.open(port, this.baudrate);
        client.hello();
        int maxPayload = client.getMaximumPayload();

        progress(20, "Reading section header");
        byte[] startPattern = client.readFlash(0x00004000, 16);

        WiFi101CertificateBundle certBundle = createBundleFromWebsites(websites);

        byte[] certData;

        if (Arrays.equals(WiFi101CertificateBundle.START_PATTERN_V0, startPattern)) {
            certData = certBundle.getEncodedV0();
        } else if (Arrays.equals(WiFi101CertificateBundle.START_PATTERN_V1, startPattern)) {
            certData = certBundle.getEncodedV1();
        } else {
            throw new Exception("Unknown starting pattern, please reflash firmware!");
        }

        int size = certData.length;
        int address = 0x00004000;
        int written = 0;

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

        while (written < size) {
            progress(60 + written * 80 / size, "Programming...");
            int len = maxPayload;
            if (written + len > size) {
                len = size - written;
            }
            client.writeFlash(address, Arrays.copyOfRange(certData, written, written + len));
            written += len;
            address += len;
        }
        progress(100, "Done!");
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:net.devietti.ArchConfMapServlet.java

/** Fetch info for all tracked conferences from WikiCFP */
private void getconfs(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // pull conference info from WikiCFP
    List<Conf> confs = new LinkedList<Conf>();

    // NB: WikiCFP's search only recognizes the first 8 terms, so we have multiple
    // *serialized* requests :-(
    final int BATCH_SIZE = 8;
    for (int i = 0; i < CONFERENCE_NAMES.length; i += BATCH_SIZE) {
        String[] slice = Arrays.copyOfRange(CONFERENCE_NAMES, i,
                Math.min(i + BATCH_SIZE, CONFERENCE_NAMES.length));
        confs.addAll(getConfInfo(Arrays.asList(slice)));
    }//w w  w  .ja v  a  2 s.  c  om

    // sort conferences by start date
    Collections.sort(confs);

    List<Conf> toRemove = new LinkedList<Conf>();
    for (Conf c : confs) {
        DateTime now = new DateTime();
        // conference is already over; don't display it
        if (c.end.isBefore(now)) {
            toRemove.add(c);
            continue;
        }

        c.deadlineStatus = "pre";
        if (c.deadline.isBefore(now)) {
            c.deadlineStatus = "post";
        }
    }
    confs.removeAll(toRemove);

    resp.setContentType("application/json");
    resp.getWriter().println(GSON.toJson(confs));
}

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

private void testRandomRead(long bucketKey, FileAccessFSImpl hfa, String fileName) throws IOException {
    FileAccess.FileReader in = hfa.getReader(bucketKey, fileName);
    Slice tkey = new Slice(null, 0, 0);
    Slice tval = new Slice(null, 0, 0);

    // seek to existing key k
    // seek() method should move to key[i] where key[i] = k
    // so next "next()" would return key[i] which is equal to k
    in.seek(new Slice(new byte[] { 1 }));
    assertTrue(in.next(tkey, tval));//  w w  w  .  ja va2  s.com
    assertEquals("Value is not as expected", values[1],
            new String(Arrays.copyOfRange(tval.buffer, tval.offset, tval.offset + tval.length)));

    // If seek to non-existing key k
    // seek() method should move to key[i] where key[i-1] < k and key[i] > k
    // so next "next()"  would return first key[i] which is greater than k
    assertFalse(in.seek(new Slice(new byte[] { 2 })));
    in.next(tkey, tval);
    assertEquals("Value is not as expected", values[2],
            new String(Arrays.copyOfRange(tval.buffer, tval.offset, tval.offset + tval.length)));
    in.close();
}

From source file:com.ibm.cics.ca1y.Util.java

/**
 * Return a string of hexadecimal of byteArray. If the length of byteArray
 * is greater than 16, return the first 8 bytes + "..." + the last 8 bytes.
 * //  ww w  .  j  a  v  a  2 s .  co  m
 * @param byteArray
 *            - byte array to use.
 * @return String of hexadecimal.
 */
public static String getHexSummary(byte[] byteArray) {
    if (byteArray == null) {
        return "";
    }

    if (byteArray.length <= 16) {
        return getHex(byteArray);
    }

    // H
    return getHex(Arrays.copyOfRange(byteArray, 0, 8)) + "..."
            + getHex(Arrays.copyOfRange(byteArray, byteArray.length - 8, byteArray.length));
}

From source file:eu.bittrade.libs.steemj.protocol.PublicKey.java

/**
 * Recreate the address from the public key.
 * /*from www  . ja  v a 2s .  c o m*/
 * @return The address.
 */
@JsonIgnore
public String getAddressFromPublicKey() {
    try {
        // Recreate the address from the public key.
        return this.prefix + Base58.encode(Bytes.concat(this.toByteArray(),
                Arrays.copyOfRange(calculateChecksum(this.toByteArray()), 0, CHECKSUM_BYTES)));
    } catch (SteemInvalidTransactionException | NullPointerException e) {
        LOGGER.debug("An error occured while generating an address from a public key.", e);
        return "";
    }
}