From 84ce8c185385b4fbabc98878766b8eea69577ac2 Mon Sep 17 00:00:00 2001 From: Luca Frosini Date: Thu, 14 Dec 2017 16:03:22 +0000 Subject: [PATCH] Refactoring code git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/accounting/accounting-service@160513 82a268e6-3cf1-43bd-a215-b396298e98cf --- pom.xml | 88 +++++++++++-------- .../service/AccountingResource.java | 8 +- .../service/AccountingServiceInitializer.java | 73 +++++---------- .../AccountingServiceExceptionMapper.java | 4 +- .../service/resources/ResourceInsert.java | 30 ++++--- .../service/resources/ResourceQuery.java | 11 +-- .../service/resources/ServiceState.java | 32 +++---- .../accounting/service/utils/UtilRecord.java | 81 ----------------- .../accounting/service/JerseyClient.java | 54 ------------ 9 files changed, 117 insertions(+), 264 deletions(-) delete mode 100644 src/main/java/org/gcube/data/publishing/accounting/service/utils/UtilRecord.java delete mode 100644 src/test/java/org/gucbe/data/publishing/accounting/service/JerseyClient.java diff --git a/pom.xml b/pom.xml index 373afef..6cfb839 100644 --- a/pom.xml +++ b/pom.xml @@ -6,6 +6,7 @@ maven-parent 1.0.0 + org.gcube.accounting accounting-service 1.2.0-SNAPSHOT @@ -19,7 +20,7 @@ ${project.basedir}/distro DataPublishing - + scm:https://svn.d4science.research-infrastructures.eu/gcube/trunk/accounting/${project.artifactId} scm:https://svn.d4science.research-infrastructures.eu/gcube/trunk/accounting/${project.artifactId} @@ -46,93 +47,107 @@ - - - - org.gcube.core - common-smartgears - - org.gcube.core common-smartgears-app + provided - org.gcube.common authorization-client + provided - org.gcube.common common-authorization + provided - - org.slf4j slf4j-api + provided - - ch.qos.logback - logback-classic - 1.0.13 + org.gcube.accounting + accounting-lib + provided - - + org.gcube.accounting accounting-analytics [2.0.0-SNAPSHOT,3.0.0-SNAPSHOT) - org.gcube.accounting accounting-analytics-persistence-couchbase [1.0.0-SNAPSHOT,2.0.0-SNAPSHOT) - - - - + + javax.ws.rs javax.ws.rs-api 2.0.1 - org.glassfish.jersey.containers jersey-container-servlet 2.13 - javax.servlet javax.servlet-api 3.0.1 provided - + + + + junit + junit + 4.11 + test + + + ch.qos.logback + logback-classic + 1.0.13 + test + + org.apache.maven.plugins - maven-assembly-plugin - - - ${distroDirectory}/descriptor.xml - - + maven-resources-plugin - servicearchive - install + copy-profile - single + copy-resources + process-resources + + ${webappDirectory} + + + ${distroDirectory} + true + + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + make-servicearchive + package @@ -142,10 +157,11 @@ ${artifactId} false + - war + servicearchive install war diff --git a/src/main/java/org/gcube/data/publishing/accounting/service/AccountingResource.java b/src/main/java/org/gcube/data/publishing/accounting/service/AccountingResource.java index b2bbccd..b6f902f 100644 --- a/src/main/java/org/gcube/data/publishing/accounting/service/AccountingResource.java +++ b/src/main/java/org/gcube/data/publishing/accounting/service/AccountingResource.java @@ -5,18 +5,18 @@ import javax.ws.rs.core.MediaType; import org.gcube.data.publishing.accounting.service.resources.ResourceInsert; import org.glassfish.jersey.server.ResourceConfig; + /** * @author Alessandro Pieve (alessandro.pieve@isti.cnr.it) * @author Luca Frosini (ISTI - CNR) */ @ApplicationPath("/") -public class AccountingResource extends ResourceConfig{ +public class AccountingResource extends ResourceConfig { public static final String APPLICATION_JSON_CHARSET_UTF_8 = MediaType.APPLICATION_JSON + ";charset=UTF-8"; - public AccountingResource(){ + public AccountingResource() { packages(ResourceInsert.class.getPackage().toString()); } - + } - diff --git a/src/main/java/org/gcube/data/publishing/accounting/service/AccountingServiceInitializer.java b/src/main/java/org/gcube/data/publishing/accounting/service/AccountingServiceInitializer.java index 5a2e9e1..e0c19f4 100644 --- a/src/main/java/org/gcube/data/publishing/accounting/service/AccountingServiceInitializer.java +++ b/src/main/java/org/gcube/data/publishing/accounting/service/AccountingServiceInitializer.java @@ -1,8 +1,6 @@ package org.gcube.data.publishing.accounting.service; -import org.gcube.accounting.analytics.persistence.AccountingPersistenceQuery; import org.gcube.accounting.analytics.persistence.AccountingPersistenceQueryFactory; -import org.gcube.accounting.persistence.AccountingPersistence; import org.gcube.accounting.persistence.AccountingPersistenceFactory; import org.gcube.common.authorization.client.Constants; import org.gcube.common.authorization.client.exceptions.ObjectNotFound; @@ -14,26 +12,21 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AccountingServiceInitializer implements ApplicationManager { - + private static Logger logger = LoggerFactory.getLogger(AccountingServiceInitializer.class); - - // Used for Record insert - protected AccountingPersistence accountingPersistence = null; - // Used for Query - protected AccountingPersistenceQuery accountingPersistenceQuery; - - public static String getCurrentContext(){ + + public static String getCurrentContext() { String token = SecurityTokenProvider.instance.get(); AuthorizationEntry authorizationEntry; try { authorizationEntry = Constants.authorizationService().get(token); - } catch (Exception e) { + } catch(Exception e) { return ScopeProvider.instance.get(); } return authorizationEntry.getContext(); } - public static String getCurrentContext(String token) throws ObjectNotFound, Exception{ + public static String getCurrentContext(String token) throws ObjectNotFound, Exception { AuthorizationEntry authorizationEntry = Constants.authorizationService().get(token); String context = authorizationEntry.getContext(); logger.info("Context of token {} is {}", token, context); @@ -44,63 +37,37 @@ public class AccountingServiceInitializer implements ApplicationManager { public void onInit() { String context = getCurrentContext(); - logger.debug( - "\n-------------------------------------------------------\n" + logger.debug("\n-------------------------------------------------------\n" + "Accounting Service is Starting on context {}\n" - + "-------------------------------------------------------", - context); + + "-------------------------------------------------------", context); // Initializing the persistence connector used for insert - accountingPersistence = AccountingPersistenceFactory.getPersistence(); - accountingPersistenceQuery = AccountingPersistenceQueryFactory.getInstance(); - - - + AccountingPersistenceFactory.getPersistence(); + // Initializing the persistence connector used for query + AccountingPersistenceQueryFactory.getInstance(); } - + public void onShutdown() { String context = getCurrentContext(); - logger.trace( - "\n-------------------------------------------------------\n" + logger.trace("\n-------------------------------------------------------\n" + "Accounting Service is Stopping on context {}\n" - + "-------------------------------------------------------", - context); + + "-------------------------------------------------------", context); try { // Closing the persistence connector used for insert - accountingPersistence.flush(); - accountingPersistence.close(); - + AccountingPersistenceFactory.getPersistence().close(); + // Closing the persistence connector used for query - accountingPersistenceQuery.close(); - + AccountingPersistenceQueryFactory.getInstance().close(); - logger.trace( - "\n-------------------------------------------------------\n" + logger.trace("\n-------------------------------------------------------\n" + "Accounting Service Stopped Successfully on context {}\n" - + "-------------------------------------------------------", - context); + + "-------------------------------------------------------", context); - } catch (Exception e) { + } catch(Exception e) { logger.error("Error while stopping Accounting Service on context {}", context, e); } } - - /** - * - * @return persistence for document store lib - */ - public AccountingPersistence getAccountingPersistence() { - return accountingPersistence; - } - - /** - * - * @return persistence for accounting analytics - */ - public AccountingPersistenceQuery getAccountingPersistenceQuery() { - return accountingPersistenceQuery; - } - + } diff --git a/src/main/java/org/gcube/data/publishing/accounting/service/resources/AccountingServiceExceptionMapper.java b/src/main/java/org/gcube/data/publishing/accounting/service/resources/AccountingServiceExceptionMapper.java index e82328a..542632e 100644 --- a/src/main/java/org/gcube/data/publishing/accounting/service/resources/AccountingServiceExceptionMapper.java +++ b/src/main/java/org/gcube/data/publishing/accounting/service/resources/AccountingServiceExceptionMapper.java @@ -10,8 +10,8 @@ import javax.ws.rs.ext.Provider; * @author Luca Frosini (ISTI - CNR) */ @Provider -public class AccountingServiceExceptionMapper implements ExceptionMapper{ - +public class AccountingServiceExceptionMapper implements ExceptionMapper { + @Override public Response toResponse(Exception exception) { Status status = Status.INTERNAL_SERVER_ERROR; diff --git a/src/main/java/org/gcube/data/publishing/accounting/service/resources/ResourceInsert.java b/src/main/java/org/gcube/data/publishing/accounting/service/resources/ResourceInsert.java index 1293a9f..8679c06 100644 --- a/src/main/java/org/gcube/data/publishing/accounting/service/resources/ResourceInsert.java +++ b/src/main/java/org/gcube/data/publishing/accounting/service/resources/ResourceInsert.java @@ -10,40 +10,42 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.gcube.accounting.persistence.AccountingPersistence; +import org.gcube.accounting.persistence.AccountingPersistenceFactory; import org.gcube.data.publishing.accounting.service.AccountingResource; import org.gcube.data.publishing.accounting.service.AccountingServiceInitializer; import org.gcube.documentstore.records.DSMapper; import org.gcube.documentstore.records.Record; -import org.gcube.smartgears.ApplicationManagerProvider; import org.gcube.smartgears.annotations.ManagedBy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +/** + * @author Alessandro Pieve (alessandro.pieve@isti.cnr.it) + * @author Luca Frosini (ISTI - CNR) + */ @ManagedBy(AccountingServiceInitializer.class) @Path(ResourceInsert.INSERT_PATH_PART) public class ResourceInsert { - + private static final Logger log = LoggerFactory.getLogger(ResourceInsert.class); - + public static final String INSERT_PATH_PART = "insert"; public static final String RECORD_PATH_PART = "record"; - + @POST @Path(RECORD_PATH_PART) - @Consumes({ MediaType.TEXT_PLAIN, AccountingResource.APPLICATION_JSON_CHARSET_UTF_8 }) + @Consumes({MediaType.TEXT_PLAIN, AccountingResource.APPLICATION_JSON_CHARSET_UTF_8}) public Response add(String json) throws Exception { - - log.debug("Goign to account : {}", json); - - AccountingServiceInitializer appManager = (AccountingServiceInitializer) ApplicationManagerProvider - .get(AccountingServiceInitializer.class); - AccountingPersistence accountingPersistence = appManager.getAccountingPersistence(); - + + log.debug("Going to account : {}", json); + + AccountingPersistence accountingPersistence = AccountingPersistenceFactory.getPersistence(); + List records = DSMapper.unmarshalList(json); - for (Record record : records) { + for(Record record : records) { accountingPersistence.account(record); } return Response.status(Status.CREATED).build(); } - + } diff --git a/src/main/java/org/gcube/data/publishing/accounting/service/resources/ResourceQuery.java b/src/main/java/org/gcube/data/publishing/accounting/service/resources/ResourceQuery.java index 455285c..f3493a4 100644 --- a/src/main/java/org/gcube/data/publishing/accounting/service/resources/ResourceQuery.java +++ b/src/main/java/org/gcube/data/publishing/accounting/service/resources/ResourceQuery.java @@ -8,13 +8,17 @@ import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import org.gcube.accounting.analytics.persistence.AccountingPersistenceQuery; +import org.gcube.accounting.analytics.persistence.AccountingPersistenceQueryFactory; import org.gcube.data.publishing.accounting.service.AccountingResource; import org.gcube.data.publishing.accounting.service.AccountingServiceInitializer; -import org.gcube.smartgears.ApplicationManagerProvider; import org.gcube.smartgears.annotations.ManagedBy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +/** + * @author Alessandro Pieve (alessandro.pieve@isti.cnr.it) + * @author Luca Frosini (ISTI - CNR) + */ @ManagedBy(AccountingServiceInitializer.class) @Path(ResourceQuery.QUERY_PATH_PART) public class ResourceQuery { @@ -34,10 +38,7 @@ public class ResourceQuery { @NotNull @PathParam(RECORD_ID_PATH_PART) String recordId) throws Exception { log.debug("Requested {} having ID {}", type, recordId); - - AccountingServiceInitializer appManager = (AccountingServiceInitializer) ApplicationManagerProvider - .get(AccountingServiceInitializer.class); - AccountingPersistenceQuery accountingPersistenceQuery = appManager.getAccountingPersistenceQuery(); + AccountingPersistenceQuery accountingPersistenceQuery = AccountingPersistenceQueryFactory.getInstance(); String record = accountingPersistenceQuery.getRecord(recordId, type); return Response.status(200).entity(record).type(AccountingResource.APPLICATION_JSON_CHARSET_UTF_8).build(); diff --git a/src/main/java/org/gcube/data/publishing/accounting/service/resources/ServiceState.java b/src/main/java/org/gcube/data/publishing/accounting/service/resources/ServiceState.java index 723921f..1582f3d 100644 --- a/src/main/java/org/gcube/data/publishing/accounting/service/resources/ServiceState.java +++ b/src/main/java/org/gcube/data/publishing/accounting/service/resources/ServiceState.java @@ -7,24 +7,29 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.gcube.accounting.analytics.persistence.AccountingPersistenceQuery; +import org.gcube.accounting.analytics.persistence.AccountingPersistenceQueryFactory; import org.gcube.accounting.persistence.AccountingPersistence; +import org.gcube.accounting.persistence.AccountingPersistenceFactory; import org.gcube.data.publishing.accounting.service.AccountingResource; import org.gcube.data.publishing.accounting.service.AccountingServiceInitializer; -import org.gcube.smartgears.ApplicationManagerProvider; import org.gcube.smartgears.annotations.ManagedBy; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +/** + * @author Alessandro Pieve (alessandro.pieve@isti.cnr.it) + * @author Luca Frosini (ISTI - CNR) + */ @ManagedBy(AccountingServiceInitializer.class) @Path(ServiceState.STATE_PATH_PART) public class ServiceState { - + private static final Logger logger = LoggerFactory.getLogger(ServiceState.class); - + public static final String STATE_PATH_PART = "state"; - + public static final String SERVICE = "service"; public static final String RUNNING = "running"; public static final String CONTEXT = "context"; @@ -37,32 +42,29 @@ public class ServiceState { public Response getState() throws JSONException { String context = AccountingServiceInitializer.getCurrentContext(); logger.debug("Getting Service Status fro context {}", context); - + JSONObject jsonObject = new JSONObject(); jsonObject.append(SERVICE, RUNNING); jsonObject.append(CONTEXT, context); Status responseStatus = Status.SERVICE_UNAVAILABLE; - - AccountingServiceInitializer appManager = (AccountingServiceInitializer) ApplicationManagerProvider - .get(AccountingServiceInitializer.class); - - AccountingPersistence accountingPersistence = appManager.getAccountingPersistence(); + + AccountingPersistence accountingPersistence = AccountingPersistenceFactory.getPersistence(); try { jsonObject.append(INSERT_CONNECTION_UP, accountingPersistence.isConnectionActive()); - }catch (Exception e) { + } catch(Exception e) { jsonObject.append(INSERT_CONNECTION_UP, false); } - AccountingPersistenceQuery accountingPersistenceQuery = appManager.getAccountingPersistenceQuery(); + AccountingPersistenceQuery accountingPersistenceQuery = AccountingPersistenceQueryFactory.getInstance(); try { jsonObject.append(QUERY_CONNECTION_UP, accountingPersistenceQuery.isConnectionActive()); - }catch (Exception e) { + } catch(Exception e) { jsonObject.append(QUERY_CONNECTION_UP, false); } return Response.status(responseStatus).entity(jsonObject.toString()).build(); - + } - + } diff --git a/src/main/java/org/gcube/data/publishing/accounting/service/utils/UtilRecord.java b/src/main/java/org/gcube/data/publishing/accounting/service/utils/UtilRecord.java deleted file mode 100644 index fa7f57a..0000000 --- a/src/main/java/org/gcube/data/publishing/accounting/service/utils/UtilRecord.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.gcube.data.publishing.accounting.service.utils; - -import java.util.UUID; - -import org.gcube.accounting.datamodel.UsageRecord.OperationResult; -import org.gcube.accounting.datamodel.usagerecords.ServiceUsageRecord; -import org.gcube.documentstore.exception.InvalidValueException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class UtilRecord { - - private static Logger logger = LoggerFactory.getLogger(UtilRecord.class); - - public final static String TEST_CONSUMER_ID = "name.surname"; - public final static String TEST_SCOPE = "/infrastructure/vo"; - public final static String TEST_SCOPE_2 = "/infrastructure/vo/vre"; - public final static OperationResult TEST_OPERATION_RESULT = OperationResult.SUCCESS; - - public final static String TEST_SERVICE_CLASS = "TestServiceClass"; - public final static String TEST_SERVICE_NAME = "TestServiceName"; - public final static String TEST_CALLED_METHOD = "TestCalledMethod"; - public final static String TEST_CALLER_QUALIFIER = "TestCallerQualifier"; - - public final static String TEST_CALLER_HOST = "remotehost"; - public final static String TEST_HOST = "localhost"; - - public final static String TEST_PROPERTY_NAME = "TestPropertyName"; - public final static String TEST_PROPERTY_VALUE = "TestPropertyValue"; - - public final static String TEST_JOB_ID = UUID.randomUUID().toString(); - public final static String TEST_JOB_NAME = "TestJobName"; - public final static int TEST_VMS_USED = 2; - public final static String TEST_JOB_QUALIFIER = "TestJobQualifier"; - public final static long HALF_DURATION = 10 * 60 * 1000; // 10 min - - public final static String TEST_TASK_ID = UUID.randomUUID().toString(); - public final static String TEST_NESTED_MAP = "TestNestedMap"; - - public final static String TEST_PORTLET_ID = "TestPortlet"; - public final static String TEST_PORTLET_OPERATION_ID = "TestPortletOperationID"; - public final static String TEST_PORTLET_MESSAGE = "TestPortletMessage"; - - private final static long MIN_DURATION = 60; // millisec - private final static long MAX_DURATION = 1000; // millisec - /** - * Create a valid #ServiceUsageRecord with scope set automatically. - * @return the created #ServiceUsageRecord - */ - public static ServiceUsageRecord createTestServiceUsageRecord() { - ServiceUsageRecord usageRecord = new ServiceUsageRecord(); - try { - usageRecord.setConsumerId(TEST_CONSUMER_ID); - usageRecord.setOperationResult(TEST_OPERATION_RESULT); - - usageRecord.setCallerHost(TEST_CALLER_HOST); - usageRecord.setHost(TEST_HOST); - usageRecord.setCallerQualifier(TEST_CALLER_QUALIFIER); - usageRecord.setServiceClass(TEST_SERVICE_CLASS); - usageRecord.setServiceName(TEST_SERVICE_NAME); - usageRecord.setCalledMethod(TEST_CALLED_METHOD); - - usageRecord.setDuration(generateRandomLong(MIN_DURATION, MAX_DURATION)); - - } catch (InvalidValueException e) { - logger.error(" ------ You SHOULD NOT SEE THIS MESSAGE. Error Creating a test Usage Record", e); - throw new RuntimeException(e); - } - return usageRecord; - - } - - /** - * Generate A Random long in a range between min and max. - * This function is internally used to set random duration. - * @return the generated random long - */ - public static long generateRandomLong(long min, long max){ - return min + (int)(Math.random() * ((max - min) + 1)); - } -} diff --git a/src/test/java/org/gucbe/data/publishing/accounting/service/JerseyClient.java b/src/test/java/org/gucbe/data/publishing/accounting/service/JerseyClient.java deleted file mode 100644 index f941d0a..0000000 --- a/src/test/java/org/gucbe/data/publishing/accounting/service/JerseyClient.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.gucbe.data.publishing.accounting.service; - -//import org.junit.Test; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; - -public class JerseyClient { - - //private static Logger log = LoggerFactory.getLogger(JerseyClient.class); - - - - - //@Test - public void Insert() { - /* - try { - - Student st = new Student("Adriana", "Barrer", 12, 9); - - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put( - JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - - WebResource webResource = client - .resource("http://localhost:8080/accounting-service/gcube/service/send?gcube-token=3acdde42-6883-4564-b3ba-69f6486f6fe0-98187548"); - - ClientResponse response = webResource.accept("application/json") - .type("application/json").post(ClientResponse.class, st); - - if (response.getStatus() != 200) { - throw new RuntimeException("Failed : HTTP error code : " - + response.getStatus()); - } - - String output = response.getEntity(String.class); - - System.out.println("Server response .... \n"); - System.out.println(output); - - } catch (Exception e) { - - e.printStackTrace(); - - } - -*/ - - } - -}