Refactoring code

git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/accounting/accounting-service@160513 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Luca Frosini 2017-12-14 16:03:22 +00:00
parent 1318b67846
commit 84ce8c1853
9 changed files with 117 additions and 264 deletions

86
pom.xml
View File

@ -6,6 +6,7 @@
<artifactId>maven-parent</artifactId>
<version>1.0.0</version>
</parent>
<groupId>org.gcube.accounting</groupId>
<artifactId>accounting-service</artifactId>
<version>1.2.0-SNAPSHOT</version>
@ -46,93 +47,107 @@
</dependencyManagement>
<dependencies>
<!-- smartgears -->
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-smartgears</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-smartgears-app</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>authorization-client</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>common-authorization</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.0.13</version>
<groupId>org.gcube.accounting</groupId>
<artifactId>accounting-lib</artifactId>
<scope>provided</scope>
</dependency>
<!-- use for service query -->
<!-- Used for service query -->
<dependency>
<groupId>org.gcube.accounting</groupId>
<artifactId>accounting-analytics</artifactId>
<version>[2.0.0-SNAPSHOT,3.0.0-SNAPSHOT)</version>
</dependency>
<dependency>
<groupId>org.gcube.accounting</groupId>
<artifactId>accounting-analytics-persistence-couchbase</artifactId>
<version>[1.0.0-SNAPSHOT,2.0.0-SNAPSHOT)</version>
</dependency>
<!-- end use for service query -->
<!-- jersey -->
<!-- END Used for service query -->
<!-- Jersey -->
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.13</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!-- END Jersey -->
<!-- Test Dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.0.13</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptors>
<descriptor>${distroDirectory}/descriptor.xml</descriptor>
</descriptors>
</configuration>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>servicearchive</id>
<phase>install</phase>
<id>copy-profile</id>
<goals>
<goal>single</goal>
<goal>copy-resources</goal>
</goals>
<phase>process-resources</phase>
<configuration>
<outputDirectory>${webappDirectory}</outputDirectory>
<resources>
<resource>
<directory>${distroDirectory}</directory>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<id>make-servicearchive</id>
<phase>package</phase>
</execution>
</executions>
</plugin>
@ -142,10 +157,11 @@
<configuration>
<warName>${artifactId}</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
<!-- webXml>src\main\webapp\WEB-INF\web.xml</webXml -->
</configuration>
<executions>
<execution>
<id>war</id>
<id>servicearchive</id>
<phase>install</phase>
<goals>
<goal>war</goal>

View File

@ -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());
}
}

View File

@ -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;
@ -17,23 +15,18 @@ 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;
}
}

View File

@ -10,7 +10,7 @@ import javax.ws.rs.ext.Provider;
* @author Luca Frosini (ISTI - CNR)
*/
@Provider
public class AccountingServiceExceptionMapper implements ExceptionMapper<Exception>{
public class AccountingServiceExceptionMapper implements ExceptionMapper<Exception> {
@Override
public Response toResponse(Exception exception) {

View File

@ -10,15 +10,19 @@ 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 {
@ -30,17 +34,15 @@ public class ResourceInsert {
@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);
log.debug("Going to account : {}", json);
AccountingServiceInitializer appManager = (AccountingServiceInitializer) ApplicationManagerProvider
.get(AccountingServiceInitializer.class);
AccountingPersistence accountingPersistence = appManager.getAccountingPersistence();
AccountingPersistence accountingPersistence = AccountingPersistenceFactory.getPersistence();
List<Record> records = DSMapper.unmarshalList(json);
for (Record record : records) {
for(Record record : records) {
accountingPersistence.account(record);
}
return Response.status(Status.CREATED).build();

View File

@ -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();

View File

@ -7,16 +7,21 @@ 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 {
@ -44,20 +49,17 @@ public class ServiceState {
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);
}

View File

@ -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));
}
}

View File

@ -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();
}
*/
}
}