javax.xml.bind.DatatypeConverter Java Examples

The following examples show how to use javax.xml.bind.DatatypeConverter. 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: SecurityServiceImpl.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 8 votes vote down vote up
@Override
public String createToken(String subject, long ttlMillis) {
	
	if (ttlMillis <= 0) {
		throw new RuntimeException("Expiry time must be greater than Zero :["+ttlMillis+"] ");
	}
	
	SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

	// The JWT signature algorithm we will be using to sign the token
	long nowMillis = System.currentTimeMillis();

	byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey);
	Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

	JwtBuilder builder = Jwts.builder()
			.setSubject(subject)				
			.signWith(signatureAlgorithm, signingKey);
	
	builder.setExpiration(new Date(nowMillis + ttlMillis));		

	return builder.compact();
}
 
Example #2
Source File: DateUtils.java    From elasticsearch-hadoop with Apache License 2.0 6 votes vote down vote up
public static Calendar parseDate(String value) {
    // check for colon in the time offset
    int timeZoneIndex = value.indexOf("T");
    if (timeZoneIndex > 0) {
        int sign = value.indexOf("+", timeZoneIndex);
        if (sign < 0) {
            sign = value.indexOf("-", timeZoneIndex);
        }

        // +4 means it's either hh:mm or hhmm
        if (sign > 0) {
            // +3 points to either : or m
            int colonIndex = sign + 3;
            // +hh - need to add :mm
            if (colonIndex >= value.length()) {
                value = value + ":00";
            }
            else if (value.charAt(colonIndex) != ':') {
                value = value.substring(0, colonIndex) + ":" + value.substring(colonIndex);
            }
        }
    }

    return DatatypeConverter.parseDateTime(value);
}
 
Example #3
Source File: UserServiceImpl.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 6 votes vote down vote up
@Override
public User getUserByToken(String token){
	Claims claims = Jwts.parser()         
		       .setSigningKey(DatatypeConverter.parseBase64Binary(SecurityServiceImpl.secretKey))
		       .parseClaimsJws(token).getBody();
	
	if(claims == null || claims.getSubject() == null){
		return null;
	}
	
	String subject = claims.getSubject();
	
	if(subject.split("=").length != 2){
		return null;
	}
	
	String[] subjectParts = subject.split("=");
	
	
	Integer userid = new Integer(subjectParts[0]);
	Integer usertype = new Integer(subjectParts[1]);		
	
	System.out.println("{getUserByToken} usertype["+usertype+"], userid["+userid+"]");
	
	return new User(userid, usertype);
}
 
Example #4
Source File: JWTUtils.java    From DBus with Apache License 2.0 6 votes vote down vote up
public static String buildToken(String key, long expirationMinutes, Map<String, Object> claims) {

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(key);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        JwtBuilder builder = Jwts.builder().setIssuedAt(now)
                .addClaims(claims)
                .signWith(signatureAlgorithm, signingKey);
        builder.setExpiration(new Date(nowMillis + expirationMinutes * 60 * 1000));

        return builder.compact();
    }
 
Example #5
Source File: RFXComUndecodedRFMessage.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public State convertToState(RFXComValueSelector valueSelector) throws RFXComException {

    org.openhab.core.types.State state = UnDefType.UNDEF;

    if (valueSelector.getItemClass() == StringItem.class) {
        if (valueSelector == RFXComValueSelector.RAW_DATA) {
            state = new StringType(DatatypeConverter.printHexBinary(rawMessage));
        } else if (valueSelector == RFXComValueSelector.DATA) {
            state = new StringType(DatatypeConverter.printHexBinary(rawData));
        } else {
            throw new RFXComException("Can't convert " + valueSelector + " to StringItem");
        }
    } else {
        throw new RFXComException("Can't convert " + valueSelector + " to " + valueSelector.getItemClass());
    }

    return state;
}
 
Example #6
Source File: ClickHouseBlockChecksumTest.java    From clickhouse-jdbc with Apache License 2.0 6 votes vote down vote up
@Test
public void trickyBlock() {
    byte[] compressedData = DatatypeConverter.parseHexBinary("1F000100078078000000B4000000");
    int uncompressedSizeBytes = 35;

    ClickHouseBlockChecksum checksum = ClickHouseBlockChecksum.calculateForBlock(
        (byte) ClickHouseLZ4Stream.MAGIC,
        compressedData.length + HEADER_SIZE_BYTES,
        uncompressedSizeBytes,
        compressedData,
        compressedData.length
    );

    Assert.assertEquals(
        new ClickHouseBlockChecksum(-493639813825217902L, -6253550521065361778L),
        checksum
    );
}
 
Example #7
Source File: Connection.java    From jmxtrans-agent with MIT License 6 votes vote down vote up
private PrivateKey getPrivateKeyFromString(String serviceKeyPem) {
    if (isNullOrEmpty(serviceKeyPem))
        return null;
    PrivateKey privateKey = null;
    try {
        String privKeyPEM = serviceKeyPem.replace("-----BEGIN PRIVATE KEY-----", "")
                .replace("-----END PRIVATE KEY-----", "")
                .replace("\\r", "")
                .replace("\\n", "")
                .replace("\r", "")
                .replace("\n", "");

        byte[] encoded = DatatypeConverter.parseBase64Binary(privKeyPEM);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
        privateKey = KeyFactory.getInstance("RSA")
                .generatePrivate(keySpec);
    } catch (Exception e) {
        String error = "Constructing Private Key from PEM string failed: " + e.getMessage();
        logger.log(Level.SEVERE, error, e);
    }
    return privateKey;
}
 
Example #8
Source File: AdministrationRecordImpl.java    From semanticMDR with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void setLastChangeDate(Calendar lastChangeDate,
		String changeDescription) {
	if (lastChangeDate != null && Util.isNull(changeDescription)) {
		throw new IllegalArgumentException(
				"Change Description must be specified if a Last Change Date is set for Administration Record.");
	}
	if (lastChangeDate == null && !Util.isNull(changeDescription)) {
		throw new IllegalArgumentException(
				"Change Description cannot be set if a Last Change Date is not specified for Administration Record.");
	}
	if (lastChangeDate == null) {
		setPropertyValue(mdrDatabase.getVocabulary().lastChangeDate,
				mdrDatabase.getUtil().createTypedLiteral(null));
	} else {
		setPropertyValue(
				mdrDatabase.getVocabulary().lastChangeDate,
				mdrDatabase.getOntModel().createTypedLiteral(
						DatatypeConverter.printDateTime(lastChangeDate)));
	}
	setPropertyValue(mdrDatabase.getVocabulary().changeDescription,
			mdrDatabase.getUtil().createTypedLiteral(changeDescription));
}
 
Example #9
Source File: PublishKafka_0_10.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private byte[] getMessageKey(final FlowFile flowFile, final ProcessContext context) {
    if (context.getProperty(MESSAGE_DEMARCATOR).isSet()) {
        return null;
    }

    final String uninterpretedKey;
    if (context.getProperty(KEY).isSet()) {
        uninterpretedKey = context.getProperty(KEY).evaluateAttributeExpressions(flowFile).getValue();
    } else {
        uninterpretedKey = flowFile.getAttribute(KafkaProcessorUtils.KAFKA_KEY);
    }

    if (uninterpretedKey == null) {
        return null;
    }

    final String keyEncoding = context.getProperty(KEY_ATTRIBUTE_ENCODING).getValue();
    if (UTF8_ENCODING.getValue().equals(keyEncoding)) {
        return uninterpretedKey.getBytes(StandardCharsets.UTF_8);
    }

    return DatatypeConverter.parseHexBinary(uninterpretedKey);
}
 
Example #10
Source File: GridFSTest.java    From mongo-java-driver-rx with Apache License 2.0 6 votes vote down vote up
private void doDownload(final BsonDocument arguments, final BsonDocument assertion) {
    Throwable error = null;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    try {
        gridFSBucket.downloadToStream(arguments.getObjectId("id").getValue(), toAsyncOutputStream(outputStream))
                .timeout(30, SECONDS).toList().toBlocking().first();
        outputStream.close();
    } catch (Throwable e) {
        error = e;
    }

    if (assertion.containsKey("result")) {
        assertNull("Should not have thrown an exception", error);
        assertEquals(DatatypeConverter.printHexBinary(outputStream.toByteArray()).toLowerCase(),
                assertion.getDocument("result").getString("$hex").getValue());
    } else if (assertion.containsKey("error")) {
        assertNotNull("Should have thrown an exception", error);
    }
}
 
Example #11
Source File: AvroDeserializer.java    From spring-kafka with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public T deserialize(String topic, byte[] data) {
  try {
    T result = null;

    if (data != null) {
      LOGGER.debug("data='{}'", DatatypeConverter.printHexBinary(data));

      DatumReader<GenericRecord> datumReader =
          new SpecificDatumReader<>(targetType.newInstance().getSchema());
      Decoder decoder = DecoderFactory.get().binaryDecoder(data, null);

      result = (T) datumReader.read(null, decoder);
      LOGGER.debug("deserialized data='{}'", result);
    }
    return result;
  } catch (Exception ex) {
    throw new SerializationException(
        "Can't deserialize data '" + Arrays.toString(data) + "' from topic '" + topic + "'", ex);
  }
}
 
Example #12
Source File: JwtService.java    From faster-framework-project with Apache License 2.0 6 votes vote down vote up
/**
 * 解密
 *
 * @param token          要解密的token
 * @param base64Security 秘钥
 * @return Claims
 */
private Claims parseToken(String token, String base64Security) {
    try {
        Claims claims = Jwts.parser()
                .setSigningKey(DatatypeConverter.parseBase64Binary(base64Security))
                .parseClaimsJws(token).getBody();
        if (claims == null) {
            return null;
        }
        //如果环境相同
        if (this.env.equals(claims.get("env", String.class))) {
            return claims;
        }
        return null;
    } catch (Exception e) {
        return null;
    }
}
 
Example #13
Source File: GidsBaseTestClass.java    From GidsApplet with GNU General Public License v3.0 5 votes vote down vote up
protected void execute(String command, String expectedresponse) {
    byte[] expected = DatatypeConverter.parseHexBinary(expectedresponse.replaceAll("\\s",""));
    ResponseAPDU response = execute(command, 0xFFFF & Util.makeShort(expected[expected.length-2],expected[expected.length-1]));
    if (!Arrays.equals(response.getBytes(), expected)) {
        fail("expected: " + expectedresponse.replaceAll("\\s","") + " but was: " + DatatypeConverter.printHexBinary(response.getBytes()));
    }

}
 
Example #14
Source File: GridFSTest.java    From mongo-java-driver-reactivestreams with Apache License 2.0 5 votes vote down vote up
private BsonDocument parseHexDocument(final BsonDocument document, final String hexDocument) {
    if (document.containsKey(hexDocument) && document.get(hexDocument).isDocument()) {
        byte[] bytes = DatatypeConverter.parseHexBinary(document.getDocument(hexDocument).getString("$hex").getValue());
        document.put(hexDocument, new BsonBinary(bytes));
    }
    return document;
}
 
Example #15
Source File: ValueConverter.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
static public void convertFromJava(Long value, ValueProcessor processor) {
  if (value == null) {
    processor.process(null, null, null);
    return;
  }
  long longVal = ((Long) value).longValue();
  if (0 <= longVal && longVal <= MAX_UNSIGNED_INT)
    processor.process(
      value,
      "xs:unsignedInt",
      DatatypeConverter.printUnsignedInt(longVal)
    );
  else
    processor.process(value,"xs:long", LongPrimitiveToString(longVal));
}
 
Example #16
Source File: TestUtils.java    From noise-java with MIT License 5 votes vote down vote up
/**
 * Convert a string into a binary byte array.
 * 
 * @param data The string data to convert.
 * @return The binary version of the data.
 * 
 * If the string starts with "0x", then the remainder of the string is
 * interpreted as hexadecimal.  Otherwise the string is interpreted
 * as a literal string (e.g. "abc") and converted with the UTF-8 encoding.
 */
public static byte[] stringToData(String data)
{
	if (data.startsWith("0x")) {
		return DatatypeConverter.parseHexBinary(data.substring(2));
	} else {
		try {
			return data.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			return new byte [0];
		}
	}
}
 
Example #17
Source File: TrovitUtils.java    From OpenEstate-IO with Apache License 2.0 5 votes vote down vote up
/**
 * Read a {@link BigDecimal} value from XML
 * with a valid longitude range.
 *
 * @param value XML string
 * @return parsed value or null, if the value is invalid
 */
public static BigDecimal parseLongitudeValue(String value) {
    try {
        value = StringUtils.trimToNull(value);
        return (value != null) ? DatatypeConverter.parseDecimal(value) : null;
    } catch (NumberFormatException ex) {
        throw new IllegalArgumentException("Can't parse longitude value '" + value + "'!", ex);
    }
}
 
Example #18
Source File: ServerUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Build HTTP Basic authorization base64 encoded credentials argument
 * containing user name and password.
 * <p/>
 * @param user Username to be stored into encoded argument.
 * @param password Password to be stored into encoded argument.
 */
public static String basicAuthCredentials(final String user,
        final String password) {
    StringBuilder sb = new StringBuilder(user.length()
            + AUTH_BASIC_FIELD_SEPARATPR.length() + password.length());
    sb.append(user);
    sb.append(AUTH_BASIC_FIELD_SEPARATPR);
    sb.append(password);
    return DatatypeConverter.printBase64Binary(sb.toString().getBytes());
}
 
Example #19
Source File: CBuiltinLeafInfo.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public JExpression createConstant(Outline outline, XmlString lexical) {
    QName qn = DatatypeConverter.parseQName(lexical.value,new NamespaceContextAdapter(lexical));
    return JExpr._new(outline.getCodeModel().ref(QName.class))
        .arg(qn.getNamespaceURI())
        .arg(qn.getLocalPart())
        .arg(qn.getPrefix());
}
 
Example #20
Source File: TorrentEngine.java    From TorrentEngine with GNU General Public License v3.0 5 votes vote down vote up
private static List<Entry> getCollectionEntries(Map<String, Entry> collection) throws Exception
{
   List<Entry> collectionEntries = new ArrayList<>();

   int count = 0;
   Print.string("Fetching collection " + count + "/" + collection.size());

   for (Entry entry : collection.values()) {

      count++;

      try {
          // System.out.println(entry.getInfohash());
          byte[] torrent = Cache.getFromCacheOrDownload(entry.getInfohash());

          Metafile meta = new Metafile(new ByteArrayInputStream(torrent));
          String infohash = DatatypeConverter.printHexBinary(meta.getInfoSha1());
          entry.setTorrentFile(torrent);

          if (!entry.getInfohash().equalsIgnoreCase(infohash)) {
              Print.line(entry.getInfohash());
              Print.line(infohash);
              throw new Exception("Collection-Entry Consistancy Error");
          }

          collectionEntries.add(entry);

      } catch (Exception ex) {
          Print.line("Error with entry: " + entry.getInfohash());
      }

      Print.string("\rFetching collection " + count + "/" + collection.size());
   }

   Print.line("");
   return collectionEntries;
}
 
Example #21
Source File: TestCRC16.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Test
public void testHubFromMac() {
	String str = "00112233445566778899AABBCCDDEEFF";
	byte[] bytes = DatatypeConverter.parseHexBinary(str);
	assertEquals((short) 0x27A9, CRC16.ARC.crc(bytes));
	assertEquals((short) 0x57E3, CRC16.AUG.crc(bytes));
	assertEquals((short) 0x0B62, CRC16.BUYPASS.crc(bytes));
	assertEquals((short) 0x7842, CRC16.CCITT.crc(bytes));
	assertEquals((short) 0x9F0B, CRC16.CDMA2000.crc(bytes));
	assertEquals((short) 0x8545, CRC16.DDS110.crc(bytes));
	assertEquals((short) 0xDFE2, CRC16.DECT_R.crc(bytes));
	assertEquals((short) 0xDFE3, CRC16.DECT_X.crc(bytes));
	assertEquals((short) 0xF289, CRC16.DNP.crc(bytes));
	assertEquals((short) 0xAF18, CRC16.EN_13757.crc(bytes));
	assertEquals((short) 0x87BD, CRC16.GENIBUS.crc(bytes));
	assertEquals((short) 0xD856, CRC16.MAXIM.crc(bytes));
	assertEquals((short) 0x70AD, CRC16.MCRF4XX.crc(bytes));
	assertEquals((short) 0x198A, CRC16.RIELLO.crc(bytes));
	assertEquals((short) 0xB1B2, CRC16.T10_DIF.crc(bytes));
	assertEquals((short) 0x70BC, CRC16.TELEDISK.crc(bytes));
	assertEquals((short) 0x348C, CRC16.TMS37157.crc(bytes));
	assertEquals((short) 0x28E8, CRC16.USB.crc(bytes));
	assertEquals((short) 0x69CC, CRC16.A.crc(bytes));
	assertEquals((short) 0xD717, CRC16.MODBUS.crc(bytes));		
	assertEquals((short) 0x8F52, CRC16.X25.crc(bytes));
	assertEquals((short) 0x1248, CRC16.XMODEM.crc(bytes));
	assertEquals((short) 0x20FB, CRC16.KERMIT.crc(bytes));
}
 
Example #22
Source File: PermissibleValueImpl.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setPermissibleValueEndDate(Calendar permissibleValueEndDate) {
	if (permissibleValueEndDate == null) {
		setPropertyValue(
				mdrDatabase.getVocabulary().permissibleValueEndDate,
				mdrDatabase.getUtil().createTypedLiteral(null));
	} else {
		setPropertyValue(
				mdrDatabase.getVocabulary().permissibleValueEndDate,
				mdrDatabase.getOntModel().createTypedLiteral(
						DatatypeConverter
								.printDateTime(permissibleValueEndDate)));
	}
}
 
Example #23
Source File: AvroDeserializerTest.java    From spring-kafka with MIT License 5 votes vote down vote up
@Test
public void testDeserialize() {
  User user = User.newBuilder().setName("John Doe").setFavoriteColor("green")
      .setFavoriteNumber(null).build();

  byte[] data = DatatypeConverter.parseHexBinary("104A6F686E20446F6502000A677265656E");
  AvroDeserializer<User> avroDeserializer = new AvroDeserializer<>(User.class);

  assertThat(avroDeserializer.deserialize("avro-bijection.t", data)).isEqualTo(user);
  avroDeserializer.close();
}
 
Example #24
Source File: StringUtilsJvmTest.java    From essentials with Apache License 2.0 5 votes vote down vote up
@Test
public void testHexBig() {
    for (int i = 0; i < 256 * 256; i++) {
        byte[] bytes = {(byte) (i >> 8), (byte) i};
        String hexExpected = DatatypeConverter.printHexBinary(bytes);
        String hex = StringUtils.hex(bytes);
        assertEquals(hexExpected, hex);

        byte[] bytes2 = StringUtils.parseHex(hex);
        assertEquals(bytes[0], bytes2[0]);
        assertEquals(bytes[1], bytes2[1]);
    }
}
 
Example #25
Source File: SHA2Test.java    From Chronicle-Salt with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiPart512() {
    BytesStore message1 = NativeBytesStore.from("Message part1");
    BytesStore message2 = NativeBytesStore.from("Message part2");
    BytesStore message3 = NativeBytesStore.from("Message part3");

    SHA2.MultiPartSHA512 multi = new SHA2.MultiPartSHA512();
    multi.add(message1);
    multi.add(message2);
    multi.add(message3);
    BytesStore hash = multi.hash();

    assertEquals("D03F370D9C234701370A0323AF9BB5D0E13AEB128C6C14C427DD25B1FFCFA7EB"
            + "B505665AD2C97D989A3F460715D3C688FE04B9FC8AAA3213051486930A3B3876", DatatypeConverter.printHexBinary(hash.toByteArray()));
}
 
Example #26
Source File: SerializeUtil.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
public static String serializeToBase64(Serializable o) {
    if (o == null) {
        return null;
    }

    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject(o);
        }
       return DatatypeConverter.printBase64Binary(baos.toByteArray());
    }catch (IOException e) {
        logger.error("Object serializing error", e);
        return null;
    }
}
 
Example #27
Source File: PermissibleValueImpl.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Calendar getPermissibleValueEndDate() {
	RDFNode permissibleValueEndDate = getPropertyValue(mdrDatabase
			.getVocabulary().permissibleValueEndDate);
	if (permissibleValueEndDate == null) {
		logger.debug("PermissibleValue does not have permissibleValueEndDate");
		return null;
	}
	return DatatypeConverter.parseDateTime(permissibleValueEndDate
			.asLiteral().getLexicalForm());
}
 
Example #28
Source File: AbstractRPCChannelHandler.java    From floodlight_with_topoguard with Apache License 2.0 5 votes vote down vote up
private void authenticateResponse(String challenge, 
                                  String response) throws AuthException {
    String expected = generateResponse(challenge);
    if (expected == null) return;

    byte[] expectedBytes = DatatypeConverter.parseBase64Binary(expected);
    byte[] reponseBytes = DatatypeConverter.parseBase64Binary(response);
    
    if (!Arrays.equals(expectedBytes, reponseBytes)) {
        throw new AuthException("Challenge response does not match " +
                                "expected response");
    } 
}
 
Example #29
Source File: TokenCreator.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
private static RSAPrivateKey privateKeyConverter(String pemKey) throws NoSuchAlgorithmException,
                                                                InvalidKeySpecException {
    byte[] keyBytes = DatatypeConverter.parseBase64Binary(pemKey);
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return (RSAPrivateKey) keyFactory.generatePrivate(spec);
}
 
Example #30
Source File: TLSUtil.java    From webapp-hardware-bridge with MIT License 5 votes vote down vote up
private static RSAPrivateKey readKey(File key) throws Exception {
    String data = new String(getBytes(key));
    String[] tokens = data.split("-----BEGIN PRIVATE KEY-----");
    tokens = tokens[1].split("-----END PRIVATE KEY-----");

    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(DatatypeConverter.parseBase64Binary(tokens[0]));
    KeyFactory factory = KeyFactory.getInstance("RSA");
    return (RSAPrivateKey) factory.generatePrivate(spec);
}