core.lib.Utility Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of EpikosRestService Show documentation
Show all versions of EpikosRestService Show documentation
Epikos is a Rest Serivce framework which can be extend to develop any other Rest API/Services. For more
detail please checkout github (https://github.com/epikosrest/epikos.git)
/*
Copyright (c) [2016] [[email protected]]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package core.lib;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.MappingJsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import core.domain.enums.ApiValidationStatusCode;
import core.domain.enums.Method;
import core.domain.enums.Status;
import core.dynamic.resources.ApiParam;
import core.dynamic.resources.IMethod;
import core.dynamic.resources.ResourceDocumentBuilder;
import core.error.ApiValidationStatus;
import core.exception.EpikosException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;
public final class Utility {
final static Logger logger = LoggerFactory.getLogger(Utility.class);
final static String CONFIGURATION_FILE = "config.file.name";
final static String CONFIGURATION_FOLDER = "config.file.location";
final static String DEFAULT_CONFIGURATION_FOLDER_NAME = "Config";
static String configFileName;
static String configFolder;
public static String getConfigFileFullPath() {
final String fileSeparator = System.getProperty("file.separator");
StringBuilder configFileNameAndFolderPath = new StringBuilder();
// We will try to get name of configuration file if it's been supplied
// as argument while starting service
configFileName = System.getProperty(CONFIGURATION_FILE);
if (configFileName == null) {
// Assign default configuration name
configFileName = "Application.configuration";
}
configFileNameAndFolderPath.append("Config file name : "
+ configFileName);
configFolder = System.getProperty(CONFIGURATION_FOLDER);
if (configFolder == null) {
configFolder = System.getProperty("user.dir") + fileSeparator
+ DEFAULT_CONFIGURATION_FOLDER_NAME;
} else {
configFolder = System.getProperty("user.dir") + fileSeparator
+ configFolder;
}
configFileNameAndFolderPath.append("\nConfig folder name : "
+ configFolder);
logger.info(configFileNameAndFolderPath.toString());
return configFolder + fileSeparator + configFileName;
}
public static String getConfigFileName() {
if (configFileName == null) {
configFileName = System.getProperty(CONFIGURATION_FILE);
if (configFileName == null) {
// Assign default configuration name
configFileName = "Application.configuration";
}
}
return configFileName;
}
public static String getConfigFolder() {
if (configFolder == null) {
final String fileSeparator = System.getProperty("file.separator");
configFolder = System.getProperty(CONFIGURATION_FOLDER);
if (configFolder == null) {
configFolder = System.getProperty("user.dir") + fileSeparator
+ DEFAULT_CONFIGURATION_FOLDER_NAME;
} else {
configFolder = System.getProperty("user.dir") + fileSeparator
+ configFolder;
}
}
return configFolder;
}
public static String getTimeStamp(long milliSeconds) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(milliSeconds);
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss:SSS");
return formatter.format(cal.getTime());
}
public static String readFile(String filename) {
String result = "";
final String fileSeparator = System.getProperty("file.separator");
final String baseDir = System.getProperty("user.dir");
final String spoofFilePath = baseDir + fileSeparator + filename;
try {
BufferedReader br = new BufferedReader(new FileReader(spoofFilePath));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
result = sb.toString();
} catch(Exception e) {
e.printStackTrace();
}
return result;
}
public static boolean isResourceAJSONObject(String resourceData){
if(resourceData == null){
return false;
}
try {
final String fileSeparator = System.getProperty("file.separator");
final String baseDir = System.getProperty("user.dir");
final String spoofFilePath = baseDir + fileSeparator + resourceData;
ObjectMapper mapper = new ObjectMapper();
JsonFactory jfactory = new MappingJsonFactory();
JsonParser jParser = jfactory.createJsonParser(new File(spoofFilePath));
return true;
}catch (IOException ioExp){
return false;
}
}
public static ApiValidationStatus isValidStatusCode(String status) throws EpikosException{
ApiValidationStatus apiValidationStatus = new ApiValidationStatus(ApiValidationStatusCode.Valid);
if(StringUtils.isEmpty(status) || StringUtils.isBlank(status)){
return new ApiValidationStatus(ApiValidationStatusCode.InvalidStatus,"Empty status code is not valid");
}
Integer statusCode = Status.getStatusCode(status);
if(statusCode == null){
try {
Status statusToVerify = Status.valueOf(status);
}catch (Exception exp){
logger.error(exp.getMessage());
return new ApiValidationStatus(ApiValidationStatusCode.InvalidStatus,String.format("Status code %s is not valid",status));
}
}
return apiValidationStatus;
}
public static ApiValidationStatus isValidMethod(String method){
ApiValidationStatus methodIsValid = doesMethodExist(method);
//Will check if it is a custom method or not
if(!methodIsValid.getCode().equals(ApiValidationStatusCode.Valid)){
boolean isAValidCustomMethod = Utility.hasResourceTypeImplementInterfaceListed(method, IMethod.class.getTypeName());
if(!isAValidCustomMethod){
methodIsValid = new ApiValidationStatus(ApiValidationStatusCode.InvalidMethod,String.format("Method : %s is invalid as it has been defined as custom method but has not implemented interface IMethod",method));
}
}
return methodIsValid;
}
private static ApiValidationStatus doesMethodExist(String method){
if(!(StringUtils.isEmpty(method) && StringUtils.isBlank(method))) {
for (Method m : Method.values()) {
if (method.equalsIgnoreCase(m.name())) {
return new ApiValidationStatus(ApiValidationStatusCode.Valid);
}
}
}
return new ApiValidationStatus(ApiValidationStatusCode.InvalidMethod,String.format("Method : %s is invalid",method));
}
public static ApiValidationStatus isValidPath(String path){
if(StringUtils.isEmpty(path) || StringUtils.isBlank(path)){
return new ApiValidationStatus(ApiValidationStatusCode.InvalidPath,String.format("Empty Path is not valid"));
}
return new ApiValidationStatus(ApiValidationStatusCode.Valid);
}
/*
This method validate consume and produce filed of api. It can be either application/json or application/xml
*/
public static ApiValidationStatus isValidContentType(String contentType){
if(StringUtils.isEmpty(contentType) || StringUtils.isBlank(contentType)){
return new ApiValidationStatus(ApiValidationStatusCode.InvalidContentType,String.format("Content type %s provided is not valid",contentType));
}else if("application/json".equalsIgnoreCase(contentType) || "application/xml".equalsIgnoreCase(contentType)){
return new ApiValidationStatus(ApiValidationStatusCode.Valid);
}
return new ApiValidationStatus(ApiValidationStatusCode.InvalidContentType,String.format("Content type %s provided is not valid and is not supported",contentType));
}
public static ApiValidationStatus doesPathParamsMatchWithApiPathParam(String apiPath, List apiParmList){
//If pathParms is null or empty then don't care for further validation
if(apiParmList == null || apiParmList.isEmpty()){
return new ApiValidationStatus(ApiValidationStatusCode.Valid);
}
List pathParams = apiParmList.stream().filter(p->p.getParam()!=null).map(ApiParam::getParam).collect(Collectors.toList());
//Lets first parse all param in api path
List parameterInPath = new ArrayList<>();
int startIndex =0;
int endIndex =0;
boolean foundOpeningBracket = false;
boolean foundClosingBracket = false;
for(int ind =0;ind= apiPath.length()){
break;
}
if(foundOpeningBracket && !foundClosingBracket){
return new ApiValidationStatus(ApiValidationStatusCode.InvalidPathParam,String.format("Invalid api path : The path has not been constructed properly and missing closing '}' bracket"));
}
//reset
foundOpeningBracket=false;
foundClosingBracket = false;
}
}
if(foundOpeningBracket && !foundClosingBracket){
return new ApiValidationStatus(ApiValidationStatusCode.InvalidPathParam,String.format("Invalid api path %s : The path has not been constructed properly and missing closing '}' bracket",apiPath));
}
if(!parameterInPath.isEmpty()){
if(parameterInPath.size() != pathParams.size()){
//Number Path param parsed and path param included in api mismatched
return new ApiValidationStatus(ApiValidationStatusCode.InvalidPathParam,String.format("Invalid api path %s : The path has not been constructed properly and missing closing '}' bracket",apiPath));
}
for(int ind =0;ind parseAndGetPathParams(String apiPath){
String[] params = null;
ArrayList paramList = new ArrayList<>();
if (apiPath != null){
//Parse path and get list of path param
String pathParamOpeningBracket = "\\{";
String pathParamClosingBracket = "}";
params = apiPath.split(pathParamOpeningBracket);
for(String p : params){
if(p.contains("}")){
int indexOfClosingBracket = p.indexOf(pathParamClosingBracket);
paramList.add(p.substring(0,indexOfClosingBracket));
}
}
}
return paramList;
}
}