Java Code Examples for javax.xml.bind.DatatypeConverter

The following are top voted examples for showing how to use javax.xml.bind.DatatypeConverter. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: SistemaAlmoxarifado   File: Token.java   View source code 9 votes vote down vote up
public static boolean Verify(String jwt, String type) throws Exception {
    
    try{
        Claims claims = Jwts.parser()
            .setSigningKey(DatatypeConverter.parseBase64Binary(Parameters.TOKENKEY))
            .parseClaimsJws(jwt).getBody();
        
        //verifica se o issuer é igual ao type
        return claims.getIssuer().equals(type);
        
    } catch (ExpiredJwtException | MalformedJwtException | SignatureException 
            | UnsupportedJwtException | IllegalArgumentException e) {
        System.out.println(e.getMessage());
        return false;
    }
}
 
Example 2
Project: SistemaAlmoxarifado   File: Token.java   View source code 8 votes vote down vote up
public static String Gerate(String issuer, int idSubject, int hours) {

        //The JWT signature algorithm we will be using to sign the token
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        
        //Hours to milliseconds
        long ttlMillis = hours * 3600000;
        String subject = String.valueOf(idSubject);
        
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        
        //We will sign our JWT with our ApiKey secret
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(Parameters.TOKENKEY);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //Let's set the JWT Claims
        JwtBuilder builder = Jwts.builder().setIssuedAt(now)
                                    .setSubject(subject)
                                    .setIssuer(issuer)
                                    .signWith(signatureAlgorithm, signingKey);

        //if it has been specified, let's add the expiration
        if (ttlMillis >= 0) {
        long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }

        //Builds the JWT and serializes it to a compact, URL-safe string
        return builder.compact();
    }
 
Example 3
Project: jdk8u-jdk   File: CipherStreamClose.java   View source code 6 votes vote down vote up
public static byte[] streamEncrypt(String message, SecretKey key,
    MessageDigest digest)
    throws Exception {

    byte[] data;
    Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    encCipher.init(Cipher.ENCRYPT_MODE, key);
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DigestOutputStream dos = new DigestOutputStream(bos, digest);
        CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
        try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
            oos.writeObject(message);
        }
        data = bos.toByteArray();
    }

    if (debug) {
        System.out.println(DatatypeConverter.printHexBinary(data));
    }
    return data;
}
 
Example 4
Project: xrd4j   File: MessageHelper.java   View source code 6 votes vote down vote up
/**
 * Encodes the given image InputStream to a base64 coded string.
 *
 * @param is image InputStream to encode
 * @param type type of the image: jpeg, bmp, png, gif etc.
 * @return encoded string
 */
public static String encodeImg2String(InputStream is, String type) {
    String imageString = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        BufferedImage image = ImageIO.read(is);
        ImageIO.write(image, type, bos);
        byte[] imageBytes = bos.toByteArray();
        imageString = DatatypeConverter.printBase64Binary(imageBytes);
        bos.close();
    } catch (IOException ex) {
        LOGGER.error(ex.getMessage(), ex);
    }
    return imageString;
}
 
Example 5
Project: dss-demonstrations   File: SignatureMultipleDocumentsController.java   View source code 6 votes vote down vote up
@RequestMapping(value = "/get-data-to-sign", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public GetDataToSignResponse getDataToSign(Model model, @RequestBody @Valid DataToSignParams params,
		@ModelAttribute("signatureMultipleDocumentsForm") @Valid SignatureMultipleDocumentsForm signatureMultipleDocumentsForm, BindingResult result) {
	signatureMultipleDocumentsForm.setBase64Certificate(params.getSigningCertificate());
	signatureMultipleDocumentsForm.setBase64CertificateChain(params.getCertificateChain());
	signatureMultipleDocumentsForm.setEncryptionAlgorithm(params.getEncryptionAlgorithm());
	signatureMultipleDocumentsForm.setSigningDate(new Date());
	model.addAttribute("signatureMultipleDocumentsForm", signatureMultipleDocumentsForm);

	ToBeSigned dataToSign = signingService.getDataToSign(signatureMultipleDocumentsForm);
	if (dataToSign == null) {
		return null;
	}

	GetDataToSignResponse responseJson = new GetDataToSignResponse();
	responseJson.setDataToSign(DatatypeConverter.printBase64Binary(dataToSign.getBytes()));
	return responseJson;
}
 
Example 6
Project: dss-demonstrations   File: SigningService.java   View source code 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public DSSDocument signDocument(SignatureDocumentForm form) {
	logger.info("Start signDocument with one document");
	DocumentSignatureService service = getSignatureService(form.getContainerType(), form.getSignatureForm());

	AbstractSignatureParameters parameters = fillParameters(form);

	DSSDocument signedDocument = null;
	try {
		DSSDocument toSignDocument = WebAppUtils.toDSSDocument(form.getDocumentToSign());
		SignatureAlgorithm sigAlgorithm = SignatureAlgorithm.getAlgorithm(form.getEncryptionAlgorithm(), form.getDigestAlgorithm());
		SignatureValue signatureValue = new SignatureValue(sigAlgorithm, DatatypeConverter.parseBase64Binary(form.getBase64SignatureValue()));
		signedDocument = service.signDocument(toSignDocument, parameters, signatureValue);
	} catch (Exception e) {
		logger.error("Unable to execute signDocument : " + e.getMessage(), e);
	}
	logger.info("End signDocument with one document");
	return signedDocument;
}
 
Example 7
Project: dss-demonstrations   File: SigningService.java   View source code 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public DSSDocument signDocument(SignatureMultipleDocumentsForm form) {
	logger.info("Start signDocument with multiple documents");
	MultipleDocumentsSignatureService service = getASiCSignatureService(form.getSignatureForm());

	AbstractSignatureParameters parameters = fillParameters(form);

	DSSDocument signedDocument = null;
	try {
		List<DSSDocument> toSignDocuments = WebAppUtils.toDSSDocuments(form.getDocumentsToSign());
		SignatureAlgorithm sigAlgorithm = SignatureAlgorithm.getAlgorithm(form.getEncryptionAlgorithm(), form.getDigestAlgorithm());
		SignatureValue signatureValue = new SignatureValue(sigAlgorithm, DatatypeConverter.parseBase64Binary(form.getBase64SignatureValue()));
		signedDocument = service.signDocument(toSignDocuments, parameters, signatureValue);
	} catch (Exception e) {
		logger.error("Unable to execute signDocument : " + e.getMessage(), e);
	}
	logger.info("End signDocument with multiple documents");
	return signedDocument;
}
 
Example 8
Project: kafka-0.11.0.0-src-with-comment   File: ScramMessages.java   View source code 6 votes vote down vote up
public ServerFinalMessage(byte[] messageBytes) throws SaslException {
    String message = toMessage(messageBytes);
    Matcher matcher = PATTERN.matcher(message);
    if (!matcher.matches())
        throw new SaslException("Invalid SCRAM server final message format: " + message);
    String error = null;
    try {
        error = matcher.group("error");
    } catch (IllegalArgumentException e) {
        // ignore
    }
    if (error == null) {
        this.serverSignature = DatatypeConverter.parseBase64Binary(matcher.group("signature"));
        this.error = null;
    } else {
        this.serverSignature = null;
        this.error = error;
    }
}
 
Example 9
Project: daf-replicate-ingestion   File: AvroDeserializer.java   View source code 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 10
Project: komodoGUI   File: ProvingKeyFetcher.java   View source code 6 votes vote down vote up
private static boolean checkSHA256(File provingKey, Component parent) throws IOException {
    MessageDigest sha256;
    try {
        sha256 = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException impossible) {
        throw new RuntimeException(impossible);
    }
    try (InputStream is = new BufferedInputStream(new FileInputStream(provingKey))) {
        ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(parent,"Verifying proving key",is);
        pmis.getProgressMonitor().setMaximum(PROVING_KEY_SIZE);
        pmis.getProgressMonitor().setMillisToPopup(10);
        DigestInputStream dis = new DigestInputStream(pmis, sha256);
        byte [] temp = new byte[0x1 << 13];
        while(dis.read(temp) >= 0);
        byte [] digest = sha256.digest();
        return SHA256.equalsIgnoreCase(DatatypeConverter.printHexBinary(digest));
    }
}
 
Example 11
Project: emr-nlp-server   File: AuthFilter.java   View source code 6 votes vote down vote up
public static String[] decode(String auth) {
    //Replacing "Basic THE_BASE_64" to "THE_BASE_64" directly
    auth = auth.replaceFirst("[B|b]asic ", "");
 
    //Decode the Base64 into byte[]
    byte[] decodedBytes = DatatypeConverter.parseBase64Binary(auth);
 
    //If the decode fails in any case
    if(decodedBytes == null || decodedBytes.length == 0){
        return null;
    }
 
    //Now split the byte[] into an array :
    //  - the first one is login,
    //  - the second one password
    return new String(decodedBytes).split(":", 2);
}
 
Example 12
Project: IO   File: CompressionTask.java   View source code 6 votes vote down vote up
/**
   * Testing method for decompression of ewf file hex bytes
   * @param ewfHexStr any zlib compressed hex
   * @return decompressed string
   */
  protected static String decompress(String ewfHexStr) {
Inflater inflater = new Inflater();
byte[] input = DatatypeConverter.parseHexBinary(ewfHexStr);
inflater.setInput(input, 0, input.length);
String outputString = "empty";

byte[] result = new byte[input.length];
int resultLength;
try {
	resultLength = inflater.inflate(result);
	outputString = new String(result, 0, resultLength, "UTF-8");
} catch (DataFormatException | UnsupportedEncodingException e) {
	e.printStackTrace();
}
inflater.end();

return outputString;
  }
 
Example 13
Project: openjdk-jdk10   File: CipherStreamClose.java   View source code 6 votes vote down vote up
public static byte[] streamEncrypt(String message, SecretKey key,
    MessageDigest digest)
    throws Exception {

    byte[] data;
    Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    encCipher.init(Cipher.ENCRYPT_MODE, key);
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DigestOutputStream dos = new DigestOutputStream(bos, digest);
        CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
        try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
            oos.writeObject(message);
        }
        data = bos.toByteArray();
    }

    if (debug) {
        System.out.println(DatatypeConverter.printHexBinary(data));
    }
    return data;
}
 
Example 14
Project: oscm   File: AssertionContentVerifier.java   View source code 6 votes vote down vote up
/**
 * Verify that the NotOnOrAfter attribute in any bearer
 * <SubjectConfirmationData> has not passed, subject to allowable clock skew
 * between the providers
 * 
 * @throws AssertionValidationException
 */
void verifyAssertionExpirationDate(Node nodeAssertion,
        Node nodeConfirmationData) throws AssertionValidationException {

    Calendar expirationDate = DatatypeConverter.parseDateTime(XMLConverter
            .getStringAttValue(nodeConfirmationData,
                    SamlXmlTags.ATTRIBUTE_NOT_ON_OR_AFTER));
    if (now.equals(expirationDate) || now.after(expirationDate)) {
        String assertionId = XMLConverter.getStringAttValue(nodeAssertion,
                SamlXmlTags.ATTRIBUTE_ID);
        AssertionValidationException exception = new AssertionValidationException(
                String.format("Assertion (id=%s) expired", assertionId),
                AssertionValidationException.ReasonEnum.ASSERTION_EXPIRED,
                new String[] { assertionId });
        throw exception;
    }
}
 
Example 15
Project: Richkware-Manager-Client   File: Crypto.java   View source code 6 votes vote down vote up
public static String EncryptAES(String input, SecretKey key) throws CryptoException {
    // encode input
    input = DatatypeConverter.printBase64Binary(input.getBytes());

    byte[] ciphertext = null;
    try {
        ciphertext = AES.encrypt(input.getBytes(), key);
    } catch (Exception e) {
        throw new CryptoException(e);
    }


    // encode encrypted input
    //return DatatypeConverter.printBase64Binary(ciphertext.getBytes());
    return DatatypeConverter.printHexBinary(ciphertext);
}
 
Example 16
Project: storm-dynamic-spout   File: ZookeeperWatchTrigger.java   View source code 6 votes vote down vote up
/**
 * Using a filter chain step, make some JSON out of it and then hash it to create an idempotent identifier.
 * @param triggerEvent Trigger event that contains metadata about the request
 * @param step The FilterChainStep that we are going to generate the request from
 * @return A sideline request identifier for the filter chain step
 * @throws NoSuchAlgorithmException Your java install is whack yo, it's missing MD5, for realz???
 */
private SidelineRequestIdentifier generateSidelineRequestIdentifier(
    final TriggerEvent triggerEvent,
    final FilterChainStep step
) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    final String json = gson.toJson(step);

    final StringBuilder identifier = new StringBuilder(
        DatatypeConverter.printHexBinary(MessageDigest.getInstance("MD5").digest(json.getBytes("UTF-8")))
    );

    // If we were provided a date time in the event, append the time stamp of that event to the identifier
    if (triggerEvent.getCreatedAt() != null) {
        identifier.append("-");
        identifier.append(
            triggerEvent.getCreatedAt().atZone(ZoneOffset.UTC).toInstant().toEpochMilli()
        );
    }

    return new SidelineRequestIdentifier(identifier.toString());
}
 
Example 17
Project: osc-core   File: BackupFileServiceTest.java   View source code 6 votes vote down vote up
@Test
public void testExec_withValidKeyStoreProperties_ProperlyEncodesBackup() throws Exception {
	// Arrange.
	TestBackupFileServiceRequest testRequest = new TestBackupFileServiceRequest();

       SecretKey secretKey = generateTestSecretKey();
       KeyStoreProvider.getInstance().putSecretKey(BACKUP_KEY_ALIAS, secretKey, BACKUP_KEY_PASSWORD);
       String ivHex = generateTestIVHex();
       KeyStoreProvider.getInstance().putPassword(BACKUP_IV_ALIAS, ivHex, BACKUP_IV_PASSWORD);

	// Act.
	TestBackupFileServiceResponse response = this.target.exec(testRequest, this.em);

	// Assert.
	assertEquals(secretKey, response.key);
	assertEquals(ivHex, DatatypeConverter.printHexBinary(response.iv));
}
 
Example 18
Project: phone-simulator   File: DiameterIdentityImpl.java   View source code 5 votes vote down vote up
@Override
public void read(javolution.xml.XMLFormat.InputElement xml, DiameterIdentityImpl diameterIdentity)
        throws XMLStreamException {
    String s = xml.getAttribute(DATA, DEFAULT_VALUE);
    if (s != null) {
        diameterIdentity.data = DatatypeConverter.parseHexBinary(s);
    }
}
 
Example 19
Project: phone-simulator   File: DiameterIdentityImpl.java   View source code 5 votes vote down vote up
@Override
public void write(DiameterIdentityImpl diameterIdentity, javolution.xml.XMLFormat.OutputElement xml)
        throws XMLStreamException {
    if (diameterIdentity.data != null) {
        xml.setAttribute(DATA, DatatypeConverter.printHexBinary(diameterIdentity.data));
    }
}
 
Example 20
Project: openjdk-jdk10   File: HttpTransportPipe.java   View source code 5 votes vote down vote up
private void addBasicAuth(Packet context, Map<String, List<String>> reqHeaders) {
    String user = (String) context.invocationProperties.get(BindingProvider.USERNAME_PROPERTY);
    if (user != null) {
        String pw = (String) context.invocationProperties.get(BindingProvider.PASSWORD_PROPERTY);
        if (pw != null) {
            StringBuilder buf = new StringBuilder(user);
            buf.append(":");
            buf.append(pw);
            String creds = DatatypeConverter.printBase64Binary(buf.toString().getBytes());
            reqHeaders.put("Authorization", Collections.singletonList("Basic "+creds));
        }
    }
}
 
Example 21
Project: phone-simulator   File: TAIdImpl.java   View source code 5 votes vote down vote up
@Override
public void read(javolution.xml.XMLFormat.InputElement xml, TAIdImpl taId) throws XMLStreamException {
    String s = xml.getAttribute(DATA, DEFAULT_VALUE);
    if (s != null) {
        taId.data = DatatypeConverter.parseHexBinary(s);
    }
}
 
Example 22
Project: mybatis-generator-plugin   File: TemplateCommentGenerator.java   View source code 5 votes vote down vote up
private String getGeneratedAnnotation(String comment) {
    StringBuilder buffer = new StringBuilder();
    buffer.append("@Generated("); //$NON-NLS-1$
    if (suppressAllComments) {
        buffer.append('\"');
    } else {
        buffer.append("value=\""); //$NON-NLS-1$
    }

    buffer.append(MyBatisGenerator.class.getName());
    buffer.append('\"');

    if (!suppressDate && !suppressAllComments) {
        buffer.append(", date=\""); //$NON-NLS-1$
        buffer.append(DatatypeConverter.printDateTime(Calendar.getInstance()));
        buffer.append('\"');
    }

    if (!suppressAllComments) {
        buffer.append(", comments=\""); //$NON-NLS-1$
        buffer.append(comment);
        buffer.append('\"');
    }

    buffer.append(')');
    return buffer.toString();
}
 
Example 23
Project: athena   File: IsisUtil.java   View source code 5 votes vote down vote up
/**
 * Converts a number to four bytes.
 *
 * @param numberToConvert number to convert
 * @return numInBytes given number as bytes
 */
public static byte[] convertToFourBytes(int numberToConvert) {
    byte[] numInBytes = new byte[4];
    String s1 = Integer.toHexString(numberToConvert);
    if (s1.length() % 2 != 0) {
        s1 = "0" + s1;
    }
    byte[] hexas = DatatypeConverter.parseHexBinary(s1);
    if (hexas.length == 1) {
        numInBytes[0] = 0;
        numInBytes[1] = 0;
        numInBytes[2] = 0;
        numInBytes[3] = hexas[0];
    } else if (hexas.length == 2) {
        numInBytes[0] = 0;
        numInBytes[1] = 0;
        numInBytes[2] = hexas[0];
        numInBytes[3] = hexas[1];
    } else if (hexas.length == 3) {
        numInBytes[0] = 0;
        numInBytes[1] = hexas[0];
        numInBytes[2] = hexas[1];
        numInBytes[3] = hexas[2];
    } else {
        numInBytes[0] = hexas[0];
        numInBytes[1] = hexas[1];
        numInBytes[2] = hexas[2];
        numInBytes[3] = hexas[3];
    }
    return numInBytes;
}
 
Example 24
Project: Richkware-Manager-Client   File: RSA.java   View source code 5 votes vote down vote up
public static String sign(byte[] plainText, PrivateKey privateKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    Signature privateSignature = Signature.getInstance(signVerifyAlgorithm);
    privateSignature.initSign(privateKey);
    privateSignature.update(plainText);

    return DatatypeConverter.printBase64Binary(privateSignature.sign());
}
 
Example 25
Project: phone-simulator   File: CUGInterlockImpl.java   View source code 5 votes vote down vote up
@Override
public void read(javolution.xml.XMLFormat.InputElement xml, CUGInterlockImpl cugInterlock) throws XMLStreamException {
    String s = xml.getAttribute(DATA, DEFAULT_VALUE);
    if (s != null) {
        cugInterlock.data = DatatypeConverter.parseHexBinary(s);
    }
}
 
Example 26
Project: athena   File: OspfUtil.java   View source code 5 votes vote down vote up
/**
 * Converts a number to four bytes.
 *
 * @param numberToConvert number to convert
 * @return given number as bytes
 */
public static byte[] convertToFourBytes(int numberToConvert) {

    byte[] numInBytes = new byte[4];
    String s1 = Integer.toHexString(numberToConvert);
    if (s1.length() % 2 != 0) {
        s1 = "0" + s1;
    }
    byte[] hexas = DatatypeConverter.parseHexBinary(s1);
    if (hexas.length == 1) {
        numInBytes[0] = 0;
        numInBytes[1] = 0;
        numInBytes[2] = 0;
        numInBytes[3] = hexas[0];
    } else if (hexas.length == 2) {
        numInBytes[0] = 0;
        numInBytes[1] = 0;
        numInBytes[2] = hexas[0];
        numInBytes[3] = hexas[1];
    } else if (hexas.length == 3) {
        numInBytes[0] = 0;
        numInBytes[1] = hexas[0];
        numInBytes[2] = hexas[1];
        numInBytes[3] = hexas[2];
    } else {
        numInBytes[0] = hexas[0];
        numInBytes[1] = hexas[1];
        numInBytes[2] = hexas[2];
        numInBytes[3] = hexas[3];
    }
    return numInBytes;
}
 
Example 27
Project: avr-bootloader   File: StrUtils.java   View source code 5 votes vote down vote up
public static byte[] hexStringToBytes(String text) {
    text = text.replace(" ", "");
    if (text.length() % 2 == 1) {
        text = text.substring(0, text.length() - 1) + "0" + text.charAt(text.length() - 1);
    }
    return DatatypeConverter.parseHexBinary(text);
}
 
Example 28
Project: kms-jwt   File: JWTEncoder.java   View source code 5 votes vote down vote up
public static JwtBuilder builder(KeyEncrypt keyEncrypt) throws KeyOperationException {
    SecretKey secretKey = MacProvider.generateKey(SignatureAlgorithm.HS256);
    byte[] encryptedKey = keyEncrypt.encrypt(secretKey.getEncoded());

    return Jwts.builder()
            .setHeaderParam("kid", DatatypeConverter.printBase64Binary(encryptedKey))
            .signWith(SignatureAlgorithm.HS256, secretKey);
}
 
Example 29
Project: spanner-jdbc   File: AbstractSpannerExpressionVisitorAdapter.java   View source code 5 votes vote down vote up
@Override
public void visit(HexValue value)
{
	String stringValue = value.getValue().substring(2);
	byte[] byteValue = DatatypeConverter.parseHexBinary(stringValue);
	setValue(byteValue);
}
 
Example 30
Project: spanner-jdbc   File: DMLTester.java   View source code 5 votes vote down vote up
@SuppressWarnings("deprecation")
private void verifyTableContentsAfterUpdate() throws SQLException
{
	verifyTableContents("SELECT UUID FROM TEST WHERE ID=1", DatatypeConverter.parseHexBinary("aabbcc"));
	verifyTableContents("SELECT ACTIVE FROM TEST WHERE ID=1", Boolean.FALSE);
	verifyTableContents("SELECT AMOUNT FROM TEST WHERE ID=1", Double.valueOf(129.95d));

	verifyTableContents("SELECT AMOUNT FROM TEST WHERE ID=2", Double.valueOf(-129.95d));
	verifyTableContents("SELECT CREATED_DATE FROM TEST WHERE ID=2", new Date(2017 - 1900, 1, 17));
	verifyTableContents("SELECT LAST_UPDATED FROM TEST WHERE ID=2", new Timestamp(2017 - 1900, 1, 17, 8, 0, 0, 0));
}
 
Example 31
Project: ramus   File: Options.java   View source code 5 votes vote down vote up
public static void setStroke(String name, Stroke stroke) {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        DataSaver.saveStroke(os, stroke, new DataLoader.MemoryData());
        setString(name, DatatypeConverter.printHexBinary(os.toByteArray()));
    } catch (IOException e) {
    }
}
 
Example 32
Project: wherehowsX   File: SchemaId.java   View source code 5 votes vote down vote up
/**
 * convert String id into ByteBuffer
 * @param type
 * @param id String
 * @return byte[]
 */
public static byte[] getIdBytes(Type type, String id) {
  if (type == Type.INT) {
    return ByteBuffer.allocate(Type.INT.size).putInt(Integer.parseInt(id)).array();
  } else if (type == Type.LONG) {
    return ByteBuffer.allocate(Type.LONG.size).putLong(Long.parseLong(id)).array();
  } else if (type == Type.UUID) {
    return DatatypeConverter.parseHexBinary(id);
  } else {
    return new byte[0];
  }
}
 
Example 33
Project: pac4j-plus   File: CasClientTests.java   View source code 5 votes vote down vote up
private String deflateAndBase64(final String data) {
    try {
        final Deflater deflater = new Deflater();
        deflater.setInput(data.getBytes(HttpConstants.UTF8_ENCODING));
        deflater.finish();
        final byte[] buffer = new byte[data.length()];
        final int resultSize = deflater.deflate(buffer);
        final byte[] output = new byte[resultSize];
        System.arraycopy(buffer, 0, output, 0, resultSize);
        return DatatypeConverter.printBase64Binary(output);
    } catch (final UnsupportedEncodingException e) {
        throw new RuntimeException("Cannot find encoding:" + HttpConstants.UTF8_ENCODING, e);
    }
}
 
Example 34
Project: incubator-netbeans   File: ProxyPreferencesImpl.java   View source code 5 votes vote down vote up
@Override
public byte[] getByteArray(String key, byte[] def) {
    String value = get(key, null);
    if (value != null) {
        byte [] decoded = DatatypeConverter.parseBase64Binary(value);
        if (decoded != null) {
            return decoded;
        }
    }
    return def;
}
 
Example 35
Project: rapidminer   File: DefaultLicenseManager.java   View source code 5 votes vote down vote up
private final LicenseStatus verifyProduct(Product product) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {
    if(product.isExtension() && product.getProductId().startsWith("rapidminer-")) {
        return LicenseStatus.WRONG_PRODUCT_ID;
    } else {
        Signature rsaSignature = Signature.getInstance("SHA1withRSA");
        rsaSignature.initVerify(this.publicKey);
        rsaSignature.update(product.createBase64Representation().getBytes(StandardCharsets.UTF_8));
        return rsaSignature.verify(DatatypeConverter.parseBase64Binary(product.getSignature()))?LicenseStatus.VALID:LicenseStatus.SIGNATURE_INVALID;
    }
}
 
Example 36
Project: MonitorYourLAN   File: NetworkTest.java   View source code 5 votes vote down vote up
@Test
public void testconvertImageToBase64()
{
	System.out.println("\n   testconvertImageToBase64()");
	
	String encodedImage = null;		
	Network TempNetwork = new Network ();
	
	encodedImage = TempNetwork.convertImageToBase64("");		
	DatatypeConverter.parseBase64Binary(encodedImage);	
	
}
 
Example 37
Project: xrd4j   File: MessageHelper.java   View source code 5 votes vote down vote up
/**
 * Encodes the given image to a base64 coded string.
 *
 * @param image image to encode
 * @param type type of the image: jpeg, bmp, png, gif etc.
 * @return encoded string
 */
public static String encodeImg2String(BufferedImage image, String type) {
    String imageString = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        ImageIO.write(image, type, bos);
        byte[] imageBytes = bos.toByteArray();
        imageString = DatatypeConverter.printBase64Binary(imageBytes);
        bos.close();
    } catch (IOException ex) {
        LOGGER.error(ex.getMessage(), ex);
    }
    return imageString;
}
 
Example 38
Project: SkinFixer   File: SkinConfig.java   View source code 5 votes vote down vote up
public JsonElement toJson(String uuid, String username, String skinUrl, String capeUrl) {
    // Lets add all the information in case the game really needs them

    JsonObject tex = new JsonObject();

    if(skinUrl != null && !skinUrl.isEmpty()) {
        JsonObject skin = new JsonObject();
        skin.addProperty("url", skinUrl);
        tex.add("SKIN", skin);
    }

    if(capeUrl != null && !capeUrl.isEmpty()) {
        JsonObject cape = new JsonObject();
        cape.addProperty("url", capeUrl);
        tex.add("CAPE", cape);
    }

    JsonObject textures = new JsonObject();
    textures.addProperty("timestamp", (int)(System.currentTimeMillis() / 1000L));
    textures.addProperty("profileId", uuid);
    textures.addProperty("profileName", username);
    textures.add("textures", tex);

    JsonObject property = new JsonObject();
    property.addProperty("name", "textures");
    property.addProperty("value", DatatypeConverter.printBase64Binary(textures.toString().getBytes()));

    JsonArray properties = new JsonArray();
    properties.add(property);

    JsonObject obj = new JsonObject();
    obj.addProperty("id", uuid);
    obj.addProperty("name", username);
    obj.add("properties", properties);

    return obj;
}
 
Example 39
Project: BadIntent   File: ParcelByteArrDetails.java   View source code 5 votes vote down vote up
public ArrayList getByteArrayList(){
    String hexStr = this.byteArray.getText().replace(" ", "");
    byte[] bytes = DatatypeConverter.parseHexBinary(hexStr);
    ArrayList doubleArrayList = new ArrayList();
    for (byte byteVal : bytes){
        doubleArrayList.add((double) byteVal);
    }
    return doubleArrayList;
}
 
Example 40
Project: sdk-java-demo   File: Sign.java   View source code 5 votes vote down vote up
public static String digestHex(String str) {
	try {
		MessageDigest md = MessageDigest.getInstance("SHA-512");
		byte[] data = md.digest(str.getBytes());
		return DatatypeConverter.printHexBinary(data);
	} catch (NoSuchAlgorithmException e) {
		throw new RuntimeException(e);
	}
}