From 8dafe1da41110d144391c0b51132ae4a018ac7df Mon Sep 17 00:00:00 2001 From: yamelsenih Date: Thu, 28 Sep 2023 12:24:44 -0400 Subject: [PATCH] Update repository using `adempiere-grpc-utils` reference library --- build.gradle | 1 + .../AuthorizationServerInterceptor.java | 67 -- .../spin/authentication/SessionManager.java | 648 -------------- .../org/spin/authentication/TokenManager.java | 66 -- .../org/spin/base/workflow/WorkflowUtil.java | 2 +- .../spin/grpc/client/MiddlewareClient.java | 4 +- .../spin/grpc/server/MiddlewareServer.java | 3 +- .../grpc/server/ServiceContextProvider.java | 47 - .../java/org/spin/grpc/service/Converter.java | 1 + .../java/org/spin/grpc/service/Service.java | 1 + .../org/spin/grpc/service/ValueManager.java | 828 ------------------ 11 files changed, 8 insertions(+), 1660 deletions(-) delete mode 100644 src/main/java/org/spin/authentication/AuthorizationServerInterceptor.java delete mode 100644 src/main/java/org/spin/authentication/SessionManager.java delete mode 100644 src/main/java/org/spin/authentication/TokenManager.java delete mode 100644 src/main/java/org/spin/grpc/server/ServiceContextProvider.java delete mode 100644 src/main/java/org/spin/grpc/service/ValueManager.java diff --git a/build.gradle b/build.gradle index a494578..88d7c77 100644 --- a/build.gradle +++ b/build.gradle @@ -163,6 +163,7 @@ dependencies { implementation "${baseGroupId}:adempiere-dashboard-improvements:1.0.7" implementation "${baseGroupId}:adempiere-pos-improvements:1.0.0" implementation "${baseGroupId}:adempiere-kafka-connector:1.0.0" + implementation "${baseGroupId}:adempiere-grpc-utils:1.0.0" // Others compileOnly 'org.apache.tomcat:annotations-api:6.0.53' } diff --git a/src/main/java/org/spin/authentication/AuthorizationServerInterceptor.java b/src/main/java/org/spin/authentication/AuthorizationServerInterceptor.java deleted file mode 100644 index c17e9ca..0000000 --- a/src/main/java/org/spin/authentication/AuthorizationServerInterceptor.java +++ /dev/null @@ -1,67 +0,0 @@ -/************************************************************************************ - * Copyright (C) 2012-2018 E.R.P. Consultores y Asociados, C.A. * - * Contributor(s): Yamel Senih ysenih@erpya.com * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation, either version 2 of the License, or * - * (at your option) any later version. * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License * - * along with this program. If not, see . * - ************************************************************************************/ -package org.spin.authentication; - -import java.util.Arrays; -import java.util.List; -import java.util.Properties; - -import io.grpc.Context; -import io.grpc.Contexts; -import io.grpc.Metadata; -import io.grpc.ServerCall; -import io.grpc.ServerCallHandler; -import io.grpc.ServerInterceptor; -import io.grpc.Status; - -public class AuthorizationServerInterceptor implements ServerInterceptor { - - /** Threaded key for context management */ - public static final Context.Key SESSION_CONTEXT = Context.key("session_context"); - /** Services/Methods allow request without Bearer token validation */ - private static List ALLOW_REQUESTS_WITHOUT_TOKEN = Arrays.asList( - "" - ); - - @Override - public ServerCall.Listener interceptCall(ServerCall serverCall, Metadata metadata, ServerCallHandler serverCallHandler) { - String callingMethod = serverCall.getMethodDescriptor().getFullMethodName(); - // Bypass to ingore Bearer validation - if (ALLOW_REQUESTS_WITHOUT_TOKEN.contains(callingMethod)) { - return Contexts.interceptCall(Context.current(), serverCall, metadata, serverCallHandler); - } - - Status status; - String validToken = metadata.get(TokenManager.AUTHORIZATION_METADATA_KEY); - if (validToken == null || validToken.trim().length() <= 0) { - status = Status.UNAUTHENTICATED.withDescription("Authorization token is missing"); - } else if (!validToken.startsWith(TokenManager.BEARER_TYPE)) { - status = Status.UNAUTHENTICATED.withDescription("Unknown authorization type"); - } else { - try { - Properties sessioncontext = SessionManager.getSessionFromToken(validToken); - Context context = Context.current().withValue(SESSION_CONTEXT, sessioncontext); - return Contexts.interceptCall(context, serverCall, metadata, serverCallHandler); - } catch (Exception e) { - status = Status.UNAUTHENTICATED.withDescription(e.getMessage()).withCause(e); - } - } - - serverCall.close(status, metadata); - return new ServerCall.Listener<>() { - // noop - }; - } -} diff --git a/src/main/java/org/spin/authentication/SessionManager.java b/src/main/java/org/spin/authentication/SessionManager.java deleted file mode 100644 index 56236d9..0000000 --- a/src/main/java/org/spin/authentication/SessionManager.java +++ /dev/null @@ -1,648 +0,0 @@ -/************************************************************************************* - * Product: Adempiere ERP & CRM Smart Business Solution * - * This program is free software; you can redistribute it and/or modify it * - * under the terms version 2 or later of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * - * Copyright (C) 2012-2023 E.R.P. Consultores y Asociados, S.A. All Rights Reserved. * - * Contributor(s): Yamel Senih www.erpya.com * - *************************************************************************************/ -package org.spin.authentication; - -import java.security.Key; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.Date; -import java.util.Optional; -import java.util.Properties; -import java.util.logging.Level; - -import org.adempiere.core.domains.models.I_AD_Language; -import org.adempiere.exceptions.AdempiereException; -import org.compiere.model.MAcctSchema; -import org.compiere.model.MClient; -import org.compiere.model.MClientInfo; -import org.compiere.model.MCountry; -import org.compiere.model.MLanguage; -import org.compiere.model.MOrg; -import org.compiere.model.MRole; -import org.compiere.model.MSession; -import org.compiere.model.MSysConfig; -import org.compiere.model.MUser; -import org.compiere.model.MWarehouse; -import org.compiere.model.ModelValidationEngine; -import org.compiere.util.CCache; -import org.compiere.util.CLogger; -import org.compiere.util.DB; -import org.compiere.util.Env; -import org.compiere.util.Ini; -import org.compiere.util.Language; -import org.compiere.util.TimeUtil; -import org.compiere.util.Util; -import org.spin.eca52.util.JWTUtil; -import org.spin.model.MADToken; -import org.spin.model.MADTokenDefinition; -import org.spin.util.IThirdPartyAccessGenerator; -import org.spin.util.ITokenGenerator; -import org.spin.util.TokenGeneratorHandler; - -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; -import io.jsonwebtoken.io.Decoders; -import io.jsonwebtoken.security.Keys; - -/** - * Class for handle Session for Third Party Access - * @author Yamel Senih, ysenih@erpya.com , http://www.erpya.com - */ -public class SessionManager { - - /** Session Context */ - /** Logger */ - private static CLogger log = CLogger.getCLogger(SessionManager.class); - /** Language */ - private static CCache languageCache = new CCache(I_AD_Language.Table_Name, 30, 0); // no time-out - - /** - * Get Default Country - * @return - */ - public static MCountry getDefaultCountry() { - MClient client = MClient.get (Env.getCtx()); - MLanguage language = MLanguage.get(Env.getCtx(), client.getAD_Language()); - MCountry country = MCountry.get(Env.getCtx(), language.getCountryCode()); - // Verify - if(country != null) { - return country; - } - // Default - return MCountry.getDefault(Env.getCtx()); - } - - /** - * Get Default from language - * @param language - * @return - */ - public static String getDefaultLanguage(String language) { - MClient client = MClient.get(Env.getCtx()); - String clientLanguage = client.getAD_Language(); - if(!Util.isEmpty(clientLanguage) - && Util.isEmpty(language)) { - return clientLanguage; - } - String defaultLanguage = language; - if(Util.isEmpty(language)) { - language = Language.AD_Language_en_US; - } - // Using es / en instead es_VE / en_US - // get default - if(language.length() == 2) { - defaultLanguage = languageCache.get(language); - if(!Util.isEmpty(defaultLanguage)) { - return defaultLanguage; - } - defaultLanguage = DB.getSQLValueString(null, "SELECT AD_Language " - + "FROM AD_Language " - + "WHERE LanguageISO = ? " - + "AND (IsSystemLanguage = 'Y' OR IsBaseLanguage = 'Y')", language); - // Set language - languageCache.put(language, defaultLanguage); - } - if(Util.isEmpty(defaultLanguage)) { - defaultLanguage = Language.AD_Language_en_US; - } - // Default return - return defaultLanguage; - } - - - /** - * Load session from token - * @param tokenValue - */ - public static Properties getSessionFromToken(String tokenValue) { - tokenValue = TokenManager.getTokenWithoutType(tokenValue); - // Validate if is token based - int userId = -1; - int roleId = -1; - int organizationId = -1; - int warehouseId = -1; - String language = "en_US"; - MADToken token = createSessionFromToken(tokenValue); - if(Optional.ofNullable(token).isPresent()) { - userId = token.getAD_User_ID(); - roleId = token.getAD_Role_ID(); - organizationId = token.getAD_Org_ID(); - } - // - if(organizationId < 0) { - organizationId = 0; - } - if(warehouseId < 0) { - warehouseId = 0; - } - // Get Values from role - if(roleId < 0) { - throw new AdempiereException("@AD_User_ID@ / @AD_Role_ID@ / @AD_Org_ID@ @NotFound@"); - } - Properties context = (Properties) Env.getCtx().clone(); - DB.validateSupportedUUIDFromDB(); - // - if(organizationId < 0) { - organizationId = 0; - } - if(warehouseId < 0) { - warehouseId = 0; - } - // Get Values from role - if(roleId < 0) { - throw new AdempiereException("@AD_User_ID@ / @AD_Role_ID@ / @AD_Org_ID@ @NotFound@"); - } - Env.setContext (context, "#Date", TimeUtil.getDay(System.currentTimeMillis())); - MRole role = MRole.get(context, roleId); - // Warehouse / Org - Env.setContext (context, "#M_Warehouse_ID", warehouseId); - Env.setContext(context, "#AD_Client_ID", role.getAD_Client_ID()); - Env.setContext(context, "#AD_Org_ID", organizationId); - // Role Info - Env.setContext(context, "#AD_Role_ID", roleId); - // User Info - Env.setContext(context, "#AD_User_ID", userId); - // - MSession session = MSession.get(context, true); - if(session == null - || session.getAD_Session_ID() <= 0) { - throw new AdempiereException("@AD_Session_ID@ @NotFound@"); - } - // Load preferences - loadDefaultSessionValues(context, language); - Env.setContext (context, "#AD_Session_ID", session.getAD_Session_ID()); - Env.setContext (context, "#Session_UUID", session.getUUID()); - Env.setContext(context, "#AD_User_ID", session.getCreatedBy()); - Env.setContext(context, "#AD_Role_ID", session.getAD_Role_ID()); - Env.setContext(context, "#AD_Client_ID", session.getAD_Client_ID()); - Env.setContext(context, "#Date", new Timestamp(System.currentTimeMillis())); - setDefault(context, Env.getAD_Org_ID(context), organizationId, warehouseId); - Env.setContext(context, Env.LANGUAGE, getDefaultLanguage(language)); - return context; - } - - public static String createSession(String clientVersion, String language, int roleId, int userId, int organizationId, int warehouseId) { - Properties context = (Properties) Env.getCtx().clone(); - MRole role = MRole.get(context, roleId); - // Warehouse / Org - Env.setContext (context, "#M_Warehouse_ID", warehouseId); - Env.setContext (context, "#AD_Session_ID", 0); - // Client Info - MClient client = MClient.get(context, role.getAD_Client_ID()); - Env.setContext(context, "#AD_Client_ID", client.getAD_Client_ID()); - Env.setContext(context, "#AD_Org_ID", organizationId); - // Role Info - Env.setContext(context, "#AD_Role_ID", roleId); - // User Info - Env.setContext(context, "#AD_User_ID", userId); - // - Env.setContext(context, "#Date", new Timestamp(System.currentTimeMillis())); - MSession session = MSession.get(context, true); - if (!Util.isEmpty(clientVersion, true)) { - session.setWebSession(clientVersion); - } - Env.setContext (context, "#AD_Session_ID", session.getAD_Session_ID()); - Env.setContext (context, "#Session_UUID", session.getUUID()); - // Load preferences - SessionManager.loadDefaultSessionValues(context, language); - // Session values - String bearerToken = createBearerToken(session, warehouseId, Env.getAD_Language(context)); - return bearerToken; - } - - private static String getSecretKey() { - String secretKey = MSysConfig.getValue(JWTUtil.ECA52_JWT_SECRET_KEY, Env.getAD_Client_ID(Env.getCtx())); - if(Util.isEmpty(secretKey)) { - throw new AdempiereException("@ECA52_JWT_SECRET_KEY@ @NotFound@"); - } - return secretKey; - } - - /** - * Create token as bearer - * @param session - * @param warehouseId - * @param language - * @return - */ - private static String createBearerToken(MSession session, int warehouseId, String language) { - MUser user = MUser.get(session.getCtx(), session.getCreatedBy()); - long sessionTimeout = getSessionTimeout(user); - if(sessionTimeout == 0) { - // Default 24 hours - sessionTimeout = 86400000; - } - - byte[] keyBytes = Decoders.BASE64.decode(getSecretKey()); - Key key = Keys.hmacShaKeyFor(keyBytes); - return Jwts.builder() - .setId(String.valueOf(session.getAD_Session_ID())) - .claim("AD_Client_ID", session.getAD_Client_ID()) - .claim("AD_Org_ID", session.getAD_Org_ID()) - .claim("AD_Role_ID", session.getAD_Role_ID()) - .claim("AD_User_ID", session.getCreatedBy()) - .claim("M_Warehouse_ID", warehouseId) - .claim("AD_Language", language) - .setIssuedAt(new Date(System.currentTimeMillis())) - .setExpiration(new Date(System.currentTimeMillis() + sessionTimeout)) - .signWith(key, SignatureAlgorithm.HS256) - .compact(); - } - - /** - * Get Session Timeout from user definition - * @param user - * @return - */ - public static long getSessionTimeout(MUser user) { - long sessionTimeout = 0; - Object value = null; - // checks if the column exists in the database - if (user.get_ColumnIndex("ConnectionTimeout") >= 0) { - value = user.get_Value("ConnectionTimeout"); - } - if(value == null) { - String sessionTimeoutAsString = MSysConfig.getValue("WEBUI_DEFAULT_TIMEOUT", Env.getAD_Client_ID(Env.getCtx()), 0); - try { - if (!Util.isEmpty(sessionTimeoutAsString, true)) { - sessionTimeout = Long.parseLong(sessionTimeoutAsString); - } - } catch (Exception e) { -// log.severe(e.getLocalizedMessage()); - } - } else { - try { - sessionTimeout = Long.parseLong(String.valueOf(value)); - } catch (Exception e) { -// log.severe(e.getLocalizedMessage()); - } - } - return sessionTimeout; - } - - /** - * Set Default warehouse and organization - * @param context - * @param defaultOrganizationId - * @param newOrganizationId - * @param warehouseId - */ - private static void setDefault(Properties context, int defaultOrganizationId, int newOrganizationId, int warehouseId) { - int organizationId = defaultOrganizationId; - if(newOrganizationId >= 0) { - MOrg organization = MOrg.get(context, newOrganizationId); - // - if(organization != null) { - organizationId = organization.getAD_Org_ID(); - } - } - if (warehouseId >= 0) { - MWarehouse warehouse = MWarehouse.get(context, warehouseId); - if (warehouse != null) { - Env.setContext(context, "#M_Warehouse_ID", warehouseId); - } - } - Env.setContext(context, "#AD_Org_ID", organizationId); - } - - /** - * Get id of current session - * @return - */ - public static int getSessionId() { - return Env.getContextAsInt(Env.getCtx(), "#AD_Session_ID"); - } - - /** - * Get uuid of current session - * @return - */ - public static String getSessionUuid() { - return Env.getContext(Env.getCtx(), "#Session_UUID"); - } - - /** - * Get token object: validate it - * @param tokenValue - * @return - */ - public static MADToken createSessionFromToken(String tokenValue) { - if(Util.isEmpty(tokenValue)) { - throw new AdempiereException("@AD_Token_ID@ @NotFound@"); - } - tokenValue = TokenManager.getTokenWithoutType(tokenValue); - // - try { - ITokenGenerator generator = TokenGeneratorHandler.getInstance().getTokenGenerator(MADTokenDefinition.TOKENTYPE_ThirdPartyAccess); - if(generator == null) { - throw new AdempiereException("@AD_TokenDefinition_ID@ @NotFound@"); - } - // No child of definition - if(!IThirdPartyAccessGenerator.class.isAssignableFrom(generator.getClass())) { - throw new AdempiereException("@AD_TokenDefinition_ID@ @Invalid@"); - } - // Validate - IThirdPartyAccessGenerator thirdPartyAccessGenerator = ((IThirdPartyAccessGenerator) generator); - if(!thirdPartyAccessGenerator.validateToken(tokenValue)) { - throw new AdempiereException("@Invalid@ @AD_Token_ID@"); - } - // Default - MADToken token = thirdPartyAccessGenerator.getToken(); - return token; - } catch (Exception e) { - throw new AdempiereException(e); - } - } - - /** - * Load default values for session - * @param context - * @param language - */ - public static void loadDefaultSessionValues(Properties context, String language) { - // Client Info - MClient client = MClient.get(context, Env.getContextAsInt(context, "#AD_Client_ID")); - Env.setContext(context, "#AD_Client_Name", client.getName()); - Env.setContext(context, "#Date", new Timestamp(System.currentTimeMillis())); - Env.setContext(context, Env.LANGUAGE, getDefaultLanguage(language)); - // Role Info - MRole role = MRole.get(context, Env.getContextAsInt(context, "#AD_Role_ID")); - Env.setContext(context, "#AD_Role_Name", role.getName()); - Env.setContext(context, "#SysAdmin", role.getAD_Role_ID() == 0); - - // User Info - MUser user = MUser.get(context, Env.getContextAsInt(context, "#AD_User_ID")); - Env.setContext(context, "#AD_User_Name", user.getName()); - Env.setContext(context, "#AD_User_Description", user.getDescription()); - Env.setContext(context, "#SalesRep_ID", user.getAD_User_ID()); - - // Load preferences - loadPreferences(context); - } - - /** - * Get Default Warehouse after login - * @param organizationId - * @return - */ - public static int getDefaultWarehouseId(int organizationId) { - if (organizationId < 0) { - return -1; - } - String sql = "SELECT M_Warehouse_ID FROM M_Warehouse WHERE IsActive = 'Y' AND AD_Org_ID = ? AND IsInTransit='N'"; - return DB.getSQLValue(null, sql, organizationId); - } - - /** - * Get Default role after login - * @param userId - * @return - */ - public static int getDefaultRoleId(int userId) { - String sql = "SELECT ur.AD_Role_ID " - + "FROM AD_User_Roles ur " - + "INNER JOIN AD_Role AS r ON ur.AD_Role_ID = r.AD_Role_ID " - + "WHERE ur.AD_User_ID = ? AND ur.IsActive = 'Y' " - + "AND r.IsActive = 'Y' " - + "AND ((r.IsAccessAllOrgs = 'Y' AND EXISTS(SELECT 1 FROM AD_Org AS o WHERE (o.AD_Client_ID = r.AD_Client_ID OR o.AD_Org_ID = 0) AND o.IsActive = 'Y' AND o.IsSummary = 'N') ) " - + "OR (r.IsUseUserOrgAccess = 'N' AND EXISTS(SELECT 1 FROM AD_Role_OrgAccess AS ro WHERE ro.AD_Role_ID = ur.AD_Role_ID AND ro.IsActive = 'Y') ) " - + "OR (r.IsUseUserOrgAccess = 'Y' AND EXISTS(SELECT 1 FROM AD_User_OrgAccess AS uo WHERE uo.AD_User_ID = ur.AD_User_ID AND uo.IsActive = 'Y') )) " - + "ORDER BY COALESCE(ur.IsDefault,'N') DESC"; - return DB.getSQLValue(null, sql, userId); - } - - /** - * Get Default organization after login - * @param roleId - * @param userId - * @return - */ - public static int getDefaultOrganizationId(int roleId, int userId) { - String organizationSQL = "SELECT o.AD_Org_ID " - + "FROM AD_Role r " - + "INNER JOIN AD_Client c ON(c.AD_Client_ID = r.AD_Client_ID) " - + "INNER JOIN AD_Org o ON(c.AD_Client_ID=o.AD_Client_ID OR o.AD_Org_ID=0) " - + "WHERE r.AD_Role_ID=? " - + " AND o.IsActive='Y' AND o.IsSummary='N'" - + " AND (r.IsAccessAllOrgs='Y' " - + "OR (r.IsUseUserOrgAccess='N' AND EXISTS(SELECT 1 FROM AD_Role_OrgAccess ra WHERE ra.AD_Org_ID = o.AD_Org_ID AND ra.AD_Role_ID = r.AD_Role_ID AND ra.IsActive='Y')) " - + "OR (r.IsUseUserOrgAccess='Y' AND EXISTS(SELECT 1 FROM AD_User_OrgAccess ua WHERE ua.AD_Org_ID = o.AD_Org_ID AND ua.AD_User_ID = ? AND ua.IsActive='Y'))" - + ") " - + "ORDER BY o.AD_Org_ID DESC, o.Name"; - return DB.getSQLValue(null, organizationSQL, roleId, userId); - } - - /** - * Load Preferences into Context for selected client. - *

- * Sets Org info in context and loads relevant field from - * - AD_Client/Info, - * - C_AcctSchema, - * - C_AcctSchema_Elements - * - AD_Preference - *

- * Assumes that the context is set for #AD_Client_ID, #AD_User_ID, #AD_Role_ID - * @param context - * @return AD_Message of error (NoValidAcctInfo) or "" - */ - private static void loadPreferences(Properties context) { - if (context == null) - throw new IllegalArgumentException("Required parameter missing"); - if (Env.getContext(context,"#AD_Client_ID").length() == 0) - throw new UnsupportedOperationException("Missing Context #AD_Client_ID"); - if (Env.getContext(context,"#AD_User_ID").length() == 0) - throw new UnsupportedOperationException("Missing Context #AD_User_ID"); - if (Env.getContext(context,"#AD_Role_ID").length() == 0) - throw new UnsupportedOperationException("Missing Context #AD_Role_ID"); - // Load Role Info - MRole.getDefault(context, true); - // Other - Env.setAutoCommit(context, Ini.isPropertyBool(Ini.P_A_COMMIT)); - Env.setAutoNew(context, Ini.isPropertyBool(Ini.P_A_NEW)); - - String isShowAccounting = "N"; - if (MRole.getDefault(context, false).isShowAcct()) { - isShowAccounting = "Y"; - } - Env.setContext(context, "#ShowAcct", isShowAccounting); - - Env.setContext(context, "#ShowTrl", Ini.getProperty(Ini.P_SHOW_TRL)); - Env.setContext(context, "#ShowAdvanced", Ini.getProperty(Ini.P_SHOW_ADVANCED)); - - // Other Settings - Env.setContext(context, "#YYYY", "Y"); - Env.setContext(context, "#StdPrecision", 2); - int clientId = Env.getAD_Client_ID(context); - int orgId = Env.getAD_Org_ID(context); - // AccountSchema Info (first) - String sql = "SELECT * " - + "FROM C_AcctSchema a, AD_ClientInfo c " - + "WHERE a.C_AcctSchema_ID=c.C_AcctSchema1_ID " - + "AND c.AD_Client_ID=?"; - PreparedStatement pstmt = null; - ResultSet rs = null; - try { - int acctSchemaId = 0; - - pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, clientId); - rs = pstmt.executeQuery(); - - if (rs.next()) { - // Accounting Info - acctSchemaId = rs.getInt("C_AcctSchema_ID"); - Env.setContext(context, "$C_AcctSchema_ID", acctSchemaId); - Env.setContext(context, "$C_Currency_ID", rs.getInt("C_Currency_ID")); - Env.setContext(context, "$HasAlias", rs.getString("HasAlias")); - } - rs.close(); - pstmt.close(); - /**Define AcctSchema , Currency, HasAlias for Multi AcctSchema**/ - MAcctSchema[] ass = MAcctSchema.getClientAcctSchema(Env.getCtx(), clientId); - if(ass != null && ass.length > 1) { - for(MAcctSchema as : ass) { - acctSchemaId = MClientInfo.get(Env.getCtx(), clientId).getC_AcctSchema1_ID(); - if (as.getAD_OrgOnly_ID() != 0) { - if (as.isSkipOrg(orgId)) { - continue; - } else { - acctSchemaId = as.getC_AcctSchema_ID(); - Env.setContext(context, "$C_AcctSchema_ID", acctSchemaId); - Env.setContext(context, "$C_Currency_ID", as.getC_Currency_ID()); - Env.setContext(context, "$HasAlias", as.isHasAlias()); - break; - } - } - } - } - - // Accounting Elements - sql = "SELECT ElementType " - + "FROM C_AcctSchema_Element " - + "WHERE C_AcctSchema_ID=?" - + " AND IsActive='Y'"; - pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, acctSchemaId); - rs = pstmt.executeQuery(); - while (rs.next()) - Env.setContext(context, "$Element_" + rs.getString("ElementType"), "Y"); - rs.close(); - pstmt.close(); - - // This reads all relevant window neutral defaults - // overwriting superseeded ones. Window specific is read in Mainain - sql = "SELECT Attribute, Value, AD_Window_ID " - + "FROM AD_Preference " - + "WHERE AD_Client_ID IN (0, @#AD_Client_ID@)" - + " AND AD_Org_ID IN (0, @#AD_Org_ID@)" - + " AND (AD_User_ID IS NULL OR AD_User_ID=0 OR AD_User_ID=@#AD_User_ID@)" - + " AND IsActive='Y' " - + "ORDER BY Attribute, AD_Client_ID, AD_User_ID DESC, AD_Org_ID"; - // the last one overwrites - System - Client - User - Org - Window - sql = Env.parseContext(context, 0, sql, false); - if (sql.length() == 0) { - log.log(Level.SEVERE, "loadPreferences - Missing Environment"); - } else { - pstmt = DB.prepareStatement(sql, null); - rs = pstmt.executeQuery(); - while (rs.next()) { - int AD_Window_ID = rs.getInt(3); - String at = ""; - if (rs.wasNull()) - at = "P|" + rs.getString(1); - else - at = "P" + AD_Window_ID + "|" + rs.getString(1); - String va = rs.getString(2); - Env.setContext(context, at, va); - } - rs.close(); - pstmt.close(); - } - - // Default Values - log.info("Default Values ..."); - sql = "SELECT t.TableName, c.ColumnName " - + "FROM AD_Column c " - + " INNER JOIN AD_Table t ON (c.AD_Table_ID=t.AD_Table_ID) " - + "WHERE c.IsKey='Y' AND t.IsActive='Y'" - + " AND EXISTS (SELECT * FROM AD_Column cc " - + " WHERE ColumnName = 'IsDefault' AND t.AD_Table_ID=cc.AD_Table_ID AND cc.IsActive='Y')"; - pstmt = DB.prepareStatement(sql, null); - rs = pstmt.executeQuery(); - while (rs.next()) { - loadDefault (context, rs.getString(1), rs.getString(2)); - } - rs.close(); - pstmt.close(); - pstmt = null; - } catch (SQLException e) { - log.log(Level.SEVERE, "loadPreferences", e); - } finally { - DB.close(rs, pstmt); - } - // Country - MCountry country = getDefaultCountry(); - if(country != null) { - Env.setContext(context, "#C_Country_ID", country.getC_Country_ID()); - } - // Call ModelValidators afterLoadPreferences - teo_sarca FR [ 1670025 ] - ModelValidationEngine.get().afterLoadPreferences(context); - } // loadPreferences - - /** - * Load Default Value for Table into Context. - * @param tableName table name - * @param columnName column name - */ - private static void loadDefault (Properties context, String tableName, String columnName) { - if (tableName.startsWith("AD_Window") - || tableName.startsWith("AD_PrintFormat") - || tableName.startsWith("AD_Workflow") ) - return; - String value = null; - // - String sql = "SELECT " + columnName + " FROM " + tableName // most specific first - + " WHERE IsDefault='Y' AND IsActive='Y' ORDER BY AD_Client_ID DESC, AD_Org_ID DESC"; - sql = MRole.getDefault(Env.getCtx(), false).addAccessSQL(sql, - tableName, MRole.SQL_NOTQUALIFIED, MRole.SQL_RO); - PreparedStatement pstmt = null; - ResultSet rs = null; - try { - pstmt = DB.prepareStatement(sql, null); - rs = pstmt.executeQuery(); - if (rs.next()) - value = rs.getString(1); - rs.close(); - pstmt.close(); - pstmt = null; - } catch (SQLException e) { - log.log(Level.SEVERE, tableName + " (" + sql + ")", e); - return; - } finally { - DB.close(rs, pstmt); - } - // Set Context Value - if (value != null && value.length() != 0) - { - if (tableName.equals("C_DocType")) - Env.setContext(context, "#C_DocTypeTarget_ID", value); - else - Env.setContext(context, "#" + columnName, value); - } - } // loadDefault -} diff --git a/src/main/java/org/spin/authentication/TokenManager.java b/src/main/java/org/spin/authentication/TokenManager.java deleted file mode 100644 index b6f3ad0..0000000 --- a/src/main/java/org/spin/authentication/TokenManager.java +++ /dev/null @@ -1,66 +0,0 @@ -/************************************************************************************ - * Copyright (C) 2012-2018 E.R.P. Consultores y Asociados, C.A. * - * Contributor(s): Yamel Senih ysenih@erpya.com * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation, either version 2 of the License, or * - * (at your option) any later version. * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License * - * along with this program. If not, see . * - ************************************************************************************/ -package org.spin.authentication; - -import static io.grpc.Metadata.ASCII_STRING_MARSHALLER; - -import java.util.concurrent.Executor; - -import io.grpc.CallCredentials; -import io.grpc.Context; -import io.grpc.Metadata; -import io.grpc.Status; - -public class TokenManager extends CallCredentials { - - public static final String BEARER_TYPE = "Bearer"; - - public static final Metadata.Key AUTHORIZATION_METADATA_KEY = Metadata.Key.of("Authorization", ASCII_STRING_MARSHALLER); - public static final Context.Key CLIENT_ID_CONTEXT_KEY = Context.key("clientId"); - - private String value; - - public TokenManager(String value) { - this.value = value; - } - - @Override - public void applyRequestMetadata(RequestInfo requestInfo, Executor executor, MetadataApplier metadataApplier) { - executor.execute(() -> { - try { - Metadata headers = new Metadata(); - headers.put(AUTHORIZATION_METADATA_KEY, String.format("%s %s", BEARER_TYPE, value)); - metadataApplier.apply(headers); - } catch (Throwable e) { - metadataApplier.fail(Status.UNAUTHENTICATED.withCause(e)); - } - }); - } - - @Override - public void thisUsesUnstableApi() { - // noop - } - - public static String getTokenWithoutType(String token) { - if (token == null || token.trim().length() == 0) { - return ""; - } - if (token.startsWith(BEARER_TYPE)) { - return token.substring(BEARER_TYPE.length()).trim(); - } - return token; - } -} diff --git a/src/main/java/org/spin/base/workflow/WorkflowUtil.java b/src/main/java/org/spin/base/workflow/WorkflowUtil.java index 50774f0..69b758d 100644 --- a/src/main/java/org/spin/base/workflow/WorkflowUtil.java +++ b/src/main/java/org/spin/base/workflow/WorkflowUtil.java @@ -32,8 +32,8 @@ import org.compiere.util.Util; import org.compiere.wf.MWorkflow; import org.spin.grpc.service.Service; -import org.spin.grpc.service.ValueManager; import org.spin.proto.service.RunBusinessProcessResponse; +import org.spin.service.grpc.util.ValueManager; /** * @author Edwin Betancourt, EdwinBetanc0urt@outlook.com, https://github.com/EdwinBetanc0urt diff --git a/src/main/java/org/spin/grpc/client/MiddlewareClient.java b/src/main/java/org/spin/grpc/client/MiddlewareClient.java index e3371ae..236e2e7 100644 --- a/src/main/java/org/spin/grpc/client/MiddlewareClient.java +++ b/src/main/java/org/spin/grpc/client/MiddlewareClient.java @@ -23,14 +23,14 @@ import java.util.stream.IntStream; import org.compiere.util.CLogger; -import org.spin.authentication.TokenManager; -import org.spin.grpc.service.ValueManager; import org.spin.proto.service.Entity; import org.spin.proto.service.CreateEntityRequest; import org.spin.proto.service.DeleteEntityRequest; import org.spin.proto.service.MiddlewareServiceGrpc; import org.spin.proto.service.MiddlewareServiceGrpc.MiddlewareServiceBlockingStub; import org.spin.server.setup.SetupLoader; +import org.spin.service.grpc.authentication.TokenManager; +import org.spin.service.grpc.util.ValueManager; import com.google.protobuf.Struct; diff --git a/src/main/java/org/spin/grpc/server/MiddlewareServer.java b/src/main/java/org/spin/grpc/server/MiddlewareServer.java index 6255dea..2416783 100644 --- a/src/main/java/org/spin/grpc/server/MiddlewareServer.java +++ b/src/main/java/org/spin/grpc/server/MiddlewareServer.java @@ -19,9 +19,10 @@ import java.util.logging.Logger; import org.compiere.util.Env; -import org.spin.authentication.AuthorizationServerInterceptor; import org.spin.grpc.controller.Middleware; import org.spin.server.setup.SetupLoader; +import org.spin.service.grpc.authentication.AuthorizationServerInterceptor; +import org.spin.service.grpc.context.ServiceContextProvider; import io.grpc.Server; import io.grpc.netty.GrpcSslContexts; diff --git a/src/main/java/org/spin/grpc/server/ServiceContextProvider.java b/src/main/java/org/spin/grpc/server/ServiceContextProvider.java deleted file mode 100644 index 6984235..0000000 --- a/src/main/java/org/spin/grpc/server/ServiceContextProvider.java +++ /dev/null @@ -1,47 +0,0 @@ -/************************************************************************************ - * Copyright (C) 2012-2023 E.R.P. Consultores y Asociados, C.A. * - * Contributor(s): Yamel Senih ysenih@erpya.com * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation, either version 2 of the License, or * - * (at your option) any later version. * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License * - * along with this program. If not, see . * - ************************************************************************************/ -package org.spin.grpc.server; - -import org.compiere.util.ContextProvider; -import org.spin.authentication.AuthorizationServerInterceptor; - -import java.util.Properties; - - - -/** - * @author Yamel Senih, ysenih@erpya.com, ERPCyA http://www.erpya.com - * This class allows define a context provider based on gRPC Context - */ -public class ServiceContextProvider implements ContextProvider { - - /** - * Get server context proxy - */ - public Properties getContext() { - Properties context = (Properties) AuthorizationServerInterceptor.SESSION_CONTEXT.get(); - if(context == null) { - context = new Properties(); - } - return context; - } - - /** - * Backend not implemented here - */ - public void showURL(String url, String title) { - - } -} diff --git a/src/main/java/org/spin/grpc/service/Converter.java b/src/main/java/org/spin/grpc/service/Converter.java index 3c6523a..4af2e5d 100644 --- a/src/main/java/org/spin/grpc/service/Converter.java +++ b/src/main/java/org/spin/grpc/service/Converter.java @@ -21,6 +21,7 @@ import org.compiere.util.Msg; import org.spin.proto.service.Entity; import org.spin.proto.service.ProcessInfoLog; +import org.spin.service.grpc.util.ValueManager; import com.google.protobuf.Struct; import com.google.protobuf.Value; diff --git a/src/main/java/org/spin/grpc/service/Service.java b/src/main/java/org/spin/grpc/service/Service.java index 1111832..7582df2 100644 --- a/src/main/java/org/spin/grpc/service/Service.java +++ b/src/main/java/org/spin/grpc/service/Service.java @@ -63,6 +63,7 @@ import org.spin.proto.service.RunBusinessProcessRequest; import org.spin.proto.service.RunBusinessProcessResponse; import org.spin.proto.service.UpdateEntityRequest; +import org.spin.service.grpc.util.ValueManager; import com.google.protobuf.ByteString; import com.google.protobuf.Empty; diff --git a/src/main/java/org/spin/grpc/service/ValueManager.java b/src/main/java/org/spin/grpc/service/ValueManager.java deleted file mode 100644 index 2934876..0000000 --- a/src/main/java/org/spin/grpc/service/ValueManager.java +++ /dev/null @@ -1,828 +0,0 @@ -/************************************************************************************* - * Product: Adempiere ERP & CRM Smart Business Solution * - * This program is free software; you can redistribute it and/or modify it * - * under the terms version 2 or later of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * - * Copyright (C) 2012-2018 E.R.P. Consultores y Asociados, S.A. All Rights Reserved. * - * Contributor(s): Yamel Senih www.erpya.com * - *************************************************************************************/ -package org.spin.grpc.service; - -import static com.google.protobuf.util.Timestamps.fromMillis; - -import java.math.BigDecimal; -import java.sql.Timestamp; -import java.text.DecimalFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.Instant; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -import org.adempiere.core.domains.models.I_C_Order; -import org.adempiere.exceptions.AdempiereException; -import org.compiere.model.MLookup; -import org.compiere.model.MLookupFactory; -import org.compiere.model.MLookupInfo; -import org.compiere.model.PO; -import org.compiere.util.DisplayType; -import org.compiere.util.Env; -import org.compiere.util.Language; -import org.compiere.util.Msg; -import org.compiere.util.NamePair; -import org.compiere.util.TimeUtil; -import org.compiere.util.Util; - -import com.google.protobuf.Struct; -import com.google.protobuf.Value; - -/** - * Class for handle Values from and to client - * @author Yamel Senih, ysenih@erpya.com , http://www.erpya.com - */ -public class ValueManager { - - /** Date format */ - private static final String TIME_FORMAT = "yyyy-MM-dd hh:mm:ss"; - private static final String DATE_FORMAT = "yyyy-MM-dd"; - private static final String TYPE_KEY = "type"; - private static final String VALUE_KEY = "value"; - // Types - public static final String TYPE_DATE = "date"; - public static final String TYPE_DATE_TIME = "date_time"; - public static final String TYPE_DECIMAL = "decimal"; - - - /** - * Get Value - * @param value - * @return - */ - public static Value.Builder getValueFromObject(Object value) { - Value.Builder builder = Value.newBuilder(); - if(value == null) { - return builder; - } - // Validate value - if(value instanceof BigDecimal) { - return getValueFromDecimal((BigDecimal) value); - } else if (value instanceof Integer) { - return getValueFromInteger((Integer)value); - } else if (value instanceof String) { - return getValueFromString((String) value); - } else if (value instanceof Boolean) { - return getValueFromBoolean((Boolean) value); - } else if(value instanceof Timestamp) { - return getValueFromDate((Timestamp) value); - } - // - return builder; - } - - /** - * Get value from Integer - * @param value - * @return - */ - public static Value.Builder getValueFromInteger(Integer value) { - if(value == null) { - return Value.newBuilder(); - } - // default - return Value.newBuilder().setNumberValue((Integer)value); - } - /** - * Get value from Int - * @param value - * @return - */ - public static Value.Builder getValueFromInt(int value) { - return getValueFromInteger(value); - } - - /** - * Get value from a string - * @param value - * @return - */ - public static Value.Builder getValueFromString(String value) { - return Value.newBuilder().setStringValue(validateNull(value)); - } - - /** - * Get value from a boolean value - * @param value - * @return - */ - public static Value.Builder getValueFromBoolean(boolean value) { - return Value.newBuilder().setBoolValue(value); - } - /** - * Get value from a Boolean value - * @param value - * @return - */ - public static Value.Builder getValueFromBoolean(Boolean value) { - if(value == null) { - return Value.newBuilder(); - } - return Value.newBuilder().setBoolValue(value); - } - /** - * Get value from a String Boolean value - * @param value - * @return - */ - public static Value.Builder getValueFromStringBoolean(String value) { - return getValueFromBoolean(stringToBoolean(value)); - } - - /** - * Get value from a date - * @param value - * @return - */ - public static Value.Builder getValueFromDate(Timestamp value) { - if (value == null) { - return Value.newBuilder(); - } - Struct.Builder date = Struct.newBuilder(); - date.putFields(TYPE_KEY, Value.newBuilder().setStringValue(TYPE_DATE).build()); - date.putFields(VALUE_KEY, Value.newBuilder().setStringValue(convertDateToString(value)).build()); - return Value.newBuilder().setStructValue(date); - } - - public static com.google.protobuf.Timestamp getTimestampFromDate(Timestamp value) { - if (value == null) { - return null; - } - return fromMillis(value.getTime()); - } - - - /** - * Get value from big decimal - * @param value - * @return - */ - public static Value.Builder getValueFromDecimal(BigDecimal value) { - return getDecimalFromBigDecimal(value); - } - - /** - * Get decimal from big decimal - * @param value - * @return - */ - public static Value.Builder getDecimalFromBigDecimal(BigDecimal value) { - if (value == null) { - return Value.newBuilder(); - } - Struct.Builder decimalValue = Struct.newBuilder(); - decimalValue.putFields(TYPE_KEY, Value.newBuilder().setStringValue(TYPE_DECIMAL).build()); - decimalValue.putFields(VALUE_KEY, Value.newBuilder().setStringValue(value.toPlainString()).build()); - return Value.newBuilder().setStructValue(decimalValue); - } - - public static BigDecimal getBigDecimalFromDecimal(Value decimalValue) { - return getDecimalFromValue(decimalValue); - } - - /** - * Get BigDecimal object from decimal - * @param decimalValue - * @return - */ - public static BigDecimal getDecimalFromValue(Value decimalValue) { - if(decimalValue == null - || decimalValue.hasNullValue() - || !decimalValue.hasStringValue()) { - return null; - } - Map values = decimalValue.getStructValue().getFieldsMap(); - if(values == null) { - return null; - } - Value type = values.get(TYPE_KEY); - Value value = values.get(VALUE_KEY); - if(type == null - || value == null) { - return null; - } - String validType = Optional.ofNullable(type.getStringValue()).orElse(""); - String validValue = Optional.ofNullable(value.getStringValue()).orElse(""); - if(!validType.equals(TYPE_DECIMAL) - || validValue.length() == 0) { - return null; - } - return new BigDecimal(validValue); - } - - /** - * Get Date from value - * @param dateValue - * @return - */ - public static Timestamp getDateFromTimestampDate(com.google.protobuf.Timestamp dateValue) { - if(dateValue == null) { - return null; - } - Instant epochDate = Instant.ofEpochSecond(dateValue.getSeconds(), dateValue.getNanos()); - return new Timestamp(Date.from(epochDate).getTime()); - } - - /** - * Get Date from a value - * @param value - * @return - */ - public static Timestamp getDateFromValue(Value dateValue) { - if(dateValue == null - || dateValue.hasNullValue() - || !dateValue.hasStringValue()) { - return null; - } - Map values = dateValue.getStructValue().getFieldsMap(); - if(values == null) { - return null; - } - Value type = values.get(TYPE_KEY); - Value value = values.get(VALUE_KEY); - if(type == null - || value == null) { - return null; - } - String validType = Optional.ofNullable(type.getStringValue()).orElse(""); - String validValue = Optional.ofNullable(value.getStringValue()).orElse(""); - if((!validType.equals(TYPE_DATE) - && !validType.equals(TYPE_DATE_TIME)) - || validValue.length() == 0) { - return null; - } - return convertStringToDate(validValue); - } - - /** - * Get String from a value - * @param value - * @param uppercase - * @return - */ - public static String getStringFromValue(Value value, boolean uppercase) { - String stringValue = value.getStringValue(); - if(Util.isEmpty(stringValue, true)) { - return null; - } - // To Upper case - if(uppercase) { - stringValue = stringValue.toUpperCase(); - } - return stringValue; - } - - /** - * Get String from a value - * @param value - * @return - */ - public static String getStringFromValue(Value value) { - return getStringFromValue(value, false); - } - - /** - * Get integer from a value - * @param value - * @return - */ - public static int getIntegerFromValue(Value value) { - return (int) value.getNumberValue(); - } - - /** - * Get Boolean from a value - * @param value - * @return - */ - public static boolean getBooleanFromValue(Value value) { - if (!Util.isEmpty(value.getStringValue(), true)) { - return "Y".equals(value.getStringValue()) - || "Yes".equals(value.getStringValue()) - || "true".equals(value.getStringValue()); - } - - return value.getBoolValue(); - } - - /** - * Get Value from reference - * @param value - * @param referenceId reference of value - * @return - */ - public static Value.Builder getValueFromReference(Object value, int referenceId) { - Value.Builder builderValue = Value.newBuilder(); - if(value == null) { - return builderValue; - } - // Validate values - if(isLookup(referenceId) - || DisplayType.isID(referenceId)) { - return getValueFromObject(value); - } else if(DisplayType.Integer == referenceId) { - Integer integerValue = null; - if(value instanceof Integer) { - integerValue = (Integer) value; - } else if (value instanceof Long) { - long longValue = (long) value; - integerValue = Math.toIntExact(longValue); - } else if(value instanceof BigDecimal) { - integerValue = ((BigDecimal) value).intValue(); - } else if (value instanceof String) { - try { - integerValue = Integer.valueOf((String) value); - } catch (Exception e) { - integerValue = null; - } - } - return getValueFromInteger(integerValue); - } else if(DisplayType.isNumeric(referenceId)) { - BigDecimal bigDecimalValue = null; - if (value instanceof Integer) { - Integer intValue = (Integer) value; - bigDecimalValue = BigDecimal.valueOf(intValue); - } else if (value instanceof Long) { - long longValue = (long) value; - bigDecimalValue = BigDecimal.valueOf(longValue); - } else if (value instanceof String) { - bigDecimalValue = new BigDecimal((String) value); - } else { - bigDecimalValue = (BigDecimal) value; - } - return getValueFromDecimal(bigDecimalValue); - } else if(DisplayType.YesNo == referenceId) { - if (value instanceof String) { - return getValueFromStringBoolean((String) value); - } - return getValueFromBoolean((Boolean) value); - } else if(DisplayType.isDate(referenceId)) { - return getValueFromDate((Timestamp) value); - } else if(DisplayType.isText(referenceId)) { - return getValueFromString((String) value); - } else if (DisplayType.Button == referenceId) { - if (value instanceof Integer) { - return getValueFromInteger((Integer) value); - } else if (value instanceof Long) { - long longValue = (long) value; - Integer integerValue = Math.toIntExact(longValue); - return getValueFromInt(integerValue); - } else if(value instanceof BigDecimal) { - return getValueFromInteger(((BigDecimal) value).intValue()); - } else if (value instanceof String) { - return getValueFromString((String) value); - } - return getValueFromObject(value); - } - // - return builderValue; - } - - public static String getDisplayedValueFromReference(Object value, String columnName, int displayTypeId, int referenceValueId) { - String displayedValue = null; - - if (value == null) { - return displayedValue; - } - if (DisplayType.isText (displayTypeId)) { - ; - } else if (displayTypeId == DisplayType.YesNo) { - displayedValue = booleanToString(value.toString(), true); - } else if (displayTypeId == DisplayType.Amount) { - DecimalFormat amountFormat = DisplayType.getNumberFormat(DisplayType.Amount, Env.getLanguage(Env.getCtx())); - displayedValue = amountFormat.format (new BigDecimal(value.toString())); - } else if (displayTypeId == DisplayType.Integer) { - DecimalFormat intFormat = DisplayType.getNumberFormat(DisplayType.Integer, Env.getLanguage(Env.getCtx())); - displayedValue = intFormat.format(Integer.valueOf(value.toString())); - } else if (DisplayType.isNumeric(displayTypeId)) { - DecimalFormat numberFormat = DisplayType.getNumberFormat(DisplayType.Number, Env.getLanguage(Env.getCtx())); - if (I_C_Order.COLUMNNAME_ProcessedOn.equals(columnName)) { - if (value.toString().indexOf(".") > 0) { - value = value.toString().substring(0, value.toString().indexOf(".")); - } - displayedValue = TimeUtil.formatElapsed(System.currentTimeMillis() - new BigDecimal(value.toString()).longValue()); - } else { - displayedValue = numberFormat.format(new BigDecimal(value.toString())); - } - } else if (displayTypeId == DisplayType.Date) { - SimpleDateFormat dateFormat = DisplayType.getDateFormat(DisplayType.DateTime, Env.getLanguage(Env.getCtx())); - displayedValue = dateFormat.format(Timestamp.valueOf(value.toString())); - } else if (displayTypeId == DisplayType.DateTime) { - SimpleDateFormat dateTimeFormat = DisplayType.getDateFormat(DisplayType.DateTime, Env.getLanguage(Env.getCtx())); - displayedValue = dateTimeFormat.format (Timestamp.valueOf(value.toString())); - } else if (DisplayType.isLookup(displayTypeId) && displayTypeId != DisplayType.Button && displayTypeId != DisplayType.List) { - Language language = Env.getLanguage(Env.getCtx()); - MLookupInfo lookupInfo = MLookupFactory.getLookupInfo(Env.getCtx(), 0, 0, displayTypeId, language, columnName, referenceValueId, false, null, false); - MLookup lookup = new MLookup(lookupInfo, 0); - NamePair pp = lookup.get(value); - if (pp != null) { - displayedValue = pp.getName(); - } - } else if((DisplayType.Button == displayTypeId || DisplayType.List == displayTypeId) && referenceValueId != 0) { - MLookupInfo lookupInfo = MLookupFactory.getLookup_List(Env.getLanguage(Env.getCtx()), referenceValueId); - - MLookup lookup = new MLookup(lookupInfo, 0); - if (value != null) { - Object key = value; - NamePair pp = lookup.get(key); - if (pp != null) { - displayedValue = pp.getName(); - } - } - } else if (DisplayType.isLOB(displayTypeId)) { - ; - } - return displayedValue; - } - - /** - * Convert Selection values from gRPC to ADempiere values - * @param values - * @return - */ - public static Map convertValuesMapToObjects(Map values) { - Map convertedValues = new HashMap<>(); - if (values == null || values.size() <= 0) { - return convertedValues; - } - values.keySet().forEach(keyValue -> { - convertedValues.put(keyValue, getObjectFromValue(values.get(keyValue))); - }); - // - return convertedValues; - } - - /** - * Convert Selection values from gRPC to ADempiere values - * @param values - * @return - */ - public static Value.Builder convertObjectMapToStruct(Map values) { - Value.Builder convertedValues = Value.newBuilder(); - if (values == null || values.size() <= 0) { - return convertedValues; - } - Struct.Builder mapValue = Struct.newBuilder(); - values.keySet().forEach(keyValue -> { - mapValue.putFields(keyValue, getValueFromObject(values.get(keyValue)).build()); - }); - // - return convertedValues.setStructValue(mapValue); - } - - /** - * Default get value from type - * @param valueToConvert - * @return - */ - public static Object getObjectFromValue(Value valueToConvert) { - return getObjectFromValue(valueToConvert, false); - } - - /** - * Get value from parameter type - * @param value - * @return - */ - public static Object getObjectFromValue(Value value, boolean uppercase) { - if(value == null - || value.hasNullValue()) { - return null; - } - if(value.hasStringValue()) { - return getStringFromValue(value, uppercase); - } - if(value.hasNumberValue()) { - return (int) value.getNumberValue(); - } - if(value.hasBoolValue()) { - return value.getBoolValue(); - } - if(value.hasStructValue()) { - if(isDecimalValue(value)) { - return getDecimalFromValue(value); - } else if(isDateValue(value)) { - return getDateFromValue(value); - } - } - return null; - } - - /** - * Validate if a value is date - * @param value - * @return - */ - public static boolean isDateValue(Value value) { - Map values = value.getStructValue().getFieldsMap(); - if(values == null) { - return false; - } - Value type = values.get(TYPE_KEY); - if(type == null) { - return false; - } - String validType = Optional.ofNullable(type.getStringValue()).orElse(""); - return validType.equals(TYPE_DATE) || validType.equals(TYPE_DATE_TIME); - } - - /** - * Validate if is a decimal value - * @param value - * @return - */ - public static boolean isDecimalValue(Value value) { - Map values = value.getStructValue().getFieldsMap(); - if(values == null) { - return false; - } - Value type = values.get(TYPE_KEY); - if(type == null) { - return false; - } - String validType = Optional.ofNullable(type.getStringValue()).orElse(""); - return validType.equals(TYPE_DECIMAL); - } - - /** - * Get Object from value based on reference - * @param value - * @param referenceId - * @return - */ - public static Object getObjectFromReference(Value value, int referenceId) { - if(value == null) { - return null; - } - // Validate values - if(isLookup(referenceId) - || DisplayType.isID(referenceId)) { - return getObjectFromValue(value); - } else if(DisplayType.Integer == referenceId) { - return getIntegerFromValue(value); - } else if(DisplayType.isNumeric(referenceId)) { - return getDecimalFromValue(value); - } else if(DisplayType.YesNo == referenceId) { - return getBooleanFromValue(value); - } else if(DisplayType.isDate(referenceId)) { - return getDateFromValue(value); - } else if(DisplayType.isText(referenceId)) { - return getStringFromValue(value); - } - // - return null; - } - - /** - * Is lookup include location - * @param displayType - * @return - */ - public static boolean isLookup(int displayType) { - return DisplayType.isLookup(displayType) - || DisplayType.Account == displayType - || DisplayType.Location == displayType - || DisplayType.Locator == displayType - || DisplayType.PAttribute == displayType; - } - - /** - * Convert null on "" - * @param value - * @return - */ - public static String validateNull(String value) { - if(value == null) { - value = ""; - } - // - return value; - } - - /** - * Get translation if is necessary - * @param object - * @param columnName - * @return - */ - public static String getTranslation(PO object, String columnName) { - if(object == null) { - return null; - } - if(Language.isBaseLanguage(Env.getAD_Language(Env.getCtx()))) { - return object.get_ValueAsString(columnName); - } - // - return object.get_Translation(columnName); - } - - /** - * Validate if is numeric - * @param value - * @return - */ - public static boolean isNumeric(String value) { - if(Util.isEmpty(value, true)) { - return false; - } - // - return value.matches("[+-]?\\d*(\\.\\d+)?"); - } - - /** - * Get Int value from String - * @param value - * @return - */ - public static int getIntegerFromString(String value) { - Integer integerValue = null; - try { - integerValue = Integer.parseInt(value); - } catch (Exception e) { - - } - if(integerValue == null) { - return 0; - } - return integerValue; - } - - - /** - * Validate if is boolean - * @param value - * @return - */ - public static boolean isBoolean(String value) { - if (Util.isEmpty(value, true)) { - return false; - } - // - return value.equals("Y") - || value.equals("N") - || value.equals("Yes") - || value.equals("No") - || value.equals("true") - || value.equals("false") - ; - } - - /** - * Validate Date - * @param value - * @return - */ - public static boolean isDate(String value) { - return getDateFromString(value) != null; - } - - /** - * Is BigDecimal - * @param value - * @return - */ - public static boolean isBigDecimal(String value) { - return getBigDecimalFromString(value) != null; - } - - /** - * - * @param value - * @return - */ - public static BigDecimal getBigDecimalFromString(String value) { - BigDecimal numberValue = null; - if (Util.isEmpty(value, true)) { - return null; - } - // - try { - numberValue = new BigDecimal(value); - } catch (Exception e) { - - } - return numberValue; - } - - /** - * Get Date from String - * @param value - * @return - */ - public static Timestamp getDateFromString(String value) { - if(Util.isEmpty(value)) { - return null; - } - Date date = null; - try { - date = DisplayType.getTimestampFormat_Default().parse(value); - } catch (ParseException e) { - - } - // Convert - if(date != null) { - return new Timestamp(date.getTime()); - } - return null; - } - - public static Timestamp getTimestampFromLong(long value) { - if (value > 0) { - return new Timestamp(value); - } - return null; - } - - /** - * Get long from Timestamp - * @param value - * @return - */ - public static long getLongFromTimestamp(Timestamp value) { - if (value == null) { - return 0L; - } - return value.getTime(); - } - - - /** - * Convert string to dates - * @param date - * @return - */ - public static Timestamp convertStringToDate(String date) { - if (Util.isEmpty(date, true)) { - return null; - } - String format = DATE_FORMAT; - if(date.length() == TIME_FORMAT.length()) { - format = TIME_FORMAT; - } else if(date.length() != DATE_FORMAT.length()) { - throw new AdempiereException("Invalid date format, please use some like this: \"" + DATE_FORMAT + "\" or \"" + TIME_FORMAT + "\""); - } - SimpleDateFormat dateConverter = new SimpleDateFormat(format); - try { - Date validFromParameter = dateConverter.parse(date); - return new Timestamp(validFromParameter.getTime()); - } catch (Exception e) { - throw new AdempiereException(e); - } - } - - /** - * Convert Timestamp to String - * @param date - * @return - */ - public static String convertDateToString(Timestamp date) { - if(date == null) { - return null; - } - return new SimpleDateFormat(TIME_FORMAT).format(date); - } - - public static boolean stringToBoolean(String value) { - if (value != null && ("Y".equals(value) || "Yes".equals(value) || "true".equals(value))) { - return true; - } - return false; - } - - public static String booleanToString(String value) { - return booleanToString(stringToBoolean(value), false); - } - public static String booleanToString(String value, boolean translated) { - return booleanToString(stringToBoolean(value), translated); - } - public static String booleanToString(boolean value) { - return booleanToString(value, false); - } - public static String booleanToString(boolean value, boolean translated) { - String convertedValue = "N"; - if (value) { - convertedValue = "Y"; - } - if (translated) { - return Msg.getMsg(Env.getCtx(), convertedValue); - } - return convertedValue; - } -}