org.apache.commons.codec.binary.Hex Java Examples

The following examples show how to use org.apache.commons.codec.binary.Hex. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ABE.java    From SPADE with GNU General Public License v3.0 6 votes vote down vote up
private String encryptAnnotation(String plainAnnotation, Cipher cipher)
{
	if(plainAnnotation == null)
		return null;
	try
	{
		String encryptedAnnotationStr;
		byte[] encryptedAnnotation = cipher.doFinal(plainAnnotation.getBytes(StandardCharsets.UTF_8));
		encryptedAnnotationStr = Hex.encodeHexString(encryptedAnnotation);
		return encryptedAnnotationStr;
	}
	catch(Exception ex)
	{
		String message = "Unable to encrypt annotation " + "'" + plainAnnotation + "'. " +
				"This would disturb any further encryption of annotations.";
		logger.log(Level.WARNING, message, ex);
		return null;
	}
}
 
Example #2
Source File: ContinueToken.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Generate a continuation token which is used in get Bucket.
 *
 * @return if key is not null return continuation token, else returns null.
 */
public String encodeToString() {
  if (this.lastKey != null) {

    ByteBuffer buffer = ByteBuffer
        .allocate(4 + lastKey.length()
            + (lastDir == null ? 0 : lastDir.length()));
    buffer.putInt(lastKey.length());
    buffer.put(lastKey.getBytes(StandardCharsets.UTF_8));
    if (lastDir != null) {
      buffer.put(lastDir.getBytes(StandardCharsets.UTF_8));
    }

    String hex = Hex.encodeHexString(buffer.array());
    String digest = DigestUtils.sha256Hex(hex);
    return hex + CONTINUE_TOKEN_SEPERATOR + digest;
  } else {
    return null;
  }
}
 
Example #3
Source File: BitcoinJSONRPCRetriever.java    From bitcoin-transaction-explorer with MIT License 6 votes vote down vote up
@Override
public AddressInformation getAddressInformation(final String address) throws ApplicationException {
  try (final CloseableHttpClient client = getAuthenticatedHttpClientProxy();
      final InputStream jsonData = doComplexJSONRPCMethod(client, "searchrawtransactions", address).getContent()) {

    final AddressInformation addressInformation = JSONRPCParser.getAddressInformation(address, jsonData);

    for (final AddressOutpoint outpoint : addressInformation.getOutpoints()) {
      final String txid = new String(Hex.encodeHex(outpoint.getReferenceTransaction()));
      try (final InputStream utxoJsonData = doComplexJSONRPCMethod(client, "gettxout", txid, outpoint.getIndex()).getContent()) {
        outpoint.setSpent(JSONRPCParser.isNullResult(utxoJsonData));
      }
    }

    return addressInformation;
  } catch (IOException | HttpException | DecoderException e) {
    e.printStackTrace();
    throw new ApplicationException(e.getMessage());
  }
}
 
Example #4
Source File: RelayMain.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void handleRelay() {
    get("/relay", (request, response) -> {
        log.info("Incoming relay request from: " + request.userAgent());
        boolean isAndroid = request.queryParams("isAndroid").equalsIgnoreCase("true");
        boolean useSound = request.queryParams("snd").equalsIgnoreCase("true");
        String token = new String(Hex.decodeHex(request.queryParams("token").toCharArray()), "UTF-8");
        String encryptedMessage = new String(Hex.decodeHex(request.queryParams("msg").toCharArray()), "UTF-8");
        log.info("isAndroid={}\nuseSound={}\napsTokenHex={}\nencryptedMessage={}", isAndroid, useSound, token,
            encryptedMessage);
        if (isAndroid) {
            return relayService.sendAndroidMessage(token, encryptedMessage, useSound);
        } else {
            boolean isProduction = request.queryParams("isProduction").equalsIgnoreCase("true");
            boolean isContentAvailable = request.queryParams("isContentAvailable").equalsIgnoreCase("true");
            return relayService.sendAppleMessage(isProduction, isContentAvailable, token, encryptedMessage, useSound);
        }
    });
}
 
Example #5
Source File: DistributedLogTool.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
protected void printStreams(Namespace namespace) throws Exception {
    Iterator<String> streams = namespace.getLogs();
    System.out.println("Streams under " + getUri() + " : ");
    System.out.println("--------------------------------");
    while (streams.hasNext()) {
        String streamName = streams.next();
        System.out.println(streamName);
        if (!printMetadata) {
            continue;
        }
        MetadataAccessor accessor =
                namespace.getNamespaceDriver().getMetadataAccessor(streamName);
        byte[] metadata = accessor.getMetadata();
        if (null == metadata || metadata.length == 0) {
            continue;
        }
        if (printHex) {
            System.out.println(Hex.encodeHexString(metadata));
        } else {
            System.out.println(new String(metadata, UTF_8));
        }
        System.out.println("");
    }
    System.out.println("--------------------------------");
}
 
Example #6
Source File: AndroidRelocationIterator.java    From unidbg with Apache License 2.0 6 votes vote down vote up
public AndroidRelocationIterator(int objectSize, SymbolLocator symtab, byte[] androidRelData, boolean rela) {
    if (log.isDebugEnabled()) {
        Inspector.inspect(androidRelData, "androidRelData hex=" + Hex.encodeHexString(androidRelData));
    }

    this.objectSize = objectSize;
    this.buffer = ByteBuffer.wrap(androidRelData);
    this.rela = rela;
    reloc_ = new ElfRelocation(objectSize, symtab);

    relocation_count_ = readSleb128();
    reloc_.offset = readSleb128();

    relocation_index_ = 0;
    relocation_group_index_ = 0;
    group_size_ = 0;
}
 
Example #7
Source File: AnalyticsPluginAssetsService.java    From gocd with Apache License 2.0 6 votes vote down vote up
private String sha2Digest(byte[]... bytes) {
    try {
        MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM);

        for (byte[] data : bytes) {
            md.update(data);
        }

        return Hex.encodeHexString(md.digest());
    } catch (Exception e) {
        LOGGER.error("Error generating {} hash", HASH_ALGORITHM, e);
        ExceptionUtils.bomb(e);
    }

    return null;
}
 
Example #8
Source File: MD5Crypt.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * MD5 and Hexify an array of bytes.  Take the input array, MD5 encodes it
 * and then turns it into Hex.
 * @param secretBytes you want md5hexed
 * @return md5hexed String.
 */
public static String md5Hex(byte[] secretBytes) {
    String retval = null;
    // add secret
    MessageDigest md;
    try {
        md = MessageDigest.getInstance("MD5");
        //byte[] secretBytes = inputString.getBytes("UTF-8");
        md.update(secretBytes);
        // generate the digest
        byte[] digest = md.digest();
        // hexify this puppy
        retval = new String(Hex.encodeHex(digest));
    }
    catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("NoSuchAlgorithm: MD5.  Something" +
                " weird with your JVM, you should be able to do this.", e);
    }
    return retval;
}
 
Example #9
Source File: SketchCore.java    From arduino-remote-uploader with GNU General Public License v2.0 6 votes vote down vote up
public String getMd5(int[] program) {
	MessageDigest messageDigest;
	
	try {
		messageDigest = MessageDigest.getInstance("MD5");
	} catch (NoSuchAlgorithmException e) {
		//srlsy??
		throw new RuntimeException("", e);
	}
	
	for (int i = 0; i < program.length; i++) {
		messageDigest.update((byte)i);	
	}
	
	return new String(Hex.encodeHex(messageDigest.digest()));
}
 
Example #10
Source File: Uuid5Evaluator.java    From nifi with Apache License 2.0 6 votes vote down vote up
private static String toString(final byte[] uuid) {
    if (uuid == null) {
        return new UUID(0, 0).toString();
    }

    final String encoded = Hex.encodeHexString(Objects.requireNonNull(uuid));
    final StringBuffer sb = new StringBuffer(encoded);

    while (sb.length() != 32) {
        sb.insert(0, "0");
    }

    sb.ensureCapacity(32);
    sb.insert(8, '-');
    sb.insert(13, '-');
    sb.insert(18, '-');
    sb.insert(23, '-');

    return sb.toString();
}
 
Example #11
Source File: B2SingleUploadService.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void verify(final Path file, final MessageDigest digest, final Checksum checksum) throws ChecksumException {
    if(null == digest) {
        log.debug(String.format("Digest verification disabled for file %s", file));
        return;
    }
    if(file.getType().contains(Path.Type.encrypted)) {
        log.warn(String.format("Skip checksum verification for %s with client side encryption enabled", file));
        return;
    }
    final String expected = Hex.encodeHexString(digest.digest());
    if(!checksum.equals(Checksum.parse(expected))) {
        throw new ChecksumException(MessageFormat.format(LocaleFactory.localizedString("Upload {0} failed", "Error"), file.getName()),
                MessageFormat.format("Mismatch between {0} hash {1} of uploaded data and ETag {2} returned by the server",
                        checksum.algorithm.toString(), expected, checksum.hash));
    }
}
 
Example #12
Source File: KeyUtil.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Returns the digest value of a given public key.
 *
 * <p>In Version “H003” of the EBICS protocol the ES of the financial:
 *
 * <p>The SHA-256 hash values of the financial institution's public keys for X002 and E002 are
 * composed by concatenating the exponent with a blank character and the modulus in hexadecimal
 * representation (using lower case letters) without leading zero (as to the hexadecimal
 * representation). The resulting string has to be converted into a byte array based on US ASCII
 * code.
 *
 * @param publicKey the public key
 * @return the digest value
 * @throws EbicsException
 */
public static byte[] getKeyDigest(RSAPublicKey publicKey) throws AxelorException {
  String modulus;
  String exponent;
  String hash;
  byte[] digest;

  exponent = Hex.encodeHexString(publicKey.getPublicExponent().toByteArray());
  modulus = Hex.encodeHexString(removeFirstByte(publicKey.getModulus().toByteArray()));
  hash = exponent + " " + modulus;

  if (hash.charAt(0) == '0') {
    hash = hash.substring(1);
  }

  try {
    digest = MessageDigest.getInstance("SHA-256", "BC").digest(hash.getBytes("US-ASCII"));
  } catch (GeneralSecurityException | UnsupportedEncodingException e) {
    throw new AxelorException(
        e.getCause(), TraceBackRepository.CATEGORY_CONFIGURATION_ERROR, e.getMessage());
  }

  return new String(Hex.encodeHex(digest, false)).getBytes();
}
 
Example #13
Source File: EncodeContent.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void process(InputStream in, OutputStream out) throws IOException {
    int len;
    byte[] inBuf = new byte[8192];
    Hex h = new Hex();
    while ((len = in.read(inBuf)) > 0) {
        // If the input buffer is of odd length, try to get another byte
        if (len % 2 != 0) {
            int b = in.read();
            if (b != -1) {
                inBuf[len] = (byte) b;
                len++;
            }
        }

        // Construct a new buffer bounded to len
        byte[] slice = Arrays.copyOfRange(inBuf, 0, len);
        try {
            out.write(h.decode(slice));
        } catch (DecoderException ex) {
            throw new IOException(ex);
        }
    }
    out.flush();
}
 
Example #14
Source File: HashCrypt.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
private static boolean doCompareTypePrefix(String crypted, String defaultCrypt, byte[] bytes) {
    int typeEnd = crypted.indexOf("}");
    String hashType = crypted.substring(1, typeEnd);
    String hashed = crypted.substring(typeEnd + 1);
    MessageDigest messagedigest = getMessageDigest(hashType);
    messagedigest.update(bytes);
    byte[] digestBytes = messagedigest.digest();
    char[] digestChars = Hex.encodeHex(digestBytes);
    String checkCrypted = new String(digestChars);
    if (hashed.equals(checkCrypted)) {
        return true;
    }
    // This next block should be removed when all {prefix}oldFunnyHex are fixed.
    if (hashed.equals(oldFunnyHex(digestBytes))) {
        Debug.logWarning("Warning: detected oldFunnyHex password prefixed with a hashType; this is not valid, please update the value in the database with ({%s}%s)", module, hashType, checkCrypted);
        return true;
    }
    return false;
}
 
Example #15
Source File: HttpClientTracingHandlerIntegrationTest.java    From xio with Apache License 2.0 6 votes vote down vote up
@Test
public void testOutBoundAndInboundSpan() throws Exception {
  TracingConfig tracingConfig =
      new TracingConfig(
          "tracingHandlerClientIntegrationTest", config().getConfig("settings.tracing"));
  val client = newClient(new FakeTracer(tracingConfig));

  val request =
      DefaultSegmentedRequest.builder()
          .method(GET)
          .path("/v1/authinit")
          .host("127.0.0.1" + ":" + server.getPort())
          .build();

  client.write(request);
  // We wait on the local future because this signals the full roundtrip between outbound and
  // return trip from the Application Handler out and then back in.
  local.get();
  assertEquals(reportedSpans.size(), 1);

  val responseHex = ByteBufUtil.hexDump(((SegmentedData) response).content());
  byte[] bytes = Hex.decodeHex(responseHex.toCharArray());
  assertEquals(expectedResponse, new String(bytes, "UTF-8"));
}
 
Example #16
Source File: HdfsSerDeImportService.java    From hadoop-etl-udfs with MIT License 6 votes vote down vote up
private static Object getJavaObjectFromPrimitiveData(Object data, ObjectInspector objInsp) {
    assert(objInsp.getCategory() == Category.PRIMITIVE);
    if (data == null) {
        return null;
    }
    if (data instanceof BytesWritable && objInsp instanceof WritableHiveDecimalObjectInspector) {
        // BytesWritable cannot be directly cast to HiveDecimalWritable
        WritableHiveDecimalObjectInspector oi = (WritableHiveDecimalObjectInspector) objInsp;
        data = oi.create(((BytesWritable) data).getBytes(), oi.scale());
    }
    Object obj = ObjectInspectorUtils.copyToStandardJavaObject(data, objInsp);
    if (obj instanceof HiveDecimal) {
        obj = ((HiveDecimal) obj).bigDecimalValue();
    } else if (obj instanceof HiveVarchar || obj instanceof HiveChar) {
        obj = obj.toString();
    } else if (obj instanceof byte[]) {
        obj = Hex.encodeHexString((byte[]) obj);
    }
    return obj;
}
 
Example #17
Source File: ByteArrayMarshall.java    From anno4j with Apache License 2.0 5 votes vote down vote up
public byte[] deserialize(Literal literal) {
	if (XMLSchema.HEXBINARY.equals(literal.getDatatype())) {
		try {
			return Hex.decodeHex(literal.stringValue().toCharArray());
		} catch (DecoderException e) {
			throw new ObjectConversionException(e);
		}
	}
	return Base64.decodeBase64(literal.stringValue().getBytes());
}
 
Example #18
Source File: PushStrategy.java    From sync-android with Apache License 2.0 5 votes vote down vote up
public String getReplicationId() throws DocumentStoreException {
    HashMap<String, String> dict = new HashMap<String, String>();
    dict.put("source", this.sourceDb.getIdentifier());
    dict.put("target", this.targetDb.getIdentifier());
    // get raw SHA-1 of dictionary
    try {
        byte[] sha1Bytes = Misc.getSha1(new ByteArrayInputStream(JSONUtils.serializeAsBytes(dict)));
        // return SHA-1 as a hex string
        byte[] sha1Hex = new Hex().encode(sha1Bytes);
        return new String(sha1Hex, Charset.forName("UTF-8"));
    } catch (IOException ioe) {
        throw new DocumentStoreException(ioe);
    }
}
 
Example #19
Source File: SkeletonClientSideRegionScanner.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * refresh underlying RegionScanner we call this when new store file gets
 * created by MemStore flushes or current scanner fails due to compaction
 */
public void updateScanner() throws IOException {
        if (LOG.isDebugEnabled()) {
            SpliceLogUtils.debug(LOG,
                    "updateScanner with hregionInfo=%s, tableName=%s, rootDir=%s, scan=%s",
                    hri, htd.getNameAsString(), rootDir, scan);
        }
        if (flushed) {
            if (LOG.isDebugEnabled())
                SpliceLogUtils.debug(LOG, "Flush occurred");
            byte[] restartRow = null;
            if (rowBuffer != null && !rowBuffer.isEmpty()) {
                restartRow = CellUtil.cloneRow(rowBuffer.get(0));
                rowBuffer = null;
            } else if (this.topCell != null) {
                restartRow = Bytes.add(CellUtil.cloneRow(topCell), new byte[]{0});
            }
            if (restartRow != null) {
                if (LOG.isDebugEnabled())
                    SpliceLogUtils.debug(LOG, "setting start row to %s", Hex.encodeHexString(restartRow));
                //noinspection deprecation
                scan.setStartRow(restartRow);
            }
        }
        memScannerList.add(getMemStoreScanner());
        this.region = openHRegion();
        RegionScanner regionScanner = new CountingRegionScanner(HRegionUtil.getScanner(region, scan, memScannerList), region, scan);
        if (flushed) {
            if (scanner != null)
                scanner.close();
        }
        scanner = regionScanner;
}
 
Example #20
Source File: DeltaJournalTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private List<Map> buildThirdBatch() throws DecoderException {
    Map<String, Object> e = new HashMap<String, Object>();
    e.put("_id", Hex.decodeHex("ee".toCharArray()));
    e.put("t", 3L);

    List<Map> res = new LinkedList<Map>();
    res.add(e);

    return res;
}
 
Example #21
Source File: FrameTest.java    From PacketProxy with Apache License 2.0 5 votes vote down vote up
@Test
public void removeExtraTest() throws Exception {
	byte[] frameData = Hex.decodeHex("00000e0148000000010000000541414141414242424242".toCharArray());
	Frame frame = new Frame(frameData);
	frame.removeExtra();
	System.out.println(new String(Hex.encodeHex(frame.toByteArray())));
}
 
Example #22
Source File: ItemUtils.java    From OpenModsLib with MIT License 5 votes vote down vote up
/**
 * This function returns fingerprint of NBTTag. It can be used to compare two tags
 */
public static String getNBTHash(NBTTagCompound tag) {
	try {
		MessageDigest digest = MessageDigest.getInstance("MD5");
		OutputStream dump = new NullOutputStream();
		DigestOutputStream hasher = new DigestOutputStream(dump, digest);
		DataOutput output = new DataOutputStream(hasher);
		CompressedStreamTools.write(tag, output);
		byte[] hash = digest.digest();
		return new String(Hex.encodeHex(hash));
	} catch (IOException | NoSuchAlgorithmException e) {
		throw new RuntimeException(e);
	}
}
 
Example #23
Source File: rrrccc.java    From letv with Apache License 2.0 5 votes vote down vote up
private static SecretKeySpec bй0439йй0439й(String str) throws Exception {
    String str2 = null;
    while (true) {
        try {
            str2.length();
        } catch (Exception e) {
            b0429Щ0429Щ0429Щ = b0429ЩЩЩ0429Щ();
            try {
                return new SecretKeySpec(Hex.decodeHex(str.toCharArray()), "AES");
            } catch (Exception e2) {
                throw e2;
            }
        }
    }
}
 
Example #24
Source File: FSEditLogOp.java    From big-c with Apache License 2.0 5 votes vote down vote up
public static void delegationKeyToXml(ContentHandler contentHandler,
    DelegationKey key) throws SAXException {
  contentHandler.startElement("", "", "DELEGATION_KEY", new AttributesImpl());
  XMLUtils.addSaxString(contentHandler, "KEY_ID",
      Integer.toString(key.getKeyId()));
  XMLUtils.addSaxString(contentHandler, "EXPIRY_DATE",
      Long.toString(key.getExpiryDate()));
  if (key.getEncodedKey() != null) {
    XMLUtils.addSaxString(contentHandler, "KEY",
        Hex.encodeHexString(key.getEncodedKey()));
  }
  contentHandler.endElement("", "", "DELEGATION_KEY");
}
 
Example #25
Source File: UtilityTest.java    From hedera-mirror-node with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("protobufKeyToHexIfEd25519OrNull valid ED25519 key")
public void protobufKeyToHexIfEd25519OrNull_Valid() throws Exception {
    var instr = "0011223344556677889900aabbccddeeff0011223344556677889900aabbccddeeff";
    var input = Key.newBuilder().setEd25519(ByteString.copyFrom(Hex.decodeHex(instr))).build();
    var result = getCut().protobufKeyToHexIfEd25519OrNull(input.toByteArray());

    assertThat(result).isEqualTo(instr);
}
 
Example #26
Source File: UniqueIDGeneratorThreadSafetyIT.java    From java-uniqueid with Apache License 2.0 5 votes vote down vote up
@Test
public void moreThanOneGeneratorClusterIDTest() throws InterruptedException {
    final Set<String> ids = Collections.synchronizedSet(new HashSet<>());
    // {generatorId, clusterId}
    final int[][] profiles = {
            {0, 0}, {1, 1}, {1, 2}, {1, 3}, {1, 15},
            {2, 0}, {3, 0}, {4, 0}, {5, 0}, {63, 0}
    };
    final int iterationCount = 10000;
    final CountDownLatch latch = new CountDownLatch(profiles.length);

    // Generate IDs for different generator-IDs and cluster-IDs in multiple threads.
    // Collision of IDs is almost guaranteed if the generator doesn't handle multi-threading gracefully.

    for (final int[] profile : profiles) {
        Thread t = new Thread(() -> {
            IDGenerator generator = LocalUniqueIDGeneratorFactory.generatorFor(profile[0], profile[1], Mode.SPREAD);
            try {
                for (int i = 0; i < iterationCount; i++) {
                    byte[] id = generator.generate();
                    String asHex = Hex.encodeHexString(id);
                    ids.add(asHex);
                }
            } catch (GeneratorException e) {
                // Test will fail due to missing IDs.
                e.printStackTrace();
            }
            latch.countDown();
        });
        t.start();
    }

    // Wait for all the threads to finish, or timeout.
    boolean successfullyUnlatched = latch.await(20, TimeUnit.SECONDS);
    assertThat(successfullyUnlatched, is(true));

    // If the set holds fewer items than this, duplicates were generated.
    assertThat(ids.size(), is(profiles.length * iterationCount));
}
 
Example #27
Source File: AuthStoreUtils.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
private String saltAndEncrypt(char[] data) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
    IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
  String value;
  Hex hex = new Hex();
  char[] saltedData = addSalt(data);

  byte[] encode = encrypt(saltedData, password);
  value = new String(hex.encode(encode));
  return value;
}
 
Example #28
Source File: UpdatableDigester.java    From extract with MIT License 5 votes vote down vote up
public UpdatableDigester(final String modifier, final String algorithm) {
    super(new UpdatableInputStreamDigester(20 * 1024 * 1024,
            algorithm, algorithm.replace("-", ""), Hex::encodeHexString) {
        @Override
        protected String getDigestUpdateModifier() {
            return modifier;
        }
    });
    this.algorithm = algorithm;
}
 
Example #29
Source File: DeltaJournalTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetEntityId() throws DecoderException {
    String id = "1234567890123456789012345678901234567890";
    String superid = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    String extraid = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
    Map<String, Object> delta = new HashMap<String, Object>();
    delta.put("_id", Hex.decodeHex(id.toCharArray()));
    assertEquals(id + "_id", DeltaJournal.getEntityId(delta));
    delta.put("i", Arrays.asList(Hex.decodeHex(superid.toCharArray())));
    assertEquals(superid + "_id" + id + "_id", DeltaJournal.getEntityId(delta));
    delta.put("i", Arrays.asList(Hex.decodeHex(superid.toCharArray()), Hex.decodeHex(extraid.toCharArray())));
    assertEquals(extraid + "_id" + superid + "_id" + id + "_id", DeltaJournal.getEntityId(delta));

}
 
Example #30
Source File: TabletRowAdapter.java    From timely with Apache License 2.0 5 votes vote down vote up
public static OptionalLong decodeRowOffset(Text row) {
    OptionalLong offset = OptionalLong.empty();
    byte[] bytes = row.getBytes();
    int delimidx = findRowDelimiterIndex(bytes);
    if (delimidx > 0) {
        try {
            byte[] buffer = Arrays.copyOfRange(bytes, delimidx + 1, bytes.length);
            buffer = ByteUtils.unescape(buffer);

            // key might not have all bytes for long decoding
            // ensure of sufficient length
            int extendBy = (MIN_OFFSET_LEN - (buffer.length));
            if (extendBy > 0) {
                buffer = ArrayUtils.addAll(buffer, new byte[extendBy]);
            }

            long decodedOffset = OFFSET_DECODER.decode(buffer);
            if (decodedOffset > 0) {
                offset = OptionalLong.of(decodedOffset);
            } else if (LOG.isTraceEnabled()) {
                Optional<String> prefix = decodeRowPrefix(row);
                LOG.trace(
                        "Delimiter identified but offset could not parse { prefix: {}, byte-len: {}, "
                                + "offset-len: {}, offset-bytes: {}, row-bytes: {} }",
                        prefix, bytes.length, buffer.length, Hex.encodeHex(buffer), Hex.encodeHex(bytes));
            }
        } catch (IllegalArgumentException e) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Unable to parse offset: " + e.getMessage(), e);
            }
        }
    }

    return offset;
}