Example usage for java.lang Long toHexString

List of usage examples for java.lang Long toHexString

Introduction

In this page you can find the example usage for java.lang Long toHexString.

Prototype

public static String toHexString(long i) 

Source Link

Document

Returns a string representation of the long argument as an unsigned integer in base 16.

Usage

From source file:io.orchestrate.client.itest.KvTest.java

@Theory
public void conditionalPatchKeyAsync(@ForAll(sampleSize = 10) final String key) throws InterruptedException {
    assumeThat(key, not(isEmptyString()));

    final KvMetadata kvMetadata = insertItem(key, "{}");

    String name = Long.toHexString(RAND.nextLong());

    final BlockingQueue<KvMetadata> queue = DataStructures.getLTQInstance(KvMetadata.class);
    client.kv(collection(), key).ifMatch(kvMetadata.getRef())
            .patch(JsonPatch.builder().add("name", name).build()).on(new ResponseAdapter<KvMetadata>() {
                @Override//from ww  w .  j a  v a2s .  co m
                public void onFailure(final Throwable error) {
                    fail(error.getMessage());
                }

                @Override
                public void onSuccess(final KvMetadata object) {
                    queue.add(object);
                }
            });

    final KvMetadata patched = queue.poll(5000, TimeUnit.MILLISECONDS);

    assertNotEquals(kvMetadata, patched);

    final KvObject<ObjectNode> kvObject = client.kv(kvMetadata.getCollection(), kvMetadata.getKey())
            .get(ObjectNode.class).get();

    assertNotNull(kvMetadata);
    assertNotNull(kvObject);
    assertEquals(kvMetadata.getCollection(), kvObject.getCollection());
    assertEquals(kvMetadata.getKey(), kvObject.getKey());
    assertEquals(patched.getRef(), kvObject.getRef());
    assertEquals(name, kvObject.getValue().get("name").asText());
}

From source file:net.sf.extjwnl.princeton.file.PrincetonRandomAccessDictionaryFile.java

private String renderSynset(Synset synset) {
    int estLength = offsetLength + 1//offset
            + 2 + 1 //lexfilenum
            + 1//ss_type
            + offsetLength + 1//w_cnt
            + (10 + 3 + 1) * synset.getWords().size()//avg word 10 chars + lex_id max 3 chars
            + offsetLength + 1//p_cnt
            + (1 + 1 + offsetLength + 1 + 1 + 1 + 4 + 1) * synset.getPointers().size()
            + synset.getGloss().length() + 2 + 2;
    if (POS.VERB == synset.getPOS()) {
        estLength = estLength + 8 * synset.getWords().size();//8 for verb flag, about one per word
    }/*from  www  . j  a  v a2s  .  c  om*/

    //synset_offset  lex_filenum  ss_type  w_cnt  word  lex_id  [word  lex_id...]  p_cnt  [ptr...]  [frames...]  |   gloss
    //w_cnt Two digit hexadecimal integer indicating the number of words in the synset.
    String posKey = synset.getPOS().getKey();
    if (POS.ADJECTIVE == synset.getPOS() && synset.isAdjectiveCluster()) {
        posKey = POS.ADJECTIVE_SATELLITE_KEY;
    }
    if (checkLexFileNumber && log.isWarnEnabled()
            && !LexFileIdFileNameMap.getMap().containsKey(synset.getLexFileNum())) {
        log.warn(JWNL.resolveMessage("PRINCETON_WARN_001", synset.getLexFileNum()));
    }
    if (checkWordCountLimit && log.isWarnEnabled() && (0xFF < synset.getWords().size())) {
        log.warn(JWNL.resolveMessage("PRINCETON_WARN_004",
                new Object[] { synset.getOffset(), synset.getWords().size() }));
    }
    StringBuilder result = new StringBuilder(estLength);
    formatOffset(synset.getOffset(), offsetLength, result);
    if (synset.getLexFileNum() < 10) {
        result.append(" 0").append(synset.getLexFileNum());
    } else {
        result.append(" ").append(synset.getLexFileNum());
    }
    result.append(" ").append(posKey);
    if (synset.getWords().size() < 0x10) {
        result.append(" 0").append(Integer.toHexString(synset.getWords().size())).append(" ");
    } else {
        result.append(" ").append(Integer.toHexString(synset.getWords().size())).append(" ");
    }
    for (Word w : synset.getWords()) {
        //ASCII form of a word as entered in the synset by the lexicographer, with spaces replaced by underscore characters (_ ). The text of the word is case sensitive.
        //lex_id One digit hexadecimal integer that, when appended onto lemma , uniquely identifies a sense within a lexicographer file.
        String lemma = w.getLemma().replace(' ', '_');
        if (w instanceof Adjective) {
            Adjective a = (Adjective) w;
            if (AdjectivePosition.NONE != a.getAdjectivePosition()) {
                lemma = lemma + "(" + a.getAdjectivePosition().getKey() + ")";
            }
        }
        if (checkLexIdLimit && log.isWarnEnabled() && (0xF < w.getLexId())) {
            log.warn(JWNL.resolveMessage("PRINCETON_WARN_005",
                    new Object[] { synset.getOffset(), w.getLemma(), w.getLexId() }));
        }
        result.append(lemma).append(" ");
        result.append(Long.toHexString(w.getLexId())).append(" ");
    }
    //Three digit decimal integer indicating the number of pointers from this synset to other synsets. If p_cnt is 000 the synset has no pointers.
    if (checkRelationLimit && log.isWarnEnabled() && (999 < synset.getPointers().size())) {
        log.warn(JWNL.resolveMessage("PRINCETON_WARN_002",
                new Object[] { synset.getOffset(), synset.getPointers().size() }));
    }
    if (synset.getPointers().size() < 100) {
        result.append("0");
        if (synset.getPointers().size() < 10) {
            result.append("0");
        }
    }
    result.append(synset.getPointers().size()).append(" ");
    for (Pointer p : synset.getPointers()) {
        //pointer_symbol  synset_offset  pos  source/target
        result.append(p.getType().getKey()).append(" ");
        //synset_offset is the byte offset of the target synset in the data file corresponding to pos
        formatOffset(p.getTargetOffset(), offsetLength, result);
        result.append(" ");
        //pos
        result.append(p.getTargetPOS().getKey()).append(" ");
        //source/target
        //The source/target field distinguishes lexical and semantic pointers.
        // It is a four byte field, containing two two-digit hexadecimal integers.
        // The first two digits indicates the word number in the current (source) synset,
        // the last two digits indicate the word number in the target synset.
        // A value of 0000 means that pointer_symbol represents a semantic relation between the current (source) synset and the target synset indicated by synset_offset .

        //A lexical relation between two words in different synsets is represented by non-zero values in the source and target word numbers.
        // The first and last two bytes of this field indicate the word numbers in the source and target synsets, respectively, between which the relation holds.
        // Word numbers are assigned to the word fields in a synset, from left to right, beginning with 1 .
        if (checkPointerIndexLimit && log.isWarnEnabled() && (0xFF < p.getSourceIndex())) {
            log.warn(JWNL.resolveMessage("PRINCETON_WARN_006", new Object[] { synset.getOffset(),
                    p.getSource().getSynset().getOffset(), p.getSourceIndex() }));
        }
        if (checkPointerIndexLimit && log.isWarnEnabled() && (0xFF < p.getTargetIndex())) {
            log.warn(JWNL.resolveMessage("PRINCETON_WARN_006", new Object[] { synset.getOffset(),
                    p.getTarget().getSynset().getOffset(), p.getTargetIndex() }));
        }
        if (p.getSourceIndex() < 0x10) {
            result.append("0");
        }
        result.append(Integer.toHexString(p.getSourceIndex()));
        if (p.getTargetIndex() < 0x10) {
            result.append("0");
        }
        result.append(Integer.toHexString(p.getTargetIndex())).append(" ");
    }

    //frames In data.verb only
    if (POS.VERB == synset.getPOS()) {
        BitSet verbFrames = synset.getVerbFrameFlags();
        int verbFramesCount = verbFrames.cardinality();
        for (Word word : synset.getWords()) {
            if (word instanceof Verb) {
                BitSet bits = ((Verb) word).getVerbFrameFlags();
                for (int i = bits.nextSetBit(0); i >= 0; i = bits.nextSetBit(i + 1)) {
                    //WN TRICK - there are duplicates in data
                    //02593551 41 v 04 lord_it_over 0 queen_it_over 0 put_on_airs 0 act_superior 0 001 @ 02367363 v 0000
                    // 09 + 02 00 + 02 04 + 22 04 + 02 03 + 22 03 + 08 02 + 09 02 + 08 01 + 09 01 | act like the master of; "He is lording it over the students"
                    // + 02 04 and + 02 03 duplicate + 02 00
                    // it is the only one, but it causes offsets to differ on WN30 rewrite
                    if (!verbFrames.get(i)) {
                        verbFramesCount++;
                    }
                }
            }
        }
        if (checkVerbFrameLimit && log.isWarnEnabled() && (99 < verbFramesCount)) {
            log.warn(JWNL.resolveMessage("PRINCETON_WARN_007",
                    new Object[] { synset.getOffset(), verbFramesCount }));
        }
        if (verbFramesCount < 10) {
            result.append("0");
        }
        result.append(Integer.toString(verbFramesCount)).append(" ");
        for (int i = verbFrames.nextSetBit(0); i >= 0; i = verbFrames.nextSetBit(i + 1)) {
            if (checkVerbFrameLimit && log.isWarnEnabled() && (99 < i)) {
                log.warn(JWNL.resolveMessage("PRINCETON_WARN_008", new Object[] { synset.getOffset(), i }));
            }
            result.append("+ ");
            if (i < 10) {
                result.append("0");
            }
            result.append(Integer.toString(i));
            result.append(" 00 ");
        }
        for (Word word : synset.getWords()) {
            if (word instanceof Verb) {
                BitSet bits = ((Verb) word).getVerbFrameFlags();
                for (int i = bits.nextSetBit(0); i >= 0; i = bits.nextSetBit(i + 1)) {
                    if (!verbFrames.get(i)) {
                        if (checkVerbFrameLimit && log.isWarnEnabled() && (0xFF < word.getIndex())) {
                            log.warn(JWNL.resolveMessage("PRINCETON_WARN_008",
                                    new Object[] { synset.getOffset(), word.getIndex() }));
                        }
                        result.append("+ ");
                        if (i < 10) {
                            result.append("0");
                        }
                        result.append(Integer.toString(i)).append(" ");
                        if (word.getIndex() < 0x10) {
                            result.append("0");
                        }
                        result.append(Integer.toHexString(word.getIndex())).append(" ");
                    }
                }
            }
        }
    }

    result.append("| ").append(synset.getGloss()).append("  ");//why every line in most WN files ends with two spaces?

    return result.toString();
}

From source file:org.voltdb.regressionsuites.TestInsertIntoSelectSuite.java

public void testSelectWithAggregation() throws Exception {
    final Client client = getClient();
    final long partitioningValue = 7;

    initializeTables(client);/*from  ww w .  ja v a2  s .c  o  m*/

    ClientResponse resp = client.callProcedure("insert_p_source_p_agg", partitioningValue);
    assertEquals(ClientResponse.SUCCESS, resp.getStatus());
    validateTableOfScalarLongs(resp.getResults()[0], new long[] { 1 });

    resp = client.callProcedure("@AdHoc", "select * from target_p order by bi");
    assertEquals(ClientResponse.SUCCESS, resp.getStatus());
    VoltTable targetRows = resp.getResults()[0];

    assertTrue(targetRows.advanceRow());

    assertEquals(partitioningValue, targetRows.getLong(0));
    assertEquals(Long.toHexString(-partitioningValue), targetRows.getString(1));
    assertEquals(partitioningValue * 11, targetRows.getLong(2));
    assertEquals(partitioningValue * -11, targetRows.getLong(3));

    assertFalse(targetRows.advanceRow());
}

From source file:io.warp10.standalone.StandaloneIngressHandler.java

/**
 * Handle Metadata updating//w ww. j a v a 2s  . c  o  m
 */
public void handleMeta(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    if (target.equals(Constants.API_ENDPOINT_META)) {
        baseRequest.setHandled(true);
    } else {
        return;
    }

    try {
        //
        // CORS header
        //

        response.setHeader("Access-Control-Allow-Origin", "*");

        //
        // Extract DatalogRequest if specified
        //

        String datalogHeader = request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_DATALOG));

        DatalogRequest dr = null;

        boolean forwarded = false;

        if (null != datalogHeader) {
            byte[] bytes = OrderPreservingBase64.decode(datalogHeader.getBytes(Charsets.US_ASCII));

            if (null != datalogPSK) {
                bytes = CryptoUtils.unwrap(datalogPSK, bytes);
            }

            if (null == bytes) {
                throw new IOException("Invalid Datalog header.");
            }

            TDeserializer deser = new TDeserializer(new TCompactProtocol.Factory());

            try {
                dr = new DatalogRequest();
                deser.deserialize(dr, bytes);
            } catch (TException te) {
                throw new IOException();
            }

            Map<String, String> labels = new HashMap<String, String>();
            labels.put(SensisionConstants.SENSISION_LABEL_ID, new String(
                    OrderPreservingBase64.decode(dr.getId().getBytes(Charsets.US_ASCII)), Charsets.UTF_8));
            labels.put(SensisionConstants.SENSISION_LABEL_TYPE, dr.getType());
            Sensision.update(SensisionConstants.CLASS_WARP_DATALOG_REQUESTS_RECEIVED, labels, 1);

            forwarded = true;
        }

        //
        // Loop over the input lines.
        // Each has the following format:
        //
        // class{labels}{attributes}
        //

        String token = null != dr ? dr.getToken()
                : request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_TOKENX));

        WriteToken wtoken;

        try {
            wtoken = Tokens.extractWriteToken(token);
        } catch (WarpScriptException ee) {
            throw new IOException(ee);
        }

        String application = wtoken.getAppName();
        String producer = Tokens.getUUID(wtoken.getProducerId());
        String owner = Tokens.getUUID(wtoken.getOwnerId());

        if (null == producer || null == owner) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid token.");
            return;
        }

        //
        // Determine if content if gzipped
        //

        boolean gzipped = false;

        if (null != request.getHeader("Content-Type")
                && "application/gzip".equals(request.getHeader("Content-Type"))) {
            gzipped = true;
        }

        BufferedReader br = null;

        if (gzipped) {
            GZIPInputStream is = new GZIPInputStream(request.getInputStream());
            br = new BufferedReader(new InputStreamReader(is));
        } else {
            br = request.getReader();
        }

        File loggingFile = null;
        PrintWriter loggingWriter = null;

        //
        // Open the logging file if logging is enabled
        //

        if (null != loggingDir) {
            long nanos = null != dr ? dr.getTimestamp() : TimeSource.getNanoTime();
            StringBuilder sb = new StringBuilder();
            sb.append(Long.toHexString(nanos));
            sb.insert(0, "0000000000000000", 0, 16 - sb.length());
            sb.append("-");
            if (null != dr) {
                sb.append(dr.getId());
            } else {
                sb.append(datalogId);
            }

            sb.append("-");
            sb.append(dtf.print(nanos / 1000000L));
            sb.append(Long.toString(1000000L + (nanos % 1000000L)).substring(1));
            sb.append("Z");

            if (null == dr) {
                dr = new DatalogRequest();
                dr.setTimestamp(nanos);
                dr.setType(Constants.DATALOG_META);
                dr.setId(datalogId);
                dr.setToken(token);
            }

            if (null != dr && (!forwarded || (forwarded && this.logforwarded))) {
                //
                // Serialize the request
                //

                TSerializer ser = new TSerializer(new TCompactProtocol.Factory());

                byte[] encoded;

                try {
                    encoded = ser.serialize(dr);
                } catch (TException te) {
                    throw new IOException(te);
                }

                if (null != this.datalogPSK) {
                    encoded = CryptoUtils.wrap(this.datalogPSK, encoded);
                }

                encoded = OrderPreservingBase64.encode(encoded);

                loggingFile = new File(loggingDir, sb.toString());
                loggingWriter = new PrintWriter(new FileWriterWithEncoding(loggingFile, Charsets.UTF_8));

                //
                // Write request
                //

                loggingWriter.println(new String(encoded, Charsets.US_ASCII));
            }
        }

        try {
            //
            // Loop on all lines
            //

            while (true) {
                String line = br.readLine();

                if (null == line) {
                    break;
                }

                // Ignore blank lines
                if ("".equals(line)) {
                    continue;
                }

                // Ignore comments
                if ('#' == line.charAt(0)) {
                    continue;
                }

                Metadata metadata = MetadataUtils.parseMetadata(line);

                // Add labels from the WriteToken if they exist
                if (wtoken.getLabelsSize() > 0) {
                    metadata.getLabels().putAll(wtoken.getLabels());
                }
                //
                // Force owner/producer
                //

                metadata.getLabels().put(Constants.PRODUCER_LABEL, producer);
                metadata.getLabels().put(Constants.OWNER_LABEL, owner);

                if (null != application) {
                    metadata.getLabels().put(Constants.APPLICATION_LABEL, application);
                } else {
                    // remove application label
                    metadata.getLabels().remove(Constants.APPLICATION_LABEL);
                }

                if (!MetadataUtils.validateMetadata(metadata)) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid metadata " + line);
                    return;
                }

                metadata.setSource(Configuration.INGRESS_METADATA_UPDATE_ENDPOINT);
                this.directoryClient.register(metadata);

                //
                // Write the line last, so we do not write lines which triggered exceptions
                //

                if (null != loggingWriter) {
                    loggingWriter.println(line);
                }
            }
        } finally {
            if (null != loggingWriter) {
                Map<String, String> labels = new HashMap<String, String>();
                labels.put(SensisionConstants.SENSISION_LABEL_ID, new String(
                        OrderPreservingBase64.decode(dr.getId().getBytes(Charsets.US_ASCII)), Charsets.UTF_8));
                labels.put(SensisionConstants.SENSISION_LABEL_TYPE, dr.getType());
                Sensision.update(SensisionConstants.CLASS_WARP_DATALOG_REQUESTS_LOGGED, labels, 1);

                loggingWriter.close();
                loggingFile.renameTo(new File(loggingFile.getAbsolutePath() + DatalogForwarder.DATALOG_SUFFIX));
            }
        }

        response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        if (!response.isCommitted()) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            return;
        }
    }
}

From source file:io.orchestrate.client.itest.KvTest.java

@Theory
public void conditionalPatchKeyRefFailed(@ForAll(sampleSize = 10) final String key) {
    assumeThat(key, not(isEmptyString()));

    insertItem(key, "{}");

    String name = Long.toHexString(RAND.nextLong());

    ItemVersionMismatchException thrown = null;
    try {//from   w w  w. j  ava 2s.  co m
        final KvMetadata patched = client.kv(collection(), key).ifMatch("0000000000000000")
                .patch(JsonPatch.builder().add("name", name).build()).get();
        fail("Should have failed with a concurrency conflict.");
    } catch (ItemVersionMismatchException ex) {
        thrown = ex;
    }

    assertNotNull(thrown);
}

From source file:org.trafodion.dtm.TmAuditTlog.java

public static Put formatRecord(final long lvTransid, final TransactionState lvTx) throws Exception {
    if (LOG.isTraceEnabled())
        LOG.trace("formatRecord start");
    StringBuilder tableString = new StringBuilder();
    String transidString = new String(String.valueOf(lvTransid));
    String lvTxState;/*from   w  ww .j ava  2s  .  c  o  m*/
    Set<TransactionRegionLocation> regions = lvTx.getParticipatingRegions();
    Iterator<TransactionRegionLocation> it = regions.iterator();
    long lvAsn;
    long threadId = Thread.currentThread().getId();
    while (it.hasNext()) {
        String name = new String(it.next().getRegionInfo().getTable().getNameAsString());
        if (name.length() > 0) {
            tableString.append(",");
            tableString.append(name);
        }
    }
    if (LOG.isTraceEnabled())
        LOG.trace("formatRecord table names " + tableString.toString());
    Put p;

    //create our own hashed key
    long key = (((lvTransid & tLogHashKey) << tLogHashShiftFactor) + (lvTransid & 0xFFFFFFFF));
    if (LOG.isTraceEnabled())
        LOG.trace("key: " + key + " hex: " + Long.toHexString(key));
    p = new Put(Bytes.toBytes(key));
    lvAsn = asn.getAndIncrement();
    lvTxState = lvTx.getStatus();
    if (LOG.isTraceEnabled())
        LOG.trace("formatRecord transid: " + lvTransid + " state: " + lvTxState + " ASN: " + lvAsn);
    p.add(TLOG_FAMILY, ASN_STATE, Bytes
            .toBytes(String.valueOf(lvAsn) + "," + transidString + "," + lvTxState + tableString.toString()));

    if (LOG.isTraceEnabled())
        LOG.trace("formatRecord exit");
    return p;
}

From source file:org.apache.bookkeeper.bookie.LedgerStorageCheckpointTest.java

@Test
public void testCheckPointForEntryLoggerWithMultipleActiveEntryLogs() throws Exception {
    File tmpDir = createTempDir("DiskCheck", "test");

    final ServerConfiguration conf = TestBKConfiguration.newServerConfiguration()
            .setMetadataServiceUri(zkUtil.getMetadataServiceUri()).setZkTimeout(5000)
            .setJournalDirName(tmpDir.getPath()).setLedgerDirNames(new String[] { tmpDir.getPath() })
            .setAutoRecoveryDaemonEnabled(false).setFlushInterval(3000)
            .setBookiePort(PortManager.nextFreePort())
            // entrylog per ledger is enabled
            .setEntryLogPerLedgerEnabled(true)
            .setLedgerStorageClass(MockInterleavedLedgerStorage.class.getName());

    Assert.assertEquals("Number of JournalDirs", 1, conf.getJournalDirs().length);
    // we know there is only one ledgerDir
    File ledgerDir = Bookie.getCurrentDirectories(conf.getLedgerDirs())[0];
    BookieServer server = new BookieServer(conf);
    server.start();//from  www  .  j  a v a 2s .c o m
    ClientConfiguration clientConf = new ClientConfiguration();
    clientConf.setMetadataServiceUri(zkUtil.getMetadataServiceUri());
    final BookKeeper bkClient = new BookKeeper(clientConf);

    int numOfLedgers = 12;
    int numOfEntries = 100;
    byte[] dataBytes = "data".getBytes();
    AtomicBoolean receivedExceptionForAdd = new AtomicBoolean(false);
    LongStream.range(0, numOfLedgers).parallel().mapToObj((ledgerId) -> {
        LedgerHandle handle = null;
        try {
            handle = bkClient.createLedgerAdv(ledgerId, 1, 1, 1, DigestType.CRC32, "passwd".getBytes(), null);
        } catch (BKException | InterruptedException exc) {
            receivedExceptionForAdd.compareAndSet(false, true);
            LOG.error("Got Exception while trying to create LedgerHandle for ledgerId: " + ledgerId, exc);
        }
        return handle;
    }).forEach((writeHandle) -> {
        IntStream.range(0, numOfEntries).forEach((entryId) -> {
            try {
                writeHandle.addEntry(entryId, dataBytes);
            } catch (BKException | InterruptedException exc) {
                receivedExceptionForAdd.compareAndSet(false, true);
                LOG.error("Got Exception while trying to AddEntry of ledgerId: " + writeHandle.getId()
                        + " entryId: " + entryId, exc);
            }
        });
        try {
            writeHandle.close();
        } catch (BKException | InterruptedException e) {
            receivedExceptionForAdd.compareAndSet(false, true);
            LOG.error("Got Exception while trying to close writeHandle of ledgerId: " + writeHandle.getId(), e);
        }
    });

    Assert.assertFalse(
            "There shouldn't be any exceptions while creating writeHandle and adding entries to writeHandle",
            receivedExceptionForAdd.get());

    executorController.advance(Duration.ofMillis(conf.getFlushInterval()));
    // since we have waited for more than flushInterval SyncThread should have checkpointed.
    // if entrylogperledger is not enabled, then we checkpoint only when currentLog in EntryLogger
    // is rotated. but if entrylogperledger is enabled, then we checkpoint for every flushInterval period
    File lastMarkFile = new File(ledgerDir, "lastMark");
    Assert.assertTrue("lastMark file must be existing, because checkpoint should have happened",
            lastMarkFile.exists());
    LogMark rolledLogMark = readLastMarkFile(lastMarkFile);
    Assert.assertNotEquals("rolledLogMark should not be zero, since checkpoint has happenend", 0,
            rolledLogMark.compare(new LogMark()));

    bkClient.close();
    // here we are calling shutdown, but MockInterleavedLedgerStorage shudown/flush
    // methods are noop, so entrylogger is not flushed as part of this shutdown
    // here we are trying to simulate Bookie crash, but there is no way to
    // simulate bookie abrupt crash
    server.shutdown();

    // delete journal files and lastMark, to make sure that we are not reading from
    // Journal file
    File[] journalDirs = conf.getJournalDirs();
    for (File journalDir : journalDirs) {
        File journalDirectory = Bookie.getCurrentDirectory(journalDir);
        List<Long> journalLogsId = Journal.listJournalIds(journalDirectory, null);
        for (long journalId : journalLogsId) {
            File journalFile = new File(journalDirectory, Long.toHexString(journalId) + ".txn");
            journalFile.delete();
        }
    }

    // we know there is only one ledgerDir
    lastMarkFile = new File(ledgerDir, "lastMark");
    lastMarkFile.delete();

    // now we are restarting BookieServer
    conf.setLedgerStorageClass(InterleavedLedgerStorage.class.getName());
    server = new BookieServer(conf);
    server.start();
    BookKeeper newBKClient = new BookKeeper(clientConf);
    // since Bookie checkpointed successfully before shutdown/crash,
    // we should be able to read from entryLogs though journal is deleted

    AtomicBoolean receivedExceptionForRead = new AtomicBoolean(false);

    LongStream.range(0, numOfLedgers).parallel().forEach((ledgerId) -> {
        try {
            LedgerHandle lh = newBKClient.openLedger(ledgerId, DigestType.CRC32, "passwd".getBytes());
            Enumeration<LedgerEntry> entries = lh.readEntries(0, numOfEntries - 1);
            while (entries.hasMoreElements()) {
                LedgerEntry entry = entries.nextElement();
                byte[] readData = entry.getEntry();
                Assert.assertEquals("Ledger Entry Data should match", new String("data".getBytes()),
                        new String(readData));
            }
            lh.close();
        } catch (BKException | InterruptedException e) {
            receivedExceptionForRead.compareAndSet(false, true);
            LOG.error("Got Exception while trying to read entries of ledger, ledgerId: " + ledgerId, e);
        }
    });
    Assert.assertFalse("There shouldn't be any exceptions while creating readHandle and while reading"
            + "entries using readHandle", receivedExceptionForRead.get());

    newBKClient.close();
    server.shutdown();
}

From source file:com.blockwithme.longdb.tools.DBTool.java

/** Write CRC value in the meta-data file */
private static void writeCRC(final String theOutFile, final OutputStream theBOStrm, final boolean isCompressed,
        final CRC32 theChecksum) throws IOException {
    final Long chksum = isCompressed ? ((CRCGZipOutputStream) theBOStrm).getCRC().getValue()
            : theChecksum.getValue();//  ww  w  .ja  va2 s. c  om
    final File crcFile = new File((new File(theOutFile)).getAbsolutePath() // $codepro.audit.disable
            // com.instantiations.assist.eclipse.analysis.pathManipulation
            + ".crc32");
    FileUtils.writeStringToFile(crcFile, Long.toHexString(chksum));
}

From source file:io.orchestrate.client.itest.KvTest.java

@Theory
public void mergePatchKey(@ForAll(sampleSize = 10) final String key) {
    assumeThat(key, not(isEmptyString()));

    String name1 = Long.toHexString(RAND.nextLong());

    final KvMetadata kvMetadata = insertItem(key, "{`name1`:`%s`}", name1);

    String name2 = Long.toHexString(RAND.nextLong());

    final KvMetadata patched = client.kv(collection(), key).merge("{\"name2\":\"" + name2 + "\"}").get();

    assertNotEquals(kvMetadata, patched);

    final KvObject<ObjectNode> kvObject = client.kv(kvMetadata.getCollection(), kvMetadata.getKey())
            .get(ObjectNode.class).get();

    assertEquals(patched.getRef(), kvObject.getRef());
    assertEquals(name1, kvObject.getValue().get("name1").asText());
    assertEquals(name2, kvObject.getValue().get("name2").asText());
}

From source file:org.openbravo.erpCommon.obps.ActivationKey.java

public String getOpsLogId() {
    CRC32 crc = new CRC32();
    crc.update(getPublicKey().getBytes());
    return Long.toHexString(crc.getValue());
}