decision making in java - java

private Object artikanID(String string) {
try {
DAOTerjemah dao = new DAOTerjemah(ConnectionDB.getConnection()) {};
List<Kata> terjemahan1 = new ArrayList<Kata>();
List<Kata> terjemahan2 = new ArrayList<Kata>();
List<Kata> terjemahan3 = new ArrayList<Kata>();
terjemahan1 = dao.getByIndo(string);
terjemahan2 = dao.getByIndo(string.substring(0,string.length()-1));
terjemahan3 = dao.getByIndo(string.substring(0,string.length()-2));
if (terjemahan1 == null) {
return terjemahan1.get(0).getDayak();
}
else {
return terjemahan2.get(0).getDayak();
}
}catch(Exception e){
return string ;
}
}
there are 3 conditions(terjemahan1,terjemahan2 & terjemahan 3),
how to create the conditions to be executed terjemahan3 ?

With an else, but I'm not entirely sure I understand your logic.
if (terjemahan1 == null) {
return terjemahan1.get(0).getDayak();
}
else if (terjemahan2 == null) {
return terjemahan2.get(0).getDayak();
}
else {
return terjemahan3.get(0).getDayak();
}
I think you probably want the opposite though, so you only call this on variables that are not null. In this case you have to decide which one you want to call in preference if they are all not null. Also you have to decide what to do if all of them are null.
if (terjemahan1 != null) {
return terjemahan1.get(0).getDayak();
}
else if (terjemahan2 != null) {
return terjemahan2.get(0).getDayak();
}
else if (terjemahan3 != null) {
return terjemahan3.get(0).getDayak();
}
else
{
// decide what to do in this condition
}

Related

How write test case for gatewayreasoncode to verify reason code is actually truncated in the test

How write test case for gatewayreasoncode to verify reason code is actually truncated in the test.
public String actionAndReturnRefundIdIfGenerated(TransactionReconciliationEventVO vo) {
Payment payment = paymentManager.get(vo.getZRelatedObjectId());
// Update payment object
if (payment.getGatewayState() == GatewayState.Submitted) {
payment.setGatewayState(GatewayState.Settled);
if (StringUtils.isNotEmpty(vo.getGatewayReconciliationStatus())) {
payment.setGatewayReconciliationStatus(vo.getGatewayReconciliationStatus());
}
if (StringUtils.isNotEmpty(vo.getGatewayReconciliationReason())) {
payment.setGatewayReconciliationReason(vo.getGatewayReconciliationReason());
}
if (StringUtils.isNotEmpty(vo.getPayoutId())) {
payment.setPayoutId(vo.getPayoutId());
}
paymentManager.saveSimpleObjectWithSystemInfo(payment);
}
// Update Payment Method related object
if (sessionManager.getUserSession().hasPermission(ApplicationPermission.AutoPayTurnOffOnRejectionOrReversal) && payment.getBillingAccount()
.getAutoPay()) {
payment.getBillingAccount().setAutoPay(false);
billingAccountManager.saveSimpleObjectWithSystemInfo(payment.getBillingAccount());
}
if (sessionManager.getUserSession().hasPermission(ApplicationPermission.disableGenerateRefundForGRReversalEvent)) {
return null;
}
RefundForPaymentReconciliationVO refundForPaymentReconciliationVO = new RefundForPaymentReconciliationVO();
refundForPaymentReconciliationVO.setPaymentId(payment.getId());
refundForPaymentReconciliationVO.setAmount(Decimal.ZERO.equals(vo.getAmount()) ? payment.getPaymentAmount() : vo.getAmount());
refundForPaymentReconciliationVO.setRefundDate(ZDateUtils.today(TzUtils.userTimeZone()));
if (payment.isSettlementSupported()) {
try {
PaymentAccountingTransactionCheckUtils.checkIfRefundLocked(null, refundForPaymentReconciliationVO.getRefundDate(), null,
PaymentAccountingTransactionCheckUtils.OperationType.Create);
} catch (ValidateException ve) {
if (ve.getApiError() != null && ve.getApiError().equals(ApiError.ACCOUNTING_PERIOD_CLOSED)) {
Calendar calendar = Calendar.getInstance(TzUtils.userTimeZone());
calendar.setTime(refundForPaymentReconciliationVO.getRefundDate());
calendar.add(Calendar.MONTH, 1);
refundForPaymentReconciliationVO.setRefundDate(ZDateUtils.dateOf(calendar));
}
}
}
if (payment.getPaymentMethod() != null) {
refundForPaymentReconciliationVO.setPaymentMethodId(payment.getPaymentMethod().getId());
}
refundForPaymentReconciliationVO.setMethodType(payment.getMethodType());
refundForPaymentReconciliationVO.setReferenceId(vo.getCreatedGatewayReferenceId());
refundForPaymentReconciliationVO.setSecondRefundReferenceId(vo.getCreatedGatewaySecondReferenceId());
refundForPaymentReconciliationVO.setReasonCode(ReconciliationServiceConstant.REVERSAL);
refundForPaymentReconciliationVO.setGatewayState(GatewayState.Settled);
refundForPaymentReconciliationVO.setSettledOn(vo.getEventDateTime());
refundForPaymentReconciliationVO.setGatewayReasonCode(truncateGatewayReasonCode(vo.getGatewayReasonCode()));
refundForPaymentReconciliationVO.setGatewayReason(vo.getGatewayReasonMessage());
System.out.println("truncateGatewayReasonCode(vo.getGatewayReasonCode()... "+truncateGatewayReasonCode(vo.getGatewayReasonCode()));
return arGatewayIntegrationService.createRefundForPaymentReconciliation(refundForPaymentReconciliationVO);
}

How to shorten the condition code ? (JAV, Check null)

I use it to check for null.DataSet has a structure of both String Integer and Bigdecimal data types.
How to shorten the condition code? Is there any way? To shorten my code. Thank you.
public void ConfrimData(DataSet data) {
if (StringUtils.isEmpty(data.getA())
|| StringUtils.isEmpty(data.getB())
|| StringUtils.isEmpty(data.getC())
|| StringUtils.isEmpty(data.getD())
|| StringUtils.isEmpty(data.getE())
|| StringUtils.isEmpty(data.getF())
){
if (StringUtils.isEmpty(data.getA())) {
loggerTransaction.info(Var.VALUE_A);
}
if (StringUtils.isEmpty(data.getB())) {
loggerTransaction.info(Var.VALUE_B);
}
if (StringUtils.isEmpty(data.getC())) {
loggerTransaction.info(Var.VALUE_C);
}
if (StringUtils.isEmpty(data.getD())) {
loggerTransaction.info(Var.VALUE_D);
}
if (StringUtils.isEmpty(data.getE())) {
loggerTransaction.info(Var.VALUE_E);
}
if (StringUtils.isEmpty(data.getF())) {
loggerTransaction.info(Var.VALUE_F);
}
return;
}
_DataSet
private String A = null;
private Integer B = null;
private String C= null;
private String D = null;
private BigDecimal E= null;
private String F= null;
Well, you could make it slightly less repeaty using streams, but it won't make it necessarily better, let alone faster:
LinkedHashMap<Supplier, String> map = new LinkedHashMap<>();
map.put(data::getA, Var.VALUE_A);
map.put(data::getB, Var.VALUE_B);
map.put(data::getC, Var.VALUE_C);
map.put(data::getD, Var.VALUE_D);
map.put(data::getE, Var.VALUE_E);
map.put(data::getF, Var.VALUE_F);
List<String> logMessages = map.entrySet().stream()
.filter(entry -> StringUtils.isEmpty(entry.getKey().get()))
.map(Map.Entry::getValue)
.collect(Collectors.toList());
if (!logMessages.isEmpty()) {
logMessages.forEach(loggerTransaction::info);
}
else {
// Remaining code
}
In your first if statement you check all the parameters to see if any of them are empty.
Then, in the inner if statements, you check them again. The first check is redundant. The return statement is also not necessary since it does not end the method early or returns any data.
Here is a shorter version that should give the same result:
public void confirmData(DataSet data) {
if (StringUtils.isEmpty(data.getA())) {
loggerTransaction.info(Var.VALUE_A);
}
if (StringUtils.isEmpty(data.getB())) {
loggerTransaction.info(Var.VALUE_B);
}
if (StringUtils.isEmpty(data.getC())) {
loggerTransaction.info(Var.VALUE_C);
}
if (StringUtils.isEmpty(data.getD())) {
loggerTransaction.info(Var.VALUE_D);
}
if (StringUtils.isEmpty(data.getE())) {
loggerTransaction.info(Var.VALUE_E);
}
if (StringUtils.isEmpty(data.getF())) {
loggerTransaction.info(Var.VALUE_F);
}
}
EDIT
Here is a slightly prettier solution with less code repetition:
public void confirmData(DataSet data) {
logIfEmpty(data.getA(), Var.VALUE_A);
logIfEmpty(data.getB(), Var.VALUE_B);
logIfEmpty(data.getC(), Var.VALUE_C);
logIfEmpty(data.getD(), Var.VALUE_D);
logIfEmpty(data.getE(), Var.VALUE_E);
logIfEmpty(data.getF(), Var.VALUE_F);
}
private void logIfEmpty(Object check, String log) {
if (StringUtils.isEmpty(check)) {
loggerTransaction.info(log);
}
}
EDIT #2
And if you have other code you want to execute if you did not find any empty values, you can do this:
public void confirmData(DataSet data) {
boolean foundEmpty;
foundEmpty = logIfEmpty(data.getA(), Var.VALUE_A);
foundEmpty = logIfEmpty(data.getB(), Var.VALUE_B) || foundEmpty;
foundEmpty = logIfEmpty(data.getC(), Var.VALUE_C) || foundEmpty;
foundEmpty = logIfEmpty(data.getD(), Var.VALUE_D) || foundEmpty;
foundEmpty = logIfEmpty(data.getE(), Var.VALUE_E) || foundEmpty;
foundEmpty = logIfEmpty(data.getF(), Var.VALUE_F) || foundEmpty;
if(foundEmpty) {
return;
}
}
private boolean logIfEmpty(String check, String log) {
if (StringUtils.isEmpty(check)) {
loggerTransaction.info(log);
return true;
}
return false;
}
Maybe assigning a flag...
public void ConfrimData(DataSet data) {
boolean flag;
if (flag = StringUtils.isEmpty(data.getA())) {
loggerTransaction.info(Var.VALUE_A);
}
if (flag = StringUtils.isEmpty(data.getB()) || flag) {
loggerTransaction.info(Var.VALUE_B);
}
if (flag = StringUtils.isEmpty(data.getC()) || flag) {
loggerTransaction.info(Var.VALUE_C);
}
if (flag = StringUtils.isEmpty(data.getD()) || flag) {
loggerTransaction.info(Var.VALUE_D);
}
if (flag = StringUtils.isEmpty(data.getE()) || flag) {
loggerTransaction.info(Var.VALUE_E);
}
if (flag = StringUtils.isEmpty(data.getF()) || flag) {
loggerTransaction.info(Var.VALUE_F);
}
if (flag) return;

Common method for null check

I want to create a common method which will check for null on primary keys of database tables.
I have two type of datatype
String
Date
Want to create a common function which will take parameters on the run time and check for null.
Table 1:
private boolean checkForNullEntries(Table1 table1) {
if (StringUtil.isNullOrEmpty(table1.getName())) {
return true;
} else if (table1.getLastUpdateTime() == null) {
return true;
}
return false;
}
public checkIfPrimaryKeyIsNull(Table1 table1) {
boolean nullValueFound = checkForNullEntries(table1);
if (nullValueFound) {
//skip db operation
} else {
// save to DB
}
}
Table 2:
private boolean checkForNullEntries(Table2 table2) {
if (table2.getTimeSlot == null) {
return true;
} else if (table2.getDate() == null) {
return true;
}
return false;
}
public checkIfPrimaryKeyIsNull(Table2 table2) {
boolean nullValueFound = checkForNullEntries(table2);
if (nullValueFound){
//skip db operation
} else {
// save to DB
}
}
I want to create a common method for both the tables. Any suggestion experts
Using a Map, you should be able to pass any table to the functions, regardless of the data type you wanna test, and then establish each test case in a different 'if', as follows:
private static boolean checkForNullEntries(Map<String, Table> map) {
if(map.get("String") != null) {
if (StringUtil.isNullOrEmpty(map.get("String").getName())) {
return true;
} else if (map.get("String").getLastUpdateTime() == null) {
return true;
}
return false;
}
if(map.get("Date") != null) {
if (map.get("Date").getTimeSlot == null) {
return true;
} else if (map.get("Date").getDate() == null) {
return true;
}
return false;
}
return false;
}
Then you can call the function like this:
Map<String, Table> map = new HashMap<>();
map.put("Date", table2);
boolean result = checkForNullEntries(map);

Add words to languagetool suggesting list

I use LanguageTool for some spellchecking and spell correction functionality in my application.
The LanguageTool documentation describes how to exclude words from spell checking (with call the addIgnoreTokens(...) method of the spell checking rule you're using).
How do you add some words (e.g., from a specific dictionary) to spell checking? That is, can LanguageTool fix words with misspellings and suggest words from my specific dictionary?
Unfortunately, the API doesn't support this I think. Without the API, you can add words to spelling.txt to get them accepted and used as suggestions. With the API, you might need to extend MorfologikSpellerRule and change this place of the code. (Disclosure: I'm the maintainer of LanguageTool)
I have similar requirement, which is load some custom words into dictionary as "suggest words", not just "ignored words". And finally I extend MorfologikSpellerRule to do this:
Create class MorfologikSpellerRuleEx extends from MorfologikSpellerRule, override the method "match()", and write my own "initSpeller()" for creating spellers.
And then for the language tool, create this custom speller rule to replace existing one.
Code:
Language lang = new AmericanEnglish();
JLanguageTool langTool = new JLanguageTool(lang);
langTool.disableRule("MORFOLOGIK_RULE_EN_US");
try {
MorfologikSpellerRuleEx spellingRule = new MorfologikSpellerRuleEx(JLanguageTool.getMessageBundle(), lang);
spellingRule.setSpellingFilePath(spellingFilePath);
//spellingFilePath is the file has my own words + words from /hunspell/spelling_en-US.txt
langTool.addRule(spellingRule);
} catch (IOException e) {
e.printStackTrace();
}
The code of my custom MorfologikSpellerRuleEx:
public class MorfologikSpellerRuleEx extends MorfologikSpellerRule {
private String spellingFilePath = null;
private boolean ignoreTaggedWords = false;
public MorfologikSpellerRuleEx(ResourceBundle messages, Language language) throws IOException {
super(messages, language);
}
#Override
public String getFileName() {
return "/en/hunspell/en_US.dict";
}
#Override
public String getId() {
return "MORFOLOGIK_SPELLING_RULE_EX";
}
#Override
public void setIgnoreTaggedWords() {
ignoreTaggedWords = true;
}
public String getSpellingFilePath() {
return spellingFilePath;
}
public void setSpellingFilePath(String spellingFilePath) {
this.spellingFilePath = spellingFilePath;
}
private void initSpellerEx(String binaryDict) throws IOException {
String plainTextDict = null;
if (JLanguageTool.getDataBroker().resourceExists(getSpellingFileName())) {
plainTextDict = getSpellingFileName();
}
if (plainTextDict != null) {
BufferedReader br = null;
if (this.spellingFilePath != null) {
try {
br = new BufferedReader(new FileReader(this.spellingFilePath));
}
catch (Exception e) {
br = null;
}
}
if (br != null) {
speller1 = new MorfologikMultiSpeller(binaryDict, br, plainTextDict, 1);
speller2 = new MorfologikMultiSpeller(binaryDict, br, plainTextDict, 2);
speller3 = new MorfologikMultiSpeller(binaryDict, br, plainTextDict, 3);
br.close();
}
else {
speller1 = new MorfologikMultiSpeller(binaryDict, plainTextDict, 1);
speller2 = new MorfologikMultiSpeller(binaryDict, plainTextDict, 2);
speller3 = new MorfologikMultiSpeller(binaryDict, plainTextDict, 3);
}
setConvertsCase(speller1.convertsCase());
} else {
throw new RuntimeException("Could not find ignore spell file in path: " + getSpellingFileName());
}
}
private boolean canBeIgnored(AnalyzedTokenReadings[] tokens, int idx, AnalyzedTokenReadings token)
throws IOException {
return token.isSentenceStart() || token.isImmunized() || token.isIgnoredBySpeller() || isUrl(token.getToken())
|| isEMail(token.getToken()) || (ignoreTaggedWords && token.isTagged()) || ignoreToken(tokens, idx);
}
#Override
public RuleMatch[] match(AnalyzedSentence sentence) throws IOException {
List<RuleMatch> ruleMatches = new ArrayList<>();
AnalyzedTokenReadings[] tokens = getSentenceWithImmunization(sentence).getTokensWithoutWhitespace();
// lazy init
if (speller1 == null) {
String binaryDict = null;
if (JLanguageTool.getDataBroker().resourceExists(getFileName())) {
binaryDict = getFileName();
}
if (binaryDict != null) {
initSpellerEx(binaryDict); //here's the change
} else {
// should not happen, as we only configure this rule (or rather its subclasses)
// when we have the resources:
return toRuleMatchArray(ruleMatches);
}
}
int idx = -1;
for (AnalyzedTokenReadings token : tokens) {
idx++;
if (canBeIgnored(tokens, idx, token)) {
continue;
}
// if we use token.getToken() we'll get ignored characters inside and speller
// will choke
String word = token.getAnalyzedToken(0).getToken();
if (tokenizingPattern() == null) {
ruleMatches.addAll(getRuleMatches(word, token.getStartPos(), sentence));
} else {
int index = 0;
Matcher m = tokenizingPattern().matcher(word);
while (m.find()) {
String match = word.subSequence(index, m.start()).toString();
ruleMatches.addAll(getRuleMatches(match, token.getStartPos() + index, sentence));
index = m.end();
}
if (index == 0) { // tokenizing char not found
ruleMatches.addAll(getRuleMatches(word, token.getStartPos(), sentence));
} else {
ruleMatches.addAll(getRuleMatches(word.subSequence(index, word.length()).toString(),
token.getStartPos() + index, sentence));
}
}
}
return toRuleMatchArray(ruleMatches);
}
}

which is best way to map servlet request parameters to a java class? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Easy way of populating Javabeans based on request parameters
Hi,
I have a Java Object with a set of search parameters, sth. like
public class SearchRequest {
private String customerName;
private String city;
...
}
This request has to be filled by a servet request.
But instead of writing code like
...
SearchRequest searchRequest = new SearchRequest();
if (request.getParameter("customerName") != null)
{
searchRequest.setCustomerName(request.getParameter("customerName"));
}
if (request.getParameter("city") != null)
{
searchRequest.setCity(request.getParameter("city"));
}
...
I'm looking for a more generic way.
I was checking the mapping tool Dozer but did not find a nice way how to handle this mapping.
Now I think reflection would be a choice.
Is this true?
If so does anyone has a code sniplet how this can be done with reflection?
I plead guilty:
public void save(HttpServletRequest req, Object obj) {
Set<String> names = new HashSet<String>();
#SuppressWarnings("unchecked")
Enumeration<String> enm = req.getParameterNames();
while (enm.hasMoreElements()) {
names.add(enm.nextElement());
}
Class clazz = obj.getClass();
while (clazz != Object.class && !names.isEmpty()) {
for (Field f: clazz.getDeclaredFields()) {
if (!Modifier.isTransient(f.getModifiers())) {
String name = f.getName();
if (names.contains(name)) {
try {
names.remove(name);
f.setAccessible(true);
Object val = convertValue(req, f.getType(),
name);
f.set(obj, val);
} catch (ParseException ex) {
LOG.error("Error assigning field", ex);
} catch (IllegalAccessException ex) {
LOG.error("Error assigning field", ex);
}
}
}
}
clazz = clazz.getSuperclass();
}
}
private Object convertValue(HttpServletRequest req, Class<?> type,
String name) throws ParseException {
if (type.isArray()) {
Class<?> elemType = type.getComponentType();
String strings[] = req.getParameterValues(name);
if (strings == null || strings.length == 0) {
return new Object[0];
}
Object array = Array.newInstance(elemType, strings.length);
for (int i = 0; i < strings.length; ++i) {
Object val = parse(elemType, strings[i]);
Array.set(array, i, val);
}
return array;
} else {
String s = req.getParameter(name);
if (s == null) {
return null;
}
return parse(type, s);
}
}
public static Object parse(Class<?> type, String value)
throws ParseException {
if (type == String.class) {
return value;
} else if (value == null || value.length() == 0) {
return null;
} else if (Enum.class.isAssignableFrom(type)) {
#SuppressWarnings("unchecked")
Object result = Enum.valueOf((Class<? extends Enum>)type, value);
return result;
} else if (type == boolean.class || type == Boolean.class) {
return "true".equals(value);
} else if (type == byte.class || type == Byte.class) {
return Byte.valueOf(value);
} else if (type == short.class || type == Short.class) {
return Short.valueOf(value);
} else if (type == int.class || type == Integer.class) {
return Integer.valueOf(value);
} else if (type == long.class || type == Long.class) {
return Long.valueOf(value);
} else if (type == float.class || type == Float.class) {
return Float.valueOf(value);
} else if (type == double.class || type == Double.class) {
return Double.valueOf(value);
} else if (type == Date.class) {
return new SimpleDateFormat("dd/MM/yyyy").parse(value);
} else if (type == BigDecimal.class) {
DecimalFormat format = getDecimalFormat("0.00");
return format.parse(value);
} else {
throw new RuntimeException("Cannot convert value of type " + type);
}
}
private static DecimalFormat getDecimalFormat(String pattern) {
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
DecimalFormat format = new DecimalFormat(pattern);
format.setParseBigDecimal(true);
format.setDecimalFormatSymbols(symbols);
return format;
}

Categories

Resources