use of org.ballerinalang.model.values.BEnumerator in project ballerina by ballerina-lang.
the class GetHmac method execute.
@Override
public void execute(Context context) {
String baseString = context.getStringArgument(0);
String keyString = context.getStringArgument(1);
BEnumerator algorithm = (BEnumerator) context.getRefArgument(0);
String hmacAlgorithm;
// todo document the supported algorithm
switch(algorithm.getName()) {
case "SHA1":
hmacAlgorithm = "HmacSHA1";
break;
case "SHA256":
hmacAlgorithm = "HmacSHA256";
break;
case "MD5":
hmacAlgorithm = "HmacMD5";
break;
default:
throw new BallerinaException("Unsupported algorithm " + algorithm + " for HMAC calculation");
}
String result;
try {
byte[] keyBytes = keyString.getBytes(Charset.defaultCharset());
SecretKey secretKey = new SecretKeySpec(keyBytes, hmacAlgorithm);
Mac mac = Mac.getInstance(hmacAlgorithm);
mac.init(secretKey);
byte[] baseStringBytes = baseString.getBytes(Charset.defaultCharset());
result = HashUtils.toHexString(mac.doFinal(baseStringBytes));
} catch (IllegalArgumentException | InvalidKeyException | NoSuchAlgorithmException e) {
throw new BallerinaException("Error while calculating HMAC for " + hmacAlgorithm + ": " + e.getMessage(), context);
}
context.setReturnValues(new BString(result));
}
use of org.ballerinalang.model.values.BEnumerator in project ballerina by ballerina-lang.
the class ParseTo method execute.
@Override
public void execute(Context context) {
String dateString = context.getStringArgument(0);
BEnumerator pattern = (BEnumerator) context.getRefArgument(0);
TemporalAccessor parsedDateTime;
switch(pattern.getName()) {
case "RFC_1123":
parsedDateTime = DateTimeFormatter.RFC_1123_DATE_TIME.parse(dateString);
break;
default:
throw new BallerinaException("failed to parse date/time string: " + dateString);
}
StructInfo timeZoneStructInfo = Utils.getTimeZoneStructInfo(context);
StructInfo timeStructInfo = Utils.getTimeStructInfo(context);
long epochTime = -1;
String zoneId;
try {
epochTime = Instant.from(parsedDateTime).toEpochMilli();
zoneId = String.valueOf(ZoneId.from(parsedDateTime));
} catch (DateTimeException e) {
if (epochTime < 0) {
throw new BallerinaException("failed to parse \"" + dateString + "\" to the " + pattern.getName() + " format");
}
zoneId = ZoneId.systemDefault().toString();
}
BStruct timeStruct = Utils.createTimeStruct(timeZoneStructInfo, timeStructInfo, epochTime, zoneId);
context.setReturnValues(timeStruct);
}
Aggregations