Notes![what is notes.io? What is notes.io?](/theme/images/whatisnotesio.png)
![]() ![]() Notes - notes.io |
* Copyright 2006-2021 HighRadius Corporation
*/
package com.highradius.g4.service.redline.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.highradius.g4.core.common.G4Log;
import com.highradius.g4.core.common.G4LogManager;
import com.highradius.g4.redline.dto.ProjectListDTO;
import com.highradius.g4.redline.dto.ProjectTemplateListDTO;
import com.highradius.g4.redline.dto.SearchDTO;
import com.highradius.g4.redline.dto.UsersListDTO;
import com.highradius.g4.redline.entity.ClosingUnit;
import com.highradius.g4.service.config.APIConstants;
import com.highradius.g4.service.redline.manager.FiscalCalendarManager;
/**
* The Class UserHelper.
*
* @author arun.kumar
*/
@Component
public class Helper {
/** The Constant LOGGER. */
private static final G4Log LOGGER = G4LogManager.getLog(Helper.class);
/** The Constant mapper. */
private static final ObjectMapper mapper = new ObjectMapper();
/**
* Gets the user info by id.
*
* @param ids the ids
* @return the user info by id
*/
public UsersListDTO getUsersById(List<Long> ids) {
LOGGER.debug("Inside getUsersById of Helper");
UsersListDTO usersListDTO = new UsersListDTO();
String url = APIConstants.IAM_SERVICE_HOST + "/user/ids?limit=" + ids.size();
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
URIBuilder builder = new URIBuilder(url);
HttpPost httpPost = new HttpPost(builder.build());
StringEntity entity = new StringEntity(
"{"userList":{"mappedUserIds":" + mapper.writeValueAsString(ids) + "}}");
httpPost.setEntity(entity);
httpPost.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
HttpResponse response = httpClient.execute(httpPost);
String content = EntityUtils.toString(response.getEntity());
httpClient.close();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonParser jp = mapper.getFactory().createParser(content);
JsonNode j = mapper.readTree(jp);
usersListDTO = mapper.convertValue(j.get("userList"), new TypeReference<UsersListDTO>() {
});
} catch (Exception e) {
LOGGER.error(e);
}
return usersListDTO;
}
/**
* Gets the mapped projects.
*
* @param ids the ids
* @return the mapped projects
*/
public ProjectListDTO getMappedProjects(List<Long> ids) {
LOGGER.debug("Inside getMappedProjects of Helper");
ProjectListDTO projectListDTO = new ProjectListDTO();
String url = APIConstants.PMS_SERVICE_HOST + "/project/mapped_projects?limit=" + ids.size();
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
URIBuilder builder = new URIBuilder(url);
HttpPost httpPost = new HttpPost(builder.build());
StringEntity entity = new StringEntity(
"{"project":{"mappedProjects":" + mapper.writeValueAsString(ids) + "}}");
httpPost.setEntity(entity);
httpPost.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
HttpResponse response = httpClient.execute(httpPost);
String content = EntityUtils.toString(response.getEntity());
httpClient.close();
ObjectMapper map1 = new ObjectMapper();
JsonFactory factory1 = map1.getFactory();
JsonParser jp11 = factory1.createParser(content);
JsonNode j1 = map1.readTree(jp11);
projectListDTO = mapper.convertValue(j1.get("ProjectListDTO"), new TypeReference<ProjectListDTO>() {
});
} catch (Exception e) {
LOGGER.error(e);
}
return projectListDTO;
}
/**
* Gets the mapped project templates.
*
* @param ids the ids
* @return the mapped project templates
*/
public ProjectTemplateListDTO getMappedProjectTemplates(List<Long> ids) {
LOGGER.debug("Inside getMappedProjectTemplates of Helper");
ProjectTemplateListDTO projectTemplateListDTO = new ProjectTemplateListDTO();
String url = APIConstants.PMS_SERVICE_HOST + "/template_library?limit=" + ids.size();
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
URIBuilder builder = new URIBuilder(url);
HttpPost httpPost = new HttpPost(builder.build());
StringEntity entity = new StringEntity(
"{"mappedProjectTemplate":{"projectTemplateId":" + mapper.writeValueAsString(ids) + "}}");
httpPost.setEntity(entity);
httpPost.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
HttpResponse response = httpClient.execute(httpPost);
String content = EntityUtils.toString(response.getEntity());
httpClient.close();
ObjectMapper map1 = new ObjectMapper();
JsonFactory factory1 = map1.getFactory();
JsonParser jp11 = factory1.createParser(content);
JsonNode j1 = map1.readTree(jp11);
projectTemplateListDTO = mapper.convertValue(j1.get("projectTemplateList"),
new TypeReference<ProjectTemplateListDTO>() {
});
} catch (Exception e) {
LOGGER.error(e);
}
return projectTemplateListDTO;
}
/**
* Gets the hash map from ids.
*
* @param data the data
* @return the hash map from ids
*/
public HashMap<Long, List<Long>> getHashMapFromIds(List<?> data) {
LOGGER.debug("Inside getHashMapFromIds of Helper");
HashMap<Long, List<Long>> map = new HashMap<Long, List<Long>>();
data.forEach(result -> {
Object[] resultSet = (Object[]) result;
ClosingUnit closingUnit = (ClosingUnit) resultSet[0];
Long cuId = closingUnit.getPkClosingUnitId();
Long id = Long.parseLong(resultSet[1].toString());
List<Long> ids = map.getOrDefault(cuId, new ArrayList<>());
ids.add(id);
map.put(cuId, ids);
});
return map;
}
/**
* Sql query builder closing unit.
*
* @param sortColumn the sort column
* @param sortOrder the sort order
* @param query the query
* @return the string
*/
public String sqlQueryBuilderClosingUnit(String sortColumn, String sortOrder, Map<String, Object> query) {
StringBuilder sqlQuery = new StringBuilder(" from ClosingUnit where accountId=:accountId");
Iterator<Entry<String, Object>> params = query.entrySet().iterator();
while (params.hasNext()) {
Map.Entry<String, Object> ele = params.next();
if (ele.getKey().equals("name")) {
sqlQuery.append(" and " + updateParamsForCriteria(ele.getKey(), ele.getValue()));
}
}
sqlQuery.append(sortQueryBuilder(sortColumn, sortOrder));
return sqlQuery.toString();
}
/**
* Sort query builder.
*
* @param sortColumn the sort column
* @param sortOrder the sort order
* @return the string
*/
public String sortQueryBuilder(String sortColumn, String sortOrder) {
try {
String sortBy = Constants.DEFAULT_SORT_BY;
String sort = Constants.DESC_ORDER;
if (StringUtils.isNotBlank(sortColumn)) {
sortBy = sortColumn;
}
if (StringUtils.isNotBlank(sortOrder)) {
sort = sortOrder;
}
return (" ORDER BY " + sortBy + " " + sort);
} catch (Exception e) {
LOGGER.error("Unable to create sort query");
return null;
}
}
/**
* Update params for criteria.
*
* @param key the key
* @param value the value
* @return the string
*/
public String updateParamsForCriteria(String key, Object value) {
return " " + key + " like CONCAT('%','" + value.toString().replace("'", "") + "','%')";
}
/**
* Gets the current date time.
*
* @return the current date time
*/
public static DateTime getCurrentDateTime() {
return new DateTime().withTimeAtStartOfDay();
}
/**
* Checks if is current date within period.
*
* @param fiscalPeriod the fiscal period
* @return true, if is current date within period
*/
public static boolean isCurrentDateWithinPeriod(FiscalCalendarManager.FiscalPeriod fiscalPeriod) {
DateTime dateTime = new DateTime();
return !dateTime.isBefore(fiscalPeriod.getStartTime()) && !dateTime.isAfter(fiscalPeriod.getEndTime());
}
/**
* Gets the query string.
*
* @param query the query
* @return the query string
*/
public static StringBuilder getQueryString(Map<String, Object> query) {
StringBuilder sb = new StringBuilder();
query.forEach((k, v) -> {
switch (k) {
case Constants.RISK_CATEGORY:
sb.append(" and anomalyRunId.fkAnomalyRuleId.riskCategory" + " LIKE ").append("'%" + v + "%'");
break;
case Constants.ANOMALY_CLASS:
sb.append(" and anomalyTypeId.anomalyClassId.name" + " LIKE ").append("'%" + v + "%'");
break;
case Constants.ANOMALY_TYPE:
sb.append(" and anomalyTypeId.name" + " LIKE ").append("'%" + v + "%'");
break;
case Constants.ANOMALY_STATUS:
sb.append(" and statusId.name" + " LIKE ").append("'%" + v + "%'");
break;
case Constants.ANOMALY_GL_ACCOUNT_ID:
sb.append(" and glAcctId" + " LIKE ").append("'%" + v + "%'");
break;
case Constants.ANOMALY_TRANSACTION_AMOUNT:
sb.append(" and transactionAmount" + " LIKE ")
.append(v.toString().contains(".") == true
? "'%" + v.toString().replace(",", "").replaceAll("0*$", "").replaceAll("\.$", "") + "%'"
: "'%" + v.toString().replace(",", "") + "%'");
break;
case Constants.DOCUMENT_NUMBER:
sb.append(" and erpId LIKE ")
.append("nil".contains(v.toString().toLowerCase()) == true ? 0 : "'%" + v + "%'");
break;
default:
sb.append(" and " + k + " LIKE ").append("'%" + v + "%'");
}
});
System.out.println("query " + sb);
return sb;
}
/**
* Gets the sort query string.
*
* @param sort the sort
* @return the sort query string
*/
public static StringBuilder getSortQueryString(String sort) {
StringBuilder sb = new StringBuilder();
switch (sort) {
case Constants.RISK_CATEGORY:
sb.append(" ORDER BY ").append("anomalyRunId.fkAnomalyRuleId.riskCategory");
break;
case Constants.ANOMALY_CLASS:
sb.append(" ORDER BY ").append("anomalyTypeId.anomalyClassId.name");
break;
case Constants.ANOMALY_TYPE:
sb.append(" ORDER BY ").append("anomalyTypeId.name");
break;
case Constants.ANOMALY_STATUS:
sb.append(" ORDER BY ").append("statusId.name");
break;
default:
sb.append(" ORDER BY ").append(sort);
}
return sb;
}
/**
* Selected column anomaly gl tx util.
*
* @param anomalyId the anomaly id
* @param searchDTO the search DTO
* @param dbColumnNames the db column names
* @param anomalySuggestGltxs the anomaly suggest gltxs
* @return the list
* @author Hrishikesh.T
*/
public List<HashMap<String, Object>> selectedColumnAnomalyGlTxUtil(Long anomalyId, SearchDTO searchDTO,
List<String> dbColumnNames, List<?> anomalySuggestGltxs) {
LOGGER.debug("Inside selectedColumnAnomalyGlTxUtil of Helper");
List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
anomalySuggestGltxs.forEach(anomalySuggestGltx -> {
HashMap<String, Object> gltx = new HashMap<String, Object>();
Object[] obj = (Object[]) anomalySuggestGltx;
for (int i = 0; i < dbColumnNames.size(); i++) {
if (dbColumnNames.get(i).equals("transaction_amount")) {
gltx.put(dbColumnNames.get(i), (String.format("%,.2f", obj[i])));
} else {
gltx.put(dbColumnNames.get(i), obj[i]);
}
}
data.add(gltx);
});
return data;
}
}
![]() |
Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...
With notes.io;
- * You can take a note from anywhere and any device with internet connection.
- * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
- * You can quickly share your contents without website, blog and e-mail.
- * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
- * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.
Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.
Easy: Notes.io doesn’t require installation. Just write and share note!
Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )
Free: Notes.io works for 14 years and has been free since the day it was started.
You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;
Email: [email protected]
Twitter: http://twitter.com/notesio
Instagram: http://instagram.com/notes.io
Facebook: http://facebook.com/notesio
Regards;
Notes.io Team