This is an automated email from the ASF dual-hosted git repository.
surajk pushed a commit to branch trunk in repository https://gitbox.apache.org/repos/asf/ofbiz-plugins.git The following commit(s) were added to refs/heads/trunk by this push: new 33d4d6c Improved: Corrected class names, method names, data members of class and variables names in plugins component. (OFBIZ-11926) Also corrected some formatting and line length related checkstyle issues. 33d4d6c is described below commit 33d4d6c915ddeb876d0ec1830feab228427bbbf6 Author: Suraj Khurana <[hidden email]> AuthorDate: Wed Aug 26 21:42:06 2020 +0530 Improved: Corrected class names, method names, data members of class and variables names in plugins component. (OFBIZ-11926) Also corrected some formatting and line length related checkstyle issues. --- .../FirstDataPaymentServices.java | 28 ++++---- .../org/apache/ofbiz/content/test/LuceneTests.java | 2 +- .../apache/ofbiz/passport/event/GitHubEvents.java | 51 +++++++------ .../ofbiz/passport/event/LinkedInEvents.java | 47 ++++++------ .../ofbiz/passport/user/GitHubAuthenticator.java | 23 +++--- .../ofbiz/passport/user/GitHubUserGroupMapper.java | 8 ++- .../ofbiz/passport/user/LinkedInAuthenticator.java | 28 +++++--- .../passport/user/LinkedInUserGroupMapper.java | 9 ++- .../apache/ofbiz/passport/util/PassportUtil.java | 83 +++++++-------------- .../ofbiz/htmlreport/sample/SampleHtmlThread.java | 13 ++-- .../java/org/apache/ofbiz/pricat/PricatEvents.java | 16 +++-- .../ofbiz/pricat/sample/SamplePricatEvents.java | 10 +-- .../org/apache/ofbiz/solr/SolrProductSearch.java | 6 +- .../main/java/org/apache/ofbiz/solr/SolrUtil.java | 84 +++++++++++----------- .../java/org/apache/ofbiz/solr/test/SolrTests.java | 66 +++++++++++------ 15 files changed, 255 insertions(+), 219 deletions(-) diff --git a/firstdatapaymentgateway/src/main/java/org/apache/ofbiz/firstdatapaymentgateway/FirstDataPaymentServices.java b/firstdatapaymentgateway/src/main/java/org/apache/ofbiz/firstdatapaymentgateway/FirstDataPaymentServices.java index 3e2467f..dc117a4 100644 --- a/firstdatapaymentgateway/src/main/java/org/apache/ofbiz/firstdatapaymentgateway/FirstDataPaymentServices.java +++ b/firstdatapaymentgateway/src/main/java/org/apache/ofbiz/firstdatapaymentgateway/FirstDataPaymentServices.java @@ -60,7 +60,7 @@ import freemarker.template.TemplateException; public class FirstDataPaymentServices { private static final String MODULE = FirstDataPaymentServices.class.getName(); - private static Properties FDProperties = null; + private static Properties fdProperties = null; public static Map<String, Object> ccAuth(DispatchContext ctx, Map<String, Object> context) { Delegator delegator = ctx.getDelegator(); @@ -103,10 +103,10 @@ public class FirstDataPaymentServices { CloseableHttpClient httpClient = HttpClients.createDefault(); StringEntity stringEntity = new StringEntity(requestBody); - HttpPost httpPost = new HttpPost(FDProperties.getProperty("transactionUrl") + "/payments"); + HttpPost httpPost = new HttpPost(fdProperties.getProperty("transactionUrl") + "/payments"); httpPost.setEntity(stringEntity); httpPost.setHeader("Client-Request-Id", clientRequestId); - httpPost.setHeader("Api-Key", FDProperties.getProperty("apiKey")); + httpPost.setHeader("Api-Key", fdProperties.getProperty("apiKey")); httpPost.setHeader("Timestamp", epochTime); httpPost.setHeader("Message-Signature", messageSignature); httpPost.setHeader("Content-Type", "application/json"); @@ -193,10 +193,10 @@ public class FirstDataPaymentServices { CloseableHttpClient httpClient = HttpClients.createDefault(); StringEntity stringEntity = new StringEntity(requestBody); - HttpPost httpPost = new HttpPost(FDProperties.getProperty("transactionUrl") + "/payments/" + authTransactionId); + HttpPost httpPost = new HttpPost(fdProperties.getProperty("transactionUrl") + "/payments/" + authTransactionId); httpPost.setEntity(stringEntity); httpPost.setHeader("Client-Request-Id", clientRequestId); - httpPost.setHeader("Api-Key", FDProperties.getProperty("apiKey")); + httpPost.setHeader("Api-Key", fdProperties.getProperty("apiKey")); httpPost.setHeader("Timestamp", epochTime); httpPost.setHeader("Message-Signature", messageSignature); httpPost.setHeader("Content-Type", "application/json"); @@ -280,10 +280,10 @@ public class FirstDataPaymentServices { CloseableHttpClient httpClient = HttpClients.createDefault(); StringEntity stringEntity = new StringEntity(requestBody); - HttpPost httpPost = new HttpPost(FDProperties.getProperty("transactionUrl") + "/payments/" + captureTransactionId); + HttpPost httpPost = new HttpPost(fdProperties.getProperty("transactionUrl") + "/payments/" + captureTransactionId); httpPost.setEntity(stringEntity); httpPost.setHeader("Client-Request-Id", clientRequestId); - httpPost.setHeader("Api-Key", FDProperties.getProperty("apiKey")); + httpPost.setHeader("Api-Key", fdProperties.getProperty("apiKey")); httpPost.setHeader("Timestamp", epochTime); httpPost.setHeader("Message-Signature", messageSignature); httpPost.setHeader("Content-Type", "application/json"); @@ -368,10 +368,10 @@ public class FirstDataPaymentServices { CloseableHttpClient httpClient = HttpClients.createDefault(); StringEntity stringEntity = new StringEntity(requestBody); - HttpPost httpPost = new HttpPost(FDProperties.getProperty("transactionUrl") + "/payments/" + releaseTransactionId); + HttpPost httpPost = new HttpPost(fdProperties.getProperty("transactionUrl") + "/payments/" + releaseTransactionId); httpPost.setEntity(stringEntity); httpPost.setHeader("Client-Request-Id", clientRequestId); - httpPost.setHeader("Api-Key", FDProperties.getProperty("apiKey")); + httpPost.setHeader("Api-Key", fdProperties.getProperty("apiKey")); httpPost.setHeader("Timestamp", epochTime); httpPost.setHeader("Message-Signature", messageSignature); httpPost.setHeader("Content-Type", "application/json"); @@ -428,8 +428,8 @@ public class FirstDataPaymentServices { props.put("apiSecret", apiSecret); //props.put("enableDataVault", enableDataVault); - if (FDProperties == null) { - FDProperties = props; + if (fdProperties == null) { + fdProperties = props; } return props; @@ -457,12 +457,12 @@ public class FirstDataPaymentServices { private static String buildMessageSignature(String paymentGatewayConfigId, String requestBody, String clientRequestId, String epochTime, Delegator delegator) { String messageSignature = null; - if (FDProperties == null) { + if (fdProperties == null) { buildFDProperties(paymentGatewayConfigId, delegator); } - String apiKey = FDProperties.getProperty("apiKey"); - final HmacUtils hmacHelper = new HmacUtils(HmacAlgorithms.HMAC_SHA_256, FDProperties.getProperty("apiSecret")); + String apiKey = fdProperties.getProperty("apiKey"); + final HmacUtils hmacHelper = new HmacUtils(HmacAlgorithms.HMAC_SHA_256, fdProperties.getProperty("apiSecret")); final Hex hexHelper = new Hex(); final String msg = apiKey + clientRequestId + epochTime + requestBody; final byte[] raw = hmacHelper.hmac(msg); diff --git a/lucene/src/main/java/org/apache/ofbiz/content/test/LuceneTests.java b/lucene/src/main/java/org/apache/ofbiz/content/test/LuceneTests.java index 253780d..e325e14 100644 --- a/lucene/src/main/java/org/apache/ofbiz/content/test/LuceneTests.java +++ b/lucene/src/main/java/org/apache/ofbiz/content/test/LuceneTests.java @@ -55,7 +55,7 @@ public class LuceneTests extends OFBizTestCase { Map<String, Object> ctx = new HashMap<>(); ctx.put("contentId", "LuceneCONTENT"); ctx.put("userLogin", getUserLogin("system")); - Map<String, Object> resp = dispatcher.runSync("indexContentTree", ctx); + Map<String, Object> resp = getDispatcher().runSync("indexContentTree", ctx); if (ServiceUtil.isError(resp)) { String errorMessage = ServiceUtil.getErrorMessage(resp); throw new Exception(errorMessage); diff --git a/passport/src/main/java/org/apache/ofbiz/passport/event/GitHubEvents.java b/passport/src/main/java/org/apache/ofbiz/passport/event/GitHubEvents.java index 84c54f8..f1e6530 100644 --- a/passport/src/main/java/org/apache/ofbiz/passport/event/GitHubEvents.java +++ b/passport/src/main/java/org/apache/ofbiz/passport/event/GitHubEvents.java @@ -68,15 +68,23 @@ public class GitHubEvents { private static final String MODULE = GitHubEvents.class.getName(); private static final String RESOURCE = "PassportUiLabels"; - public static final String AuthorizeUri = "/login/oauth/authorize"; - public static final String TokenServiceUri = "/login/oauth/access_token"; - public static final String UserApiUri = "/user"; - public static final String DEFAULT_SCOPE = "user,gist"; - public static final String ApiEndpoint = "https://api.github.com"; - public static final String TokenEndpoint = "https://github.com"; - public static final String SESSION_GITHUB_STATE = "_GITHUB_STATE_"; + private static final String AUTHORIZE_URI = "/login/oauth/authorize"; + private static final String TOKEN_SERVICE_URI = "/login/oauth/access_token"; + private static final String USER_API_URI = "/user"; + private static final String DEFAULT_SCOPE = "user,gist"; + private static final String API_END_POINT = "https://api.github.com"; + private static final String TOKEN_END_POINT = "https://github.com"; + private static final String SESSION_GITHUB_STATE = "_GITHUB_STATE_"; - public static final String envPrefix = UtilProperties.getPropertyValue(GitHubAuthenticator.props, "github.env.prefix", "test"); + public static final String ENV_PREFIX = UtilProperties.getPropertyValue(GitHubAuthenticator.PROPS, "github.env.prefix", "test"); + + public static String getApiEndPoint() { + return API_END_POINT; + } + + public static String getUserApiUri() { + return USER_API_URI; + } /** * Redirect to GitHub login page. @@ -94,7 +102,7 @@ public class GitHubEvents { try { String state = System.currentTimeMillis() + String.valueOf((new Random(10)).nextLong()); request.getSession().setAttribute(SESSION_GITHUB_STATE, state); - String redirectUrl = TokenEndpoint + AuthorizeUri + String redirectUrl = TOKEN_END_POINT + AUTHORIZE_URI + "?client_id=" + clientId + "&scope=" + DEFAULT_SCOPE + "&redirect_uri=" + URLEncoder.encode(returnURI, "UTF-8") @@ -132,7 +140,8 @@ public class GitHubEvents { String errorDescpriton = request.getParameter(PassportUtil.COMMON_ERROR_DESCRIPTION); String errMsg = null; try { - errMsg = UtilProperties.getMessage(RESOURCE, "FailedToGetGitHubAuthorizationCode", UtilMisc.toMap(PassportUtil.COMMON_ERROR, error, PassportUtil.COMMON_ERROR_DESCRIPTION, URLDecoder.decode(errorDescpriton, "UTF-8")), UtilHttp.getLocale(request)); + errMsg = UtilProperties.getMessage(RESOURCE, "FailedToGetGitHubAuthorizationCode", UtilMisc.toMap(PassportUtil.COMMON_ERROR, + error, PassportUtil.COMMON_ERROR_DESCRIPTION, URLDecoder.decode(errorDescpriton, "UTF-8")), UtilHttp.getLocale(request)); } catch (UnsupportedEncodingException e) { errMsg = UtilProperties.getMessage(RESOURCE, "GitHubGetAuthorizationCodeError", UtilHttp.getLocale(request)); } @@ -158,9 +167,9 @@ public class GitHubEvents { try { URI uri = new URIBuilder() - .setScheme(TokenEndpoint.substring(0, TokenEndpoint.indexOf(":"))) - .setHost(TokenEndpoint.substring(TokenEndpoint.indexOf(":") + 3)) - .setPath(TokenServiceUri) + .setScheme(TOKEN_END_POINT.substring(0, TOKEN_END_POINT.indexOf(":"))) + .setHost(TOKEN_END_POINT.substring(TOKEN_END_POINT.indexOf(":") + 3)) + .setPath(TOKEN_SERVICE_URI) .setParameter("client_id", clientId) .setParameter("client_secret", secret) .setParameter("code", authorizationCode) @@ -169,7 +178,7 @@ public class GitHubEvents { HttpPost postMethod = new HttpPost(uri); CloseableHttpClient jsonClient = HttpClients.custom().build(); // Debug.logInfo("GitHub get access token query string: " + postMethod.getURI(), MODULE); - postMethod.setConfig(PassportUtil.StandardRequestConfig); + postMethod.setConfig(PassportUtil.STANDARD_REQ_CONFIG); postMethod.setHeader(PassportUtil.ACCEPT_HEADER, "application/json"); CloseableHttpResponse postResponse = jsonClient.execute(postMethod); String responseString = new BasicResponseHandler().handleResponse(postResponse); @@ -185,7 +194,8 @@ public class GitHubEvents { // Debug.logInfo("Generated Access Token : " + accessToken, MODULE); // Debug.logInfo("Token Type: " + tokenType, MODULE); } else { - String errMsg = UtilProperties.getMessage(RESOURCE, "GitHubGetOAuth2AccessTokenError", UtilMisc.toMap("error", responseString), UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "GitHubGetOAuth2AccessTokenError", + UtilMisc.toMap("error", responseString), UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } @@ -195,7 +205,7 @@ public class GitHubEvents { } // Get User Profile - HttpGet getMethod = new HttpGet(ApiEndpoint + UserApiUri); + HttpGet getMethod = new HttpGet(API_END_POINT + USER_API_URI); Map<String, Object> userInfo = null; try { userInfo = GitHubAuthenticator.getUserInfo(getMethod, accessToken, tokenType, UtilHttp.getLocale(request)); @@ -229,8 +239,8 @@ public class GitHubEvents { gitHubUser.set("accessToken", accessToken); dataChanged = true; } - if (!envPrefix.equals(gitHubUser.getString("envPrefix"))) { - gitHubUser.set("envPrefix", envPrefix); + if (!ENV_PREFIX.equals(gitHubUser.getString("ENV_PREFIX"))) { + gitHubUser.set("envPrefix", ENV_PREFIX); dataChanged = true; } if (!productStoreId.equals(gitHubUser.getString("productStoreId"))) { @@ -247,7 +257,7 @@ public class GitHubEvents { } else { gitHubUser = delegator.makeValue("GitHubUser", UtilMisc.toMap("accessToken", accessToken, "productStoreId", productStoreId, - "envPrefix", envPrefix, + "envPrefix", ENV_PREFIX, "gitHubUserId", gitHubUserId)); try { gitHubUser.create(); @@ -263,7 +273,8 @@ public class GitHubEvents { String userLoginId = authn.createUser(userInfo); userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", userLoginId).queryOne(); } - String autoPassword = RandomStringUtils.randomAlphanumeric(EntityUtilProperties.getPropertyAsInteger("security", "password.length.min", 5)); + String autoPassword = RandomStringUtils.randomAlphanumeric(EntityUtilProperties.getPropertyAsInteger("security", + "password.length.min", 5)); boolean useEncryption = "true".equals(UtilProperties.getPropertyValue("security", "password.encrypt")); userLogin.set("currentPassword", useEncryption ? HashCrypt.digestHash(LoginServices.getHashType(), null, autoPassword) : autoPassword); userLogin.store(); diff --git a/passport/src/main/java/org/apache/ofbiz/passport/event/LinkedInEvents.java b/passport/src/main/java/org/apache/ofbiz/passport/event/LinkedInEvents.java index 88ef883..48e6f37 100644 --- a/passport/src/main/java/org/apache/ofbiz/passport/event/LinkedInEvents.java +++ b/passport/src/main/java/org/apache/ofbiz/passport/event/LinkedInEvents.java @@ -71,13 +71,13 @@ public class LinkedInEvents { private static final String MODULE = LinkedInEvents.class.getName(); private static final String RESOURCE = "PassportUiLabels"; - public static final String AuthorizeUri = "/uas/oauth2/authorization"; - public static final String TokenServiceUri = "/uas/oauth2/accessToken"; - public static final String UserApiUri = "/v1/people/~"; + public static final String AUTHORIZE_URI = "/uas/oauth2/authorization"; + public static final String TOKEN_SERVICE_URI = "/uas/oauth2/accessToken"; + public static final String USER_API_URI = "/v1/people/~"; public static final String DEFAULT_SCOPE = "r_basicprofile%20r_emailaddress"; - public static final String TokenEndpoint = "https://www.linkedin.com"; + public static final String TOKEN_END_POINT = "https://www.linkedin.com"; public static final String SESSION_LINKEDIN_STATE = "_LINKEDIN_STATE_"; - public static final String envPrefix = UtilProperties.getPropertyValue(LinkedInAuthenticator.props, "linkedin.env.prefix", "test"); + public static final String ENV_PREFIX = UtilProperties.getPropertyValue(LinkedInAuthenticator.getPROPS(), "linkedin.env.prefix", "test"); /** * Redirect to LinkedIn login page. @@ -89,14 +89,14 @@ public class LinkedInEvents { return "error"; } - String clientId = oauth2LinkedIn.getString(PassportUtil.ApiKeyLabel); - String returnURI = oauth2LinkedIn.getString(envPrefix + PassportUtil.ReturnUrlLabel); + String clientId = oauth2LinkedIn.getString(PassportUtil.API_KEY_LABEL); + String returnURI = oauth2LinkedIn.getString(ENV_PREFIX + PassportUtil.RETURN_URL_LABEL); // Get user authorization code try { String state = System.currentTimeMillis() + String.valueOf((new Random(10)).nextLong()); request.getSession().setAttribute(SESSION_LINKEDIN_STATE, state); - String redirectUrl = TokenEndpoint + AuthorizeUri + String redirectUrl = TOKEN_END_POINT + AUTHORIZE_URI + "?client_id=" + clientId + "&response_type=code" + "&scope=" + DEFAULT_SCOPE @@ -134,7 +134,8 @@ public class LinkedInEvents { String errorDescpriton = request.getParameter(PassportUtil.COMMON_ERROR_DESCRIPTION); String errMsg = null; try { - errMsg = UtilProperties.getMessage(RESOURCE, "LinkedInFailedToGetAuthorizationCode", UtilMisc.toMap(PassportUtil.COMMON_ERROR, error, PassportUtil.COMMON_ERROR_DESCRIPTION, URLDecoder.decode(errorDescpriton, "UTF-8")), UtilHttp.getLocale(request)); + errMsg = UtilProperties.getMessage(RESOURCE, "LinkedInFailedToGetAuthorizationCode", UtilMisc.toMap(PassportUtil.COMMON_ERROR, + error, PassportUtil.COMMON_ERROR_DESCRIPTION, URLDecoder.decode(errorDescpriton, "UTF-8")), UtilHttp.getLocale(request)); } catch (UnsupportedEncodingException e) { errMsg = UtilProperties.getMessage(RESOURCE, "LinkedInGetAuthorizationCodeError", UtilHttp.getLocale(request)); } @@ -149,9 +150,9 @@ public class LinkedInEvents { request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } - String clientId = oauth2LinkedIn.getString(PassportUtil.ApiKeyLabel); - String secret = oauth2LinkedIn.getString(PassportUtil.SecretKeyLabel); - String returnURI = oauth2LinkedIn.getString(envPrefix + PassportUtil.ReturnUrlLabel); + String clientId = oauth2LinkedIn.getString(PassportUtil.API_KEY_LABEL); + String secret = oauth2LinkedIn.getString(PassportUtil.SECRET_KEY_LABEL); + String returnURI = oauth2LinkedIn.getString(ENV_PREFIX + PassportUtil.RETURN_URL_LABEL); // Grant token from authorization code and oauth2 token // Use the authorization code to obtain an access token @@ -159,9 +160,9 @@ public class LinkedInEvents { try { URI uri = new URIBuilder() - .setScheme(TokenEndpoint.substring(0, TokenEndpoint.indexOf(":"))) - .setHost(TokenEndpoint.substring(TokenEndpoint.indexOf(":") + 3)) - .setPath(TokenServiceUri) + .setScheme(TOKEN_END_POINT.substring(0, TOKEN_END_POINT.indexOf(":"))) + .setHost(TOKEN_END_POINT.substring(TOKEN_END_POINT.indexOf(":") + 3)) + .setPath(TOKEN_SERVICE_URI) .setParameter("client_id", clientId) .setParameter("client_secret", secret) .setParameter("grant_type", "authorization_code") @@ -171,7 +172,7 @@ public class LinkedInEvents { HttpPost postMethod = new HttpPost(uri); CloseableHttpClient jsonClient = HttpClients.custom().build(); // Debug.logInfo("LinkedIn get access token query string: " + postMethod.getURI(), MODULE); - postMethod.setConfig(PassportUtil.StandardRequestConfig); + postMethod.setConfig(PassportUtil.STANDARD_REQ_CONFIG); CloseableHttpResponse postResponse = jsonClient.execute(postMethod); String responseString = new BasicResponseHandler().handleResponse(postResponse); // Debug.logInfo("LinkedIn get access token response code: " + postResponse.getStatusLine().getStatusCode(), MODULE); @@ -184,7 +185,8 @@ public class LinkedInEvents { accessToken = (String) userMap.get("access_token"); // Debug.logInfo("Generated Access Token : " + accessToken, MODULE); } else { - String errMsg = UtilProperties.getMessage(RESOURCE, "LinkedInGetOAuth2AccessTokenError", UtilMisc.toMap("error", responseString), UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "LinkedInGetOAuth2AccessTokenError", UtilMisc.toMap("error", + responseString), UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } @@ -194,7 +196,7 @@ public class LinkedInEvents { } // Get User Profile - HttpGet getMethod = new HttpGet(TokenEndpoint + UserApiUri + "?oauth2_access_token=" + accessToken); + HttpGet getMethod = new HttpGet(TOKEN_END_POINT + USER_API_URI + "?oauth2_access_token=" + accessToken); Document userInfo = null; try { userInfo = LinkedInAuthenticator.getUserInfo(getMethod, UtilHttp.getLocale(request)); @@ -228,8 +230,8 @@ public class LinkedInEvents { linkedInUser.set("accessToken", accessToken); dataChanged = true; } - if (!envPrefix.equals(linkedInUser.getString("envPrefix"))) { - linkedInUser.set("envPrefix", envPrefix); + if (!ENV_PREFIX.equals(linkedInUser.getString("ENV_PREFIX"))) { + linkedInUser.set("ENV_PREFIX", ENV_PREFIX); dataChanged = true; } if (!productStoreId.equals(linkedInUser.getString("productStoreId"))) { @@ -246,7 +248,7 @@ public class LinkedInEvents { } else { linkedInUser = delegator.makeValue("LinkedInUser", UtilMisc.toMap("accessToken", accessToken, "productStoreId", productStoreId, - "envPrefix", envPrefix, + "ENV_PREFIX", ENV_PREFIX, "linkedInUserId", linkedInUserId)); try { linkedInUser.create(); @@ -262,7 +264,8 @@ public class LinkedInEvents { String userLoginId = authn.createUser(userInfo); userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", userLoginId).queryOne(); } - String autoPassword = RandomStringUtils.randomAlphanumeric(EntityUtilProperties.getPropertyAsInteger("security", "password.length.min", 5)); + String autoPassword = RandomStringUtils.randomAlphanumeric(EntityUtilProperties.getPropertyAsInteger("security", + "password.length.min", 5)); boolean useEncryption = "true".equals(UtilProperties.getPropertyValue("security", "password.encrypt")); userLogin.set("currentPassword", useEncryption ? HashCrypt.digestHash(LoginServices.getHashType(), null, autoPassword) : autoPassword); userLogin.store(); diff --git a/passport/src/main/java/org/apache/ofbiz/passport/user/GitHubAuthenticator.java b/passport/src/main/java/org/apache/ofbiz/passport/user/GitHubAuthenticator.java index 1467b49..d09cebb 100644 --- a/passport/src/main/java/org/apache/ofbiz/passport/user/GitHubAuthenticator.java +++ b/passport/src/main/java/org/apache/ofbiz/passport/user/GitHubAuthenticator.java @@ -63,13 +63,13 @@ public class GitHubAuthenticator implements Authenticator { private static final String MODULE = GitHubAuthenticator.class.getName(); - public static final String props = "gitHubAuth.properties"; + public static final String PROPS = "gitHubAuth.properties"; private static final String RESOURCE = "PassportUiLabels"; - protected LocalDispatcher dispatcher; + private LocalDispatcher dispatcher; - protected Delegator delegator; + private Delegator delegator; /** * Method called when authenticator is first initialized (the delegator @@ -106,7 +106,7 @@ public class GitHubAuthenticator implements Authenticator { String accessToken = gitHubUser.getString("accessToken"); String tokenType = gitHubUser.getString("tokenType"); if (UtilValidate.isNotEmpty(accessToken)) { - getMethod = new HttpGet(GitHubEvents.ApiEndpoint + GitHubEvents.UserApiUri); + getMethod = new HttpGet(GitHubEvents.getApiEndPoint() + GitHubEvents.getUserApiUri()); user = GitHubAuthenticator.getUserInfo(getMethod, accessToken, tokenType, Locale.getDefault()); } } @@ -212,7 +212,7 @@ public class GitHubAuthenticator implements Authenticator { String accessToken = gitHubUser.getString("accessToken"); String tokenType = gitHubUser.getString("tokenType"); if (UtilValidate.isNotEmpty(accessToken)) { - getMethod = new HttpGet(GitHubEvents.ApiEndpoint + GitHubEvents.UserApiUri); + getMethod = new HttpGet(GitHubEvents.getApiEndPoint() + GitHubEvents.getUserApiUri()); user = getUserInfo(getMethod, accessToken, tokenType, Locale.getDefault()); } } @@ -222,6 +222,12 @@ public class GitHubAuthenticator implements Authenticator { return user; } + /** + * Create user string. + * @param userMap the user map + * @return the string + * @throws AuthenticatorException the authenticator exception + */ public String createUser(Map<String, Object> userMap) throws AuthenticatorException { GenericValue system; try { @@ -369,12 +375,13 @@ public class GitHubAuthenticator implements Authenticator { */ @Override public boolean isEnabled() { - return "true".equalsIgnoreCase(UtilProperties.getPropertyValue(props, "github.authenticator.enabled", "true")); + return "true".equalsIgnoreCase(UtilProperties.getPropertyValue(PROPS, "github.authenticator.enabled", "true")); } - public static Map<String, Object> getUserInfo(HttpGet httpGet, String accessToken, String tokenType, Locale locale) throws AuthenticatorException { + public static Map<String, Object> getUserInfo(HttpGet httpGet, String accessToken, String tokenType, Locale locale) + throws AuthenticatorException { JSON userInfo = null; - httpGet.setConfig(PassportUtil.StandardRequestConfig); + httpGet.setConfig(PassportUtil.STANDARD_REQ_CONFIG); CloseableHttpClient jsonClient = HttpClients.custom().build(); httpGet.setHeader(PassportUtil.AUTHORIZATION_HEADER, tokenType + " " + accessToken); httpGet.setHeader(PassportUtil.ACCEPT_HEADER, "application/json"); diff --git a/passport/src/main/java/org/apache/ofbiz/passport/user/GitHubUserGroupMapper.java b/passport/src/main/java/org/apache/ofbiz/passport/user/GitHubUserGroupMapper.java index 20ab400..7d2b9f1 100644 --- a/passport/src/main/java/org/apache/ofbiz/passport/user/GitHubUserGroupMapper.java +++ b/passport/src/main/java/org/apache/ofbiz/passport/user/GitHubUserGroupMapper.java @@ -32,7 +32,7 @@ import org.apache.ofbiz.base.util.UtilProperties; */ public class GitHubUserGroupMapper { - protected List<String> groups; + private List<String> groups; public GitHubUserGroupMapper(String[] groups) { this.groups = Arrays.asList(groups); @@ -45,8 +45,12 @@ public class GitHubUserGroupMapper { groups.add(group); } + /** + * Gets security groups. + * @return the security groups + */ public Set<String> getSecurityGroups() { - Properties props = UtilProperties.getProperties(GitHubAuthenticator.props); + Properties props = UtilProperties.getProperties(GitHubAuthenticator.PROPS); Set<String> secGroups = new HashSet<>(); boolean running = true; diff --git a/passport/src/main/java/org/apache/ofbiz/passport/user/LinkedInAuthenticator.java b/passport/src/main/java/org/apache/ofbiz/passport/user/LinkedInAuthenticator.java index 89ac486..6645cf0 100644 --- a/passport/src/main/java/org/apache/ofbiz/passport/user/LinkedInAuthenticator.java +++ b/passport/src/main/java/org/apache/ofbiz/passport/user/LinkedInAuthenticator.java @@ -65,13 +65,14 @@ public class LinkedInAuthenticator implements Authenticator { private static final String MODULE = LinkedInAuthenticator.class.getName(); - public static final String props = "linkedInAuth.properties"; + public static String getPROPS() { + return PROPS; + } + private static final String PROPS = "linkedInAuth.properties"; private static final String RESOURCE = "PassportUiLabels"; - - protected LocalDispatcher dispatcher; - - protected Delegator delegator; + private LocalDispatcher dispatcher; + private Delegator delegator; /** * Method called when authenticator is first initialized (the delegator @@ -107,7 +108,7 @@ public class LinkedInAuthenticator implements Authenticator { if (linkedInUser != null) { String accessToken = linkedInUser.getString("accessToken"); if (UtilValidate.isNotEmpty(accessToken)) { - getMethod = new HttpGet(LinkedInEvents.TokenEndpoint + LinkedInEvents.UserApiUri + "?oauth2_access_token=" + accessToken); + getMethod = new HttpGet(LinkedInEvents.TOKEN_END_POINT + LinkedInEvents.USER_API_URI + "?oauth2_access_token=" + accessToken); user = LinkedInAuthenticator.getUserInfo(getMethod, Locale.getDefault()); } } @@ -215,7 +216,7 @@ public class LinkedInAuthenticator implements Authenticator { if (linkedInUser != null) { String accessToken = linkedInUser.getString("accessToken"); if (UtilValidate.isNotEmpty(accessToken)) { - getMethod = new HttpGet(LinkedInEvents.TokenEndpoint + LinkedInEvents.UserApiUri + "?oauth2_access_token=" + accessToken); + getMethod = new HttpGet(LinkedInEvents.TOKEN_END_POINT + LinkedInEvents.USER_API_URI + "?oauth2_access_token=" + accessToken); user = getUserInfo(getMethod, Locale.getDefault()); } } @@ -231,6 +232,12 @@ public class LinkedInAuthenticator implements Authenticator { return user; } + /** + * Create user string. + * @param user the user + * @return the string + * @throws AuthenticatorException the authenticator exception + */ public String createUser(Document user) throws AuthenticatorException { GenericValue system; try { @@ -382,12 +389,13 @@ public class LinkedInAuthenticator implements Authenticator { */ @Override public boolean isEnabled() { - return "true".equalsIgnoreCase(UtilProperties.getPropertyValue(props, "linked.authenticator.enabled", "true")); + return "true".equalsIgnoreCase(UtilProperties.getPropertyValue(PROPS, "linked.authenticator.enabled", "true")); } - public static Document getUserInfo(HttpGet httpGet, Locale locale) throws IOException, AuthenticatorException, SAXException, ParserConfigurationException { + public static Document getUserInfo(HttpGet httpGet, Locale locale) + throws IOException, AuthenticatorException, SAXException, ParserConfigurationException { Document userInfo = null; - httpGet.setConfig(PassportUtil.StandardRequestConfig); + httpGet.setConfig(PassportUtil.STANDARD_REQ_CONFIG); CloseableHttpClient jsonClient = HttpClients.custom().build(); CloseableHttpResponse getResponse = jsonClient.execute(httpGet); String responseString = new BasicResponseHandler().handleResponse(getResponse); diff --git a/passport/src/main/java/org/apache/ofbiz/passport/user/LinkedInUserGroupMapper.java b/passport/src/main/java/org/apache/ofbiz/passport/user/LinkedInUserGroupMapper.java index a2896c5..f19ee48 100644 --- a/passport/src/main/java/org/apache/ofbiz/passport/user/LinkedInUserGroupMapper.java +++ b/passport/src/main/java/org/apache/ofbiz/passport/user/LinkedInUserGroupMapper.java @@ -32,8 +32,7 @@ import org.apache.ofbiz.base.util.UtilProperties; */ public class LinkedInUserGroupMapper { - protected List<String> groups; - + private List<String> groups; public LinkedInUserGroupMapper(String[] groups) { this.groups = Arrays.asList(groups); } @@ -45,8 +44,12 @@ public class LinkedInUserGroupMapper { groups.add(group); } + /** + * Gets security groups. + * @return the security groups + */ public Set<String> getSecurityGroups() { - Properties props = UtilProperties.getProperties(LinkedInAuthenticator.props); + Properties props = UtilProperties.getProperties(LinkedInAuthenticator.getPROPS()); Set<String> secGroups = new HashSet<>(); boolean running = true; diff --git a/passport/src/main/java/org/apache/ofbiz/passport/util/PassportUtil.java b/passport/src/main/java/org/apache/ofbiz/passport/util/PassportUtil.java index 6cd56a2..e0f4f2b 100644 --- a/passport/src/main/java/org/apache/ofbiz/passport/util/PassportUtil.java +++ b/passport/src/main/java/org/apache/ofbiz/passport/util/PassportUtil.java @@ -29,68 +29,39 @@ import org.apache.ofbiz.base.util.Debug; public class PassportUtil { private static final String MODULE = PassportUtil.class.getName(); - - public static final String ClientIdLabel = "ClientId"; - - public static final String SecretLabel = "Secret"; - - public static final String ReturnUrlLabel = "ReturnUrl"; - - public static final String TokenEndpointLabel = "TokenEndpoint"; - - public static final String GrantTypeLabel = "grantType"; - - public static final String ContentTypeLabel = "contentType"; - + private static final String CLIENT_ID_LABEL = "ClientId"; + private static final String SECRET_LABEL = "Secret"; + private static final String TOKEN_END_POINT_LABEL = "TokenEndpoint"; + private static final String GRANT_TYPE_LABEL = "grantType"; + private static final String CONTENT_TYPE_LABEL = "contentType"; + private static final String USER_PROFILE_URL_LABEL = "UserProfileUrl"; + private static final String GRANT_TYPE_PARAM = "grant_type"; + private static final String CONTENT_TYPE_PARAM = "Content-Type"; + private static final String APPLICATION_JSON = "application/json"; + private static final String RESTAPI_END_POINT_LABEL = "RESTApiEndpoint"; + private static final String COMMON_SCOPE = "scope"; + private static final String AUTHOR_CODE_GRANT_TYPE = "authorization_code"; + private static final String API_ID_LABEL = "apiId"; + private static final String APP_KEY_LABEL = "appKey"; + private static final String APP_SECRET_LABEL = "appSecret"; + private static final String APP_ID_LABEL = "appId"; + private static final String COMMON_APP_KEY = "AppKey"; + private static final String COMMON_APP_SECRET = "AppSecret"; + + // TODO: Following should be made private + public static final String COMMON_CLIENT_SECRET = "clientSecret"; + public static final String COMMON_CODE = "code"; + public static final String RETURN_URL_LABEL = "ReturnUrl"; public static final String AUTHORIZATION_HEADER = "Authorization"; - - public static final String UserProfileUrlLabel = "UserProfileUrl"; - - public static final String GrantTypeParam = "grant_type"; - - public static final String ContentTypeParam = "Content-Type"; - public static final String ACCEPT_HEADER = "Accept"; - - public static final String APPLICATION_JSON = "application/json"; - - public static final String RESTApiEndpointLabel = "RESTApiEndpoint"; - - public static final String COMMON_CODE = "code"; - - public static final String COMMON_SCOPE = "scope"; - - public static final String AuthorizationCodeGrantType = "authorization_code"; - public static final String COMMON_STATE = "state"; - public static final String COMMON_ERROR = "error"; - public static final String COMMON_ERROR_DESCRIPTION = "error_description"; - - public static final String ApiKeyLabel = "apiKey"; - - public static final String SecretKeyLabel = "secretKey"; - + public static final String API_KEY_LABEL = "apiKey"; + public static final String SECRET_KEY_LABEL = "secretKey"; public static final String COMMON_CLIENT_ID = "clientId"; - public static final String COMMON_RETURN_RUL = "returnUrl"; - - public static final String COMMON_CLIENT_SECRET = "clientSecret"; - - public static final String ApiIdLabel = "apiId"; - - public static final String AppKeyLabel = "appKey"; - - public static final String AppSecretLabel = "appSecret"; - - public static final String AppIdLabel = "appId"; - - public static final String COMMON_APP_KEY = "AppKey"; - - public static final String COMMON_APP_SECRET = "AppSecret"; - - public static final RequestConfig StandardRequestConfig = RequestConfig.custom() + public static final RequestConfig STANDARD_REQ_CONFIG = RequestConfig.custom() .setCookieSpec(CookieSpecs.STANDARD) .build(); @@ -103,7 +74,7 @@ public class PassportUtil { } public static String getEnvPrefixByHost(HttpServletRequest request) { - String prefix ="test"; + String prefix = "test"; try { InetAddress[] addresses = InetAddress.getAllByName(request.getServerName()); for (InetAddress address : addresses) { diff --git a/pricat/src/main/java/org/apache/ofbiz/htmlreport/sample/SampleHtmlThread.java b/pricat/src/main/java/org/apache/ofbiz/htmlreport/sample/SampleHtmlThread.java index d2f73d0..5528e28 100644 --- a/pricat/src/main/java/org/apache/ofbiz/htmlreport/sample/SampleHtmlThread.java +++ b/pricat/src/main/java/org/apache/ofbiz/htmlreport/sample/SampleHtmlThread.java @@ -40,8 +40,9 @@ public class SampleHtmlThread extends AbstractReportThread { public static final String COUNT_DOWN = "countdown"; public static final String COUNT_UP = "countup"; public static final String CONFIRM = "confirm_action"; - public static final String[] messageLables = new String[] {"FORMAT_DEFAULT", "FORMAT_WARNING", "FORMAT_HEADLINE", "FORMAT_NOTE", "FORMAT_OK", "FORMAT_ERROR", "FORMAT_THROWABLE"}; - public static final List<String> messages = Collections.unmodifiableList(Arrays.asList(messageLables)); + public static final String[] MESSAGE_LABLES = new String[] {"FORMAT_DEFAULT", "FORMAT_WARNING", "FORMAT_HEADLINE", "FORMAT_NOTE", + "FORMAT_OK", "FORMAT_ERROR", "FORMAT_THROWABLE"}; + public static final List<String> MESSAGES = Collections.unmodifiableList(Arrays.asList(MESSAGE_LABLES)); private static final String RESOURCE = "PricatUiLabels"; /** * Constructor, creates a new HtmlImportThreat. @@ -67,9 +68,9 @@ public class SampleHtmlThread extends AbstractReportThread { sleep(20); j = random.nextInt(7); if (j == 6) { - getReport().println(new Throwable(UtilProperties.getMessage(RESOURCE, messages.get(j), new Object[] {i}, getLocale()))); + getReport().println(new Throwable(UtilProperties.getMessage(RESOURCE, MESSAGES.get(j), new Object[] {i}, getLocale()))); } else { - getReport().println(UtilProperties.getMessage(RESOURCE, messages.get(j), new Object[] {i}, getLocale()), j); + getReport().println(UtilProperties.getMessage(RESOURCE, MESSAGES.get(j), new Object[] {i}, getLocale()), j); } } getReport().println(UtilProperties.getMessage(RESOURCE, "COUNT_COMPLETED", getLocale()), InterfaceReport.FORMAT_HEADLINE); @@ -81,9 +82,9 @@ public class SampleHtmlThread extends AbstractReportThread { sleep(20); j = random.nextInt(7); if (j == 6) { - getReport().println(new Throwable(UtilProperties.getMessage(RESOURCE, messages.get(j), new Object[] {i}, getLocale()))); + getReport().println(new Throwable(UtilProperties.getMessage(RESOURCE, MESSAGES.get(j), new Object[] {i}, getLocale()))); } else { - getReport().println(UtilProperties.getMessage(RESOURCE, messages.get(j), new Object[] {i}, getLocale()), j); + getReport().println(UtilProperties.getMessage(RESOURCE, MESSAGES.get(j), new Object[] {i}, getLocale()), j); } } getReport().println(UtilProperties.getMessage(RESOURCE, "COUNT_COMPLETED", getLocale()), InterfaceReport.FORMAT_HEADLINE); diff --git a/pricat/src/main/java/org/apache/ofbiz/pricat/PricatEvents.java b/pricat/src/main/java/org/apache/ofbiz/pricat/PricatEvents.java index 42b6ebe..b345d07 100644 --- a/pricat/src/main/java/org/apache/ofbiz/pricat/PricatEvents.java +++ b/pricat/src/main/java/org/apache/ofbiz/pricat/PricatEvents.java @@ -42,9 +42,9 @@ import org.apache.ofbiz.entity.util.EntityQuery; public class PricatEvents { private static final String MODULE = PricatEvents.class.getName(); - public static final String PricatLatestVersion = UtilProperties.getPropertyValue("pricat", "pricat.latest.version", "V1.1"); - public static final String PricatFileName = "PricatTemplate_" + PricatLatestVersion + ".xlsx"; - public static final String PricatPath = "component://pricat/webapp/pricat/downloads/"; + public static final String PRICAT_LATEST_VERSION = UtilProperties.getPropertyValue("pricat", "pricat.latest.version", "V1.1"); + public static final String PRICAT_FILE_NAME = "PricatTemplate_" + PRICAT_LATEST_VERSION + ".xlsx"; + public static final String PRICAT_PATH = "component://pricat/webapp/pricat/downloads/"; /** * Download excel template. * @param request @@ -56,10 +56,10 @@ public class PricatEvents { return "error"; } try { - String path = ComponentLocationResolver.getBaseLocation(PricatPath).toString(); + String path = ComponentLocationResolver.getBaseLocation(PRICAT_PATH).toString(); String fileName = null; if ("pricatExcelTemplate".equals(templateType)) { - fileName = PricatFileName; + fileName = PRICAT_FILE_NAME; } if (UtilValidate.isEmpty(fileName)) { return "error"; @@ -104,7 +104,8 @@ public class PricatEvents { Path path = Paths.get(pricatFileName); byte[] bytes = Files.readAllBytes(path); path = Paths.get(originalPricatFileName); - UtilHttp.streamContentToBrowser(response, bytes, "application/octet-stream", URLEncoder.encode(path.getName(path.getNameCount() - 1).toString(), "UTF-8")); + UtilHttp.streamContentToBrowser(response, bytes, "application/octet-stream", + URLEncoder.encode(path.getName(path.getNameCount() - 1).toString(), "UTF-8")); } catch (IOException e) { Debug.logError(e.getMessage(), MODULE); return "error"; @@ -134,7 +135,8 @@ public class PricatEvents { Delegator delegator = (Delegator) request.getAttribute("delegator"); GenericValue historyValue = null; try { - historyValue = EntityQuery.use(delegator).from("ExcelImportHistory").where("userLoginId", userLoginId, "sequenceNum", Long.valueOf(sequenceNum)).queryOne(); + historyValue = EntityQuery.use(delegator).from("ExcelImportHistory").where("userLoginId", userLoginId, "sequenceNum", + Long.valueOf(sequenceNum)).queryOne(); } catch (NumberFormatException | GenericEntityException e) { Debug.logError(e.getMessage(), MODULE); return "error"; diff --git a/pricat/src/main/java/org/apache/ofbiz/pricat/sample/SamplePricatEvents.java b/pricat/src/main/java/org/apache/ofbiz/pricat/sample/SamplePricatEvents.java index faef64c..650243f 100644 --- a/pricat/src/main/java/org/apache/ofbiz/pricat/sample/SamplePricatEvents.java +++ b/pricat/src/main/java/org/apache/ofbiz/pricat/sample/SamplePricatEvents.java @@ -36,9 +36,9 @@ import org.apache.ofbiz.pricat.PricatEvents; public class SamplePricatEvents extends PricatEvents { private static final String MODULE = SamplePricatEvents.class.getName(); - public static final String PricatLatestVersion = UtilProperties.getPropertyValue("pricat", "pricat.latest.version", "V1.1"); - public static final String DemoPricatFileName = "SamplePricatTemplate_" + PricatLatestVersion + ".xlsx"; - public static final String DemoPricatPath = "component://pricat/webapp/pricatdemo/downloads/"; + public static final String PRICAT_LAT_VERSION = UtilProperties.getPropertyValue("pricat", "pricat.latest.version", "V1.1"); + public static final String DEMO_PRICATE_FILE_NAME = "SamplePricatTemplate_" + PRICAT_LAT_VERSION + ".xlsx"; + public static final String DEMO_PRICATE_PATH = "component://pricat/webapp/pricatdemo/downloads/"; /** * Download excel template. * @param request @@ -51,10 +51,10 @@ public class SamplePricatEvents extends PricatEvents { return "error"; } try { - String path = ComponentLocationResolver.getBaseLocation(DemoPricatPath).toString(); + String path = ComponentLocationResolver.getBaseLocation(DEMO_PRICATE_PATH).toString(); String fileName = null; if ("pricatExcelTemplate".equals(templateType)) { - fileName = DemoPricatFileName; + fileName = DEMO_PRICATE_FILE_NAME; } if (UtilValidate.isEmpty(fileName)) { return "error"; diff --git a/solr/src/main/java/org/apache/ofbiz/solr/SolrProductSearch.java b/solr/src/main/java/org/apache/ofbiz/solr/SolrProductSearch.java index 670c879..28dd9e6 100644 --- a/solr/src/main/java/org/apache/ofbiz/solr/SolrProductSearch.java +++ b/solr/src/main/java/org/apache/ofbiz/solr/SolrProductSearch.java @@ -488,8 +488,9 @@ public abstract class SolrProductSearch { Map<String, Long> facetEntry = new HashMap<>(); List<FacetField.Count> facetEntries = facet.getValues(); if (UtilValidate.isNotEmpty(facetEntries)) { - for (FacetField.Count fcount : facetEntries) + for (FacetField.Count fcount : facetEntries) { facetEntry.put(fcount.getName(), fcount.getCount()); + } facetFields.put(facet.getName(), facetEntry); } } @@ -518,8 +519,9 @@ public abstract class SolrProductSearch { String solrIndexName = (String) context.get("indexName"); try { boolean displayProducts = false; - if (UtilValidate.isNotEmpty(context.get("displayProducts"))) + if (UtilValidate.isNotEmpty(context.get("displayProducts"))) { displayProducts = (Boolean) context.get("displayProducts"); + } int viewIndex = 0; int viewSize = 9; diff --git a/solr/src/main/java/org/apache/ofbiz/solr/SolrUtil.java b/solr/src/main/java/org/apache/ofbiz/solr/SolrUtil.java index 4474471..4c0d234 100644 --- a/solr/src/main/java/org/apache/ofbiz/solr/SolrUtil.java +++ b/solr/src/main/java/org/apache/ofbiz/solr/SolrUtil.java @@ -54,47 +54,50 @@ public final class SolrUtil { private SolrUtil() { } private static final String MODULE = SolrUtil.class.getName(); - private static final String[] solrProdAttribute = {"productId", "internalName", "manu", "size", "smallImage", "mediumImage", "largeImage", "listPrice", "defaultPrice", "inStock", "isVirtual" }; + private static final String[] SOLR_PRODUCT_ATTRIBUTE = {"productId", "internalName", "manu", "size", "smallImage", "mediumImage", "largeImage", + "listPrice", "defaultPrice", "inStock", "isVirtual" }; - private static final String solrConfigName = "solrconfig.properties"; - private static final String solrUrl = makeSolrWebappUrl(); + private static final String SOLR_CONFIG_NAME = "solrconfig.properties"; + private static final String SOLR_URL = makeSolrWebappUrl(); - private static final String socketTimeoutString = UtilProperties.getPropertyValue(solrConfigName, "solr.client.socket.timeout"); + private static final String SOCKET_TIMEOUT_STRING = UtilProperties.getPropertyValue(SOLR_CONFIG_NAME, "solr.client.socket.timeout"); - private static final String connectionTimeoutString = UtilProperties.getPropertyValue(solrConfigName, "solr.client.connection.timeout"); + private static final String CON_TIMEOUT_STRING = UtilProperties.getPropertyValue(SOLR_CONFIG_NAME, "solr.client.connection.timeout"); - private static final String clientUsername = UtilProperties.getPropertyValue(solrConfigName, "solr.client.username"); + private static final String CLIENT_USER_NAME = UtilProperties.getPropertyValue(SOLR_CONFIG_NAME, "solr.client.username"); - private static final String clientPassword = UtilProperties.getPropertyValue(solrConfigName, "solr.client.password"); + private static final String CLIENT_PASSWORD = UtilProperties.getPropertyValue(SOLR_CONFIG_NAME, "solr.client.password"); - private static final Integer socketTimeout = getSocketTimeout(); + private static final Integer SOCKET_TIMEOUT = getSocketTimeout(); - private static final Integer connectionTimeout = getConnectionTimeout(); + private static final Integer CON_TIMEOUT = getConnectionTimeout(); - private static final String trustSelfSignedCertString = UtilProperties.getPropertyValue(solrConfigName, "solr.client.trust.selfsigned.cert", "false"); + private static final String TRUST_SELF_SIGN_CERT_STRING = UtilProperties.getPropertyValue(SOLR_CONFIG_NAME, + "solr.client.trust.selfsigned.cert", "false"); - private static final boolean trustSelfSignedCert = getTrustSelfSignedCert(); + private static final boolean TRUST_SELF_SIGNED_CERT = getTrustSelfSignedCert(); public static String makeSolrWebappUrl() { - final String solrWebappProtocol = UtilProperties.getPropertyValue(solrConfigName, "solr.webapp.protocol"); - final String solrWebappDomainName = UtilProperties.getPropertyValue(solrConfigName, "solr.webapp.domainName"); - final String solrWebappPath = UtilProperties.getPropertyValue(solrConfigName, "solr.webapp.path"); - final String solrWebappPortOverride = UtilProperties.getPropertyValue(solrConfigName, "solr.webapp.portOverride"); + final String solrWebappProtocol = UtilProperties.getPropertyValue(SOLR_CONFIG_NAME, "solr.webapp.protocol"); + final String solrWebappDomainName = UtilProperties.getPropertyValue(SOLR_CONFIG_NAME, "solr.webapp.domainName"); + final String solrWebappPath = UtilProperties.getPropertyValue(SOLR_CONFIG_NAME, "solr.webapp.path"); + final String solrWebappPortOverride = UtilProperties.getPropertyValue(SOLR_CONFIG_NAME, "solr.webapp.portOverride"); String solrPort; if (UtilValidate.isNotEmpty(solrWebappPortOverride)) { solrPort = solrWebappPortOverride; } else { - solrPort = UtilProperties.getPropertyValue("url", ("https".equals(solrWebappProtocol) ? "port.https" : "port.http"), ("https".equals(solrWebappProtocol) ? "8443" : "8080")); + solrPort = UtilProperties.getPropertyValue("url", ("https".equals(solrWebappProtocol) + ? "port.https" : "port.http"), ("https".equals(solrWebappProtocol) ? "8443" : "8080")); } return solrWebappProtocol + "://" + solrWebappDomainName + ":" + solrPort + solrWebappPath; } private static Integer getSocketTimeout() { - if (UtilValidate.isNotEmpty(socketTimeoutString)) { + if (UtilValidate.isNotEmpty(SOCKET_TIMEOUT_STRING)) { try { - return Integer.parseInt(socketTimeoutString); + return Integer.parseInt(SOCKET_TIMEOUT_STRING); } catch (Exception e) { return null; } @@ -103,9 +106,9 @@ public final class SolrUtil { } private static Integer getConnectionTimeout() { - if (UtilValidate.isNotEmpty(connectionTimeoutString)) { + if (UtilValidate.isNotEmpty(CON_TIMEOUT_STRING)) { try { - return Integer.parseInt(connectionTimeoutString); + return Integer.parseInt(CON_TIMEOUT_STRING); } catch (Exception e) { return null; } @@ -114,7 +117,7 @@ public final class SolrUtil { } private static boolean getTrustSelfSignedCert() { - return "true".equals(trustSelfSignedCertString); + return "true".equals(TRUST_SELF_SIGN_CERT_STRING); } public static boolean isSolrEcaEnabled() { @@ -123,13 +126,12 @@ public final class SolrUtil { if (UtilValidate.isNotEmpty(sysProp)) { if ("true".equalsIgnoreCase(sysProp)) { ecaEnabled = Boolean.TRUE; - } - else if ("false".equalsIgnoreCase(sysProp)) { + } else if ("false".equalsIgnoreCase(sysProp)) { ecaEnabled = Boolean.FALSE; } } if (ecaEnabled == null) { - ecaEnabled = UtilProperties.getPropertyAsBoolean(SolrUtil.solrConfigName, "solr.eca.enabled", false); + ecaEnabled = UtilProperties.getPropertyAsBoolean(SolrUtil.SOLR_CONFIG_NAME, "solr.eca.enabled", false); } return Boolean.TRUE.equals(ecaEnabled); } @@ -150,16 +152,16 @@ public final class SolrUtil { return solrApp; } public static boolean isEcaTreatConnectErrorNonFatal() { - Boolean treatConnectErrorNonFatal = UtilProperties.getPropertyAsBoolean(solrConfigName, "solr.eca.treatConnectErrorNonFatal", true); + Boolean treatConnectErrorNonFatal = UtilProperties.getPropertyAsBoolean(SOLR_CONFIG_NAME, "solr.eca.treatConnectErrorNonFatal", true); return Boolean.TRUE.equals(treatConnectErrorNonFatal); } public static SolrInputDocument generateSolrDocument(Map<String, Object> context) throws GenericEntityException { SolrInputDocument doc1 = new SolrInputDocument(); // add defined attributes - for (int i = 0; i < solrProdAttribute.length; i++) { - if (context.get(solrProdAttribute[i]) != null) { - doc1.addField(solrProdAttribute[i], context.get(solrProdAttribute[i]).toString()); + for (int i = 0; i < SOLR_PRODUCT_ATTRIBUTE.length; i++) { + if (context.get(SOLR_PRODUCT_ATTRIBUTE[i]) != null) { + doc1.addField(SOLR_PRODUCT_ATTRIBUTE[i], context.get(SOLR_PRODUCT_ATTRIBUTE[i]).toString()); } } @@ -227,11 +229,13 @@ public final class SolrUtil { return doc1; } - public static Map<String, Object> categoriesAvailable(String catalogId, String categoryId, String productId, boolean displayproducts, int viewIndex, int viewSize, String solrIndexName) { + public static Map<String, Object> categoriesAvailable(String catalogId, String categoryId, String productId, + boolean displayproducts, int viewIndex, int viewSize, String solrIndexName) { return categoriesAvailable(catalogId, categoryId, productId, null, displayproducts, viewIndex, viewSize, solrIndexName); } - public static Map<String, Object> categoriesAvailable(String catalogId, String categoryId, String productId, String facetPrefix, boolean displayproducts, int viewIndex, int viewSize, String solrIndexName) { + public static Map<String, Object> categoriesAvailable(String catalogId, String categoryId, String productId, String facetPrefix, + boolean displayproducts, int viewIndex, int viewSize, String solrIndexName) { // create the data model Map<String, Object> result = new HashMap<>(); HttpSolrClient client = null; @@ -294,27 +298,27 @@ public final class SolrUtil { HttpClientContext httpContext = HttpClientContext.create(); CloseableHttpClient httpClient = null; - if (trustSelfSignedCert) { + if (TRUST_SELF_SIGNED_CERT) { httpClient = UtilHttp.getAllowAllHttpClient(); } else { httpClient = HttpClients.createDefault(); } RequestConfig requestConfig = null; - if (UtilValidate.isNotEmpty(socketTimeout) && UtilValidate.isNotEmpty(connectionTimeout)) { + if (UtilValidate.isNotEmpty(SOCKET_TIMEOUT) && UtilValidate.isNotEmpty(CON_TIMEOUT)) { requestConfig = RequestConfig.custom() - .setSocketTimeout(socketTimeout) - .setConnectTimeout(connectionTimeout) + .setSocketTimeout(SOCKET_TIMEOUT) + .setConnectTimeout(CON_TIMEOUT) .setRedirectsEnabled(true) .build(); - } else if (UtilValidate.isNotEmpty(socketTimeout)) { + } else if (UtilValidate.isNotEmpty(SOCKET_TIMEOUT)) { requestConfig = RequestConfig.custom() - .setSocketTimeout(socketTimeout) + .setSocketTimeout(SOCKET_TIMEOUT) .setRedirectsEnabled(true) .build(); - } else if (UtilValidate.isNotEmpty(connectionTimeout)) { + } else if (UtilValidate.isNotEmpty(CON_TIMEOUT)) { requestConfig = RequestConfig.custom() - .setConnectTimeout(connectionTimeout) + .setConnectTimeout(CON_TIMEOUT) .setRedirectsEnabled(true) .build(); } else { @@ -323,10 +327,10 @@ public final class SolrUtil { .build(); } - HttpGet httpLogin = new HttpGet(solrUrl + "/control/login?USERNAME=" + clientUsername + "&PASSWORD=" + clientPassword); + HttpGet httpLogin = new HttpGet(SOLR_URL + "/control/login?USERNAME=" + CLIENT_USER_NAME + "&PASSWORD=" + CLIENT_PASSWORD); httpLogin.setConfig(requestConfig); CloseableHttpResponse loginResponse = httpClient.execute(httpLogin, httpContext); loginResponse.close(); - return new HttpSolrClient.Builder(solrUrl + "/" + solrIndexName).withHttpClient(httpClient).build(); + return new HttpSolrClient.Builder(SOLR_URL + "/" + solrIndexName).withHttpClient(httpClient).build(); } } diff --git a/solr/src/main/java/org/apache/ofbiz/solr/test/SolrTests.java b/solr/src/main/java/org/apache/ofbiz/solr/test/SolrTests.java index 854dd2b..8b626c4 100644 --- a/solr/src/main/java/org/apache/ofbiz/solr/test/SolrTests.java +++ b/solr/src/main/java/org/apache/ofbiz/solr/test/SolrTests.java @@ -35,7 +35,7 @@ public class SolrTests extends OFBizTestCase { private Map<String, Object> context; private Map<String, Object> response; private String validTestProductId = "GZ-1006"; - private String validTestProductId_2 = "GZ-1005"; + private String validTestProductId2 = "GZ-1005"; private String invalidTestProductId = validTestProductId + validTestProductId; public SolrTests(String name) { @@ -46,6 +46,10 @@ public class SolrTests extends OFBizTestCase { protected void tearDown() throws Exception { } + /** + * Test add product to index. + * @throws Exception the exception + */ public void testAddProductToIndex() throws Exception { GenericValue product = EntityQuery.use(delegator).from("Product").where("productId", validTestProductId).queryOne(); @@ -53,7 +57,7 @@ public class SolrTests extends OFBizTestCase { Map<String, Object> ctx = new HashMap<>(); ctx.put("instance", product); - Map<String, Object> resp = dispatcher.runSync("addToSolr", ctx); + Map<String, Object> resp = getDispatcher().runSync("addToSolr", ctx); if (ServiceUtil.isError(resp)) { String errorMessage = ServiceUtil.getErrorMessage(resp); throw new Exception(errorMessage); @@ -63,7 +67,7 @@ public class SolrTests extends OFBizTestCase { Map<String, Object> sctx = new HashMap<>(); sctx.put("productCategoryId", "102"); - Map<String, Object> sresp = dispatcher.runSync("solrProductsSearch", sctx); + Map<String, Object> sresp = getDispatcher().runSync("solrProductsSearch", sctx); if (ServiceUtil.isError(sresp)) { String errorMessage = ServiceUtil.getErrorMessage(sresp); throw new Exception(errorMessage); @@ -73,10 +77,14 @@ public class SolrTests extends OFBizTestCase { } + /** + * Test add to solr index. + * @throws Exception the exception + */ public void testAddToSolrIndex() throws Exception { context = new HashMap<>(); context.put("productId", validTestProductId); - response = dispatcher.runSync("addToSolrIndex", context); + response = getDispatcher().runSync("addToSolrIndex", context); if (ServiceUtil.isError(response)) { String errorMessage = ServiceUtil.getErrorMessage(response); throw new Exception(errorMessage); @@ -85,10 +93,14 @@ public class SolrTests extends OFBizTestCase { response)); } - public void testAddToSolrIndex_invalidProduct() throws Exception { + /** + * Test add to solr index invalid product. + * @throws Exception the exception + */ + public void testAddToSolrIndexInvalidProduct() throws Exception { context = new HashMap<>(); context.put("productId", invalidTestProductId); - response = dispatcher.runSync("addToSolrIndex", context); + response = getDispatcher().runSync("addToSolrIndex", context); if (ServiceUtil.isError(response)) { String errorMessage = ServiceUtil.getErrorMessage(response); throw new Exception(errorMessage); @@ -97,22 +109,26 @@ public class SolrTests extends OFBizTestCase { response)); } + /** + * Test add list to solr index. + * @throws Exception the exception + */ public void testAddListToSolrIndex() throws Exception { List<Map<String, Object>> products = new ArrayList<>(); - Map<String, Object> product_1 = new HashMap<>(); - Map<String, Object> product_2 = new HashMap<>(); + Map<String, Object> product1 = new HashMap<>(); + Map<String, Object> product2 = new HashMap<>(); GenericValue validTestProduct = EntityQuery.use(delegator).from("Product").where("productId", validTestProductId).queryOne(); - GenericValue validTestProduct_2 = EntityQuery.use(delegator).from("Product").where("productId", validTestProductId_2).queryOne(); + GenericValue validTestProduct2 = EntityQuery.use(delegator).from("Product").where("productId", validTestProductId2).queryOne(); - product_1.put("productId", validTestProduct); - product_2.put("productId", validTestProduct_2); + product1.put("productId", validTestProduct); + product2.put("productId", validTestProduct2); - products.add(product_1); - products.add(product_2); + products.add(product1); + products.add(product2); context = new HashMap<>(); context.put("fieldList", products); - response = dispatcher.runSync("addListToSolrIndex", context); + response = getDispatcher().runSync("addListToSolrIndex", context); if (ServiceUtil.isError(response)) { String errorMessage = ServiceUtil.getErrorMessage(response); throw new Exception(errorMessage); @@ -121,25 +137,29 @@ public class SolrTests extends OFBizTestCase { } - public void testAddListToSolrIndex_invalidProducts() throws Exception { + /** + * Test add list to solr index invalid products. + * @throws Exception the exception + */ + public void testAddListToSolrIndexInvalidProducts() throws Exception { List<Map<String, Object>> products = new ArrayList<>(); - Map<String, Object> product_1 = new HashMap<>(); - Map<String, Object> product_2 = new HashMap<>(); + Map<String, Object> product1 = new HashMap<>(); + Map<String, Object> product2 = new HashMap<>(); GenericValue testProduct = EntityQuery.use(delegator).from("Product").where("productId", validTestProductId).queryOne(); - GenericValue testProduct_2 = EntityQuery.use(delegator).from("Product").where("productId", validTestProductId_2).queryOne(); + GenericValue testProduct2 = EntityQuery.use(delegator).from("Product").where("productId", validTestProductId2).queryOne(); testProduct.replace("productId", invalidTestProductId); testProduct.replace("productId", invalidTestProductId); - product_1.put("productId", testProduct); - product_2.put("productId", testProduct_2); + product1.put("productId", testProduct); + product2.put("productId", testProduct2); - products.add(product_1); - products.add(product_2); + products.add(product1); + products.add(product2); context = new HashMap<>(); context.put("fieldList", products); - response = dispatcher.runSync("addListToSolrIndex", context); + response = getDispatcher().runSync("addListToSolrIndex", context); if (ServiceUtil.isError(response)) { String errorMessage = ServiceUtil.getErrorMessage(response); throw new Exception(errorMessage); |
Free forum by Nabble | Edit this page |