Go through sub tags of IsoMsg and get values for jPOS - jpos

I have a jPOS project and I want to loop through sub tags of a field to get it's values. I have the following code and I don't know if it does the job:
Map<String, String> subTagMap = new HashMap<>();
ISOMsg champ11 = (ISOMsg)isoMsg.getComponent(11);
int i = 1;
while(i < 15) {
if (champ11 != null) {
ISOTaggedField subtTag = findTag(champ11, (i < 10) ? "0" + i : String.valueOf(i));
if (subtTag != null) {
LOGGER.debug("Champ11x" + i +"trouvé");
subTagMap.put(subtTag.getTag(), subtTag.getValue().toString());
}
}
i++;
}
return subTagMap;
}
private ISOTaggedField findTag(ISOComponent component, String tagName) {
if (component instanceof ISOTaggedField) {
component = ((ISOTaggedField) component).getDelegate();
}
#SuppressWarnings("unchecked")
Map<Integer, Object> children = component.getChildren();
for (Map.Entry<Integer, Object> entry : children.entrySet()) {
if (entry.getValue() instanceof ISOTaggedField) {
ISOTaggedField tag = (ISOTaggedField) entry.getValue();
if (tag.getTag().equals(tagName)) {
return tag;
}
}
}
return null;
}

This should work:
Map<String, String> subTagMap=new HashMap<>();
ISOMsg champ11 = (ISOMsg) isoMsg.getComponent(119);
if (champ != null) {
for (Object v : champ.getChildren().values()) {
if (!(v instanceof ISOTaggedField)) continue;
ISOTaggedField subTag = (ISOTaggedField) v;
subTagMap.put(subTag.getTag(), (String)subTag.getValue());
}
}
return subTagMap;

Related

Are there any Dart resources that would split a command-line String into a List<String> of arguments?

Are there any Dart resources that would split a command-line String into a List<String> of arguments?
ArgsParser takes a List<String> of already split arguments usually from main(List<String>).
To answer my own question,
I've converted a Java function I liked into a Dart Converter<String, List<String>) class:
import 'dart:convert';
/// Splits a `String` into a list of command-line argument parts.
/// e.g. "command -p param" -> ["command", "-p", "param"]
///
class CommandlineConverter extends Converter<String, List<String>>
{
#override
List<String> convert(String input)
{
if (input == null || input.isEmpty)
{
//no command? no string
return [];
}
final List<String> result = new List<String>();
var current = "";
String inQuote;
bool lastTokenHasBeenQuoted = false;
for (int index = 0; index < input.length; index++)
{
final token = input[index];
if (inQuote != null)
{
if (token == inQuote)
{
lastTokenHasBeenQuoted = true;
inQuote = null;
}
else
{
current += token;
}
}
else
{
switch (token)
{
case "'": // '
case '"': // ""
inQuote = token;
continue;
case " ": // space
if (lastTokenHasBeenQuoted || current.isNotEmpty)
{
result.add(current);
current = "";
}
break;
default:
current += token;
lastTokenHasBeenQuoted = false;
}
}
}
if (lastTokenHasBeenQuoted || current.isNotEmpty)
{
result.add(current);
}
if (inQuote != null)
{
throw new Exception("Unbalanced quote $inQuote in input:\n$input");
}
return result;
}
}

How to retrieve filtered value from a stream and use it

I'm new to Java 8:
I have to convert this piece of java 6 code to java 8 version:
List<String> unvalidnumbers = new ArrayList<>();
StringBuilder content = new StringBuilder();
String str = "current_user"
for (Iterator<String> it = numbers.iterator(); it.hasNext();) {
String number = it.next();
try {
PersIdentifier persIdentifier = this.getPersIdentifierByNumber(number);
if (persIdentifier != null) {
content.append(number).append(";").append(str);
if (StringUtils.equals(persIdentifier.getType(), "R")) {
content.append(";X");
}
if (it.hasNext()) {
content.append("\r\n");
}
}
} catch (BusException e) {
LOGGER.warn("Pers not found", e);
unvalidnumbers.add(number);
}
}
So i wrote this:
numbers.stream().filter((String number) -> {
try {
return this.getPersIdentifierByNumber(number) != null;
} catch (BusinessException e1) {
LOGGER.warn("Pers not found", e1);
return false;
}
}).forEach(number -> contentConstruction.append(number).append(";").append(str));
I know it's missing this part:
if (StringUtils.equals(persIdentifier.getType(), "R")) {
content.append(";X");
}
if (it.hasNext()) {
content.append("\r\n");
}
But i didn't found way to retrieve the corresponding persIdentifier object.
Any idea please
You should use a more functional approach if you use Java 8.
Instead of a forEach, favor collect(). Here Collectors.joining() looks suitable.
Not tested but you should have an overall idea :
String result =
numbers.stream()
.map(number -> new SimpleEntry<String, PersIdentifier>(number, this.getPersIdentifierByNumber(number) )
.filter(entry -> entry.getValue() != null)
.map(entry ->{
final String base = entry.getKey() + ";" + str;
return "R".equals(entry.getValue().getType()) ? base + ";X" : base;
})
.collect(joining("\r\n")); // Or not OS dependent : System.lineSeparator()

convert index based for loop in java 8

is it possible to convert below given for loop into java 8 code?
Object[] args = pjp.getArgs();
MethodSignature methodSignature = (MethodSignature) pjp.getStaticPart()
.getSignature();
Method method = methodSignature.getMethod();
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
StringBuilder methodArgs = new StringBuilder();
for (int argIndex = 0; argIndex < args.length; argIndex++) {
for (Annotation annotation : parameterAnnotations[argIndex]) {
if ((annotation instanceof RequestParam) || (annotation instanceof PathVariable) || (annotation instanceof RequestHeader)) {
methodArgs.append(args[argIndex] + "|");
} else if ((annotation instanceof RequestBody)) {
methodArgs.append(mapper.writeValueAsString(args[argIndex]) + "|");
}
}
}
i tried with below given java 8 code. function name is randomly taken
public void some() {
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
Arrays.stream(parameterAnnotations)
.map(f -> asd(f));
}
private Object asd(Annotation[] annotations) {
Arrays.stream(annotations)
.map(a -> change(a)); //here is problem...how i can access args[argIndex]
return null;
}
You'll have to open an InsStream to iterate over the args index, then create a SimpleEntry of each arg with it's corresponding annotaton(acc. to your code), then you can apply your business logic.
IntStream.range(0, args.length)
.mapToObj(argIndex -> new AbstractMap.SimpleEntry<>(args[argIndex], parameterAnnotations[argIndex]))
.flatMap(objectSimpleEntry -> Arrays.stream(objectSimpleEntry.getValue()).map(annotation -> new AbstractMap.SimpleEntry<>(objectSimpleEntry.getKey(), annotation)))
.forEach(objectAnnotationSimpleEntry -> {
Annotation annotation = objectAnnotationSimpleEntry.getValue();
Object arg = objectAnnotationSimpleEntry.getKey();
if ((annotation instanceof RequestParam) || (annotation instanceof PathVariable) || (annotation instanceof RequestHeader)) {
methodArgs.append(arg + "|");
} else if ((annotation instanceof RequestBody)) {
methodArgs.append(arg + "|");
}
});

redisTemplate ValueOperations increment get null

First of all, I have to say that key exists in redis,
This key is a self-increasing sequence,
But sometimes getting this key is null.
I used spring-boot: 2.0.4.0.release
My expectation is to get a self-increment of 1 at a time to generate the order number
Could you advice a solution for my scenario? Thanks!
#Override
#Transactional(rollbackFor = Exception.class)
public boolean paymentBatchMeter(UserDescriptor user, String areaCode, String newPrice) {
List<Meter> meters = meterService.findAllByFilterAndAreaCode(null, areaCode, user);
if (meters != null && meters.size() > 0) {
List<TaskValue> taskValueList = new ArrayList<>();
meters.forEach(meter -> {
if (meter.getState() == 1) {
Task task = new Task();
task.setCode(meter.getCode());
TaskValue taskValue = new TaskValue();
taskValue.setId(task.getId());
taskValue.setMeterType(meter.getMeterDicCode());
taskValue.setCode(meter.getCode());
Long orderIndex = redisTemplate.opsForValue().increment("athena:order:index", 1);
if (orderIndex == null) {
throw new IllegalStateException("error!");
}
taskValueList.add(taskValue);
Order order = new Order();
order.setCustomerId(meter.getCustomerId());
order.setCode(orderIndex.toString());
order.setCreateTime(new Date());
order.setMeterId(meter.getId());
order.setState(0);
order.setRechargeMoney(new BigDecimal(newPrice));
List<DicProjectItem> dicProjectItems = dicProjectItemMapper.getDicProjectItemAll("D10015", 1);
String dicProjectItemId = dicProjectItems.stream().filter(p -> "002".equals(p.getCode())).collect(Collectors.toList()).get(0).getId();
order.setRechargeWayDicId(dicProjectItemId);
order.setRechargeState(1);
order.setTaskId(task.getId());
order.setOperatorId(user.getId());
}
});
redisTemplate.setEnableTransactionSupport(true);
taskValueList.forEach(taskValue -> {
if ("004".equals(taskValue.getMeterType())) {
redisTemplate.convertAndSend(TOPIC, taskValue.getCode());
redisTemplate.opsForList().rightPush("athena:concentrator:meter:task:" + taskValue.getCode(), JSON.toJSONString(taskValue));
} else {
redisTemplate.opsForList().rightPush("athena:meter:task:" + taskValue.getCode(), JSON.toJSONString(taskValue));
}
});
redisTemplate.setEnableTransactionSupport(false);
return true;
}
return false;
}

how to wait for ParseCloud.callFunctionInBackgroud

I have a Utility function which I use to check if user has done few operations or not. If not, Then I need to send the results back to MainActivity.
public static boolean checkUserIsDone(String receiverPhoneNumber, String senderNumber ) {
hasApp = false;
HashMap<String, Object> parseParams = new HashMap<>();
parseParams.put("phoneNumber", receiverPhoneNumber);
parseParams.put("senderNumber", senderNumber);
ParseCloud.callFunctionInBackground("GetUserByPhoneNumber", parseParams, new FunctionCallback<String>() {
public void done(String result, ParseException e) {
if (e == null && result.equals("success")) {
hasApp = true;
} else {
hasApp = false;
Log.e("Error: ", e.getMessage());
}
}
});
return hasApp;
}

Resources