This commit is contained in:
Alessandro Pieve 2017-02-16 16:46:46 +00:00
parent d55e881660
commit 78e50b04fb
64 changed files with 4635 additions and 0 deletions

31
.classpath Normal file
View File

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

42
.project Normal file
View File

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>quota-manager</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
</natures>
</projectDescription>

13
.settings/.jsdtscope Normal file
View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src/main/webapp"/>
<classpathentry kind="src" path="target/m2e-wtp/web-resources"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.WebProject">
<attributes>
<attribute name="hide" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.baseBrowserLibrary"/>
<classpathentry kind="output" path=""/>
</classpath>

View File

@ -0,0 +1,5 @@
eclipse.preferences.version=1
encoding//src/main/java=UTF-8
encoding//src/main/resources=UTF-8
encoding//src/test/java=UTF-8
encoding/<project>=UTF-8

View File

@ -0,0 +1,8 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
org.eclipse.jdt.core.compiler.compliance=1.7
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.7

View File

@ -0,0 +1,3 @@
eclipse.preferences.version=1
org.eclipse.jpt.core.platform=eclipselink2_2
org.eclipse.jpt.jpa.core.discoverAnnotatedClasses=true

View File

@ -0,0 +1,4 @@
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="quota-service_basic">
<wb-resource deploy-path="/" source-path="/target/m2e-wtp/web-resources"/>
<wb-resource deploy-path="/" source-path="/src/main/webapp" tag="defaultRootSource"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
<dependent-module archiveName="quota-library-1.0.0-SNAPSHOT.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/quota-library/quota-library">
<dependency-type>uses</dependency-type>
</dependent-module>
<property name="java-output-path" value="/quota-service_basic/target/classes"/>
<property name="context-root" value="quota-manager"/>
</wb-module>
</project-modules>

View File

@ -0,0 +1,12 @@
<root>
<facet id="jst.jaxrs">
<node name="libprov">
<attribute name="provider-id" value="jaxrs-no-op-library-provider"/>
</node>
</facet>
<facet id="jpt.jpa">
<node name="libprov">
<attribute name="provider-id" value="jpa-no-op-library-provider"/>
</node>
</facet>
</root>

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<fixed facet="wst.jsdt.web"/>
<installed facet="jst.web" version="2.3"/>
<installed facet="wst.jsdt.web" version="1.0"/>
<installed facet="java" version="1.7"/>
<installed facet="jst.jaxrs" version="2.0"/>
<installed facet="jpt.jpa" version="2.0"/>
</faceted-project>

View File

@ -0,0 +1 @@
org.eclipse.wst.jsdt.launching.baseBrowserLibrary

View File

@ -0,0 +1 @@
Window

View File

@ -0,0 +1,2 @@
disabled=06target
eclipse.preferences.version=1

1
distro/LICENSE Normal file
View File

@ -0,0 +1 @@
${gcube.license}

62
distro/README Normal file
View File

@ -0,0 +1,62 @@
The gCube System - ${name}
--------------------------------------------------
${description}
${gcube.description}
${gcube.funding}
Version
--------------------------------------------------
${version} (${buildDate})
Please see the file named "changelog.xml" in this directory for the release notes.
Authors
--------------------------------------------------
* Alessandro Pieve(alessandro.pieve-AT-isti.cnr.it), CNR, Italy
Maintainers
--------------------------------------------------
* Alessandro Pieve(alessandro.pieve-AT-isti.cnr.it), CNR, Italy
Download information
--------------------------------------------------
Source code is available from SVN:
${scm.url}
Binaries can be downloaded from the gCube website:
${gcube.website}
Installation
--------------------------------------------------
Installation documentation is available on-line in the gCube Wiki:
${gcube.wikiRoot}
Documentation
--------------------------------------------------
Documentation is available on-line in the gCube Wiki:
${gcube.wikiRoot}
Support
--------------------------------------------------
Bugs and support requests can be reported in the gCube issue tracking tool:
${gcube.issueTracking}
Licensing
--------------------------------------------------
This software is licensed under the terms you may find in the file named "LICENSE" in this directory.

5
distro/changelog.xml Normal file
View File

@ -0,0 +1,5 @@
<ReleaseNotes>
<Changeset component="org.gcube.information-system.quota-manager.1-0-0" date="2015-04-28">
<Change>First Release</Change>
</Changeset>
</ReleaseNotes>

35
distro/descriptor.xml Normal file
View File

@ -0,0 +1,35 @@
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>servicearchive</id>
<formats>
<format>tar.gz</format>
</formats>
<baseDirectory>/</baseDirectory>
<fileSets>
<fileSet>
<directory>${distroDirectory}</directory>
<outputDirectory>/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
<includes>
<include>README</include>
<include>LICENSE</include>
<include>changelog.xml</include>
</includes>
<fileMode>755</fileMode>
<filtered>true</filtered>
</fileSet>
</fileSets>
<files>
<file>
<source>${distroDirectory}/profile.xml</source>
<outputDirectory>/</outputDirectory>
<filtered>true</filtered>
</file>
<file>
<source>target/${build.finalName}.war</source>
<outputDirectory>/${artifactId}</outputDirectory>
</file>
</files>
</assembly>

8
distro/gcube-app.xml Normal file
View File

@ -0,0 +1,8 @@
<application mode='online'>
<name>QuotaManager</name>
<group>InformationSystem</group>
<version>${version}</version>
<description>quota mananger webapp</description>
<local-persistence location='target' />
</application>

26
distro/profile.xml Normal file
View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<Resource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ID />
<Type>Service</Type>
<Profile>
<Description>${description}</Description>
<Class>InformationSystem</Class>
<Name>${artifactId}</Name>
<Version>1.0.0</Version>
<Packages>
<Software>
<Name>${artifactId}</Name>
<Version>${version}</Version>
<MavenCoordinates>
<groupId>${groupId}</groupId>
<artifactId>${artifactId}</artifactId>
<version>${version}</version>
</MavenCoordinates>
<Files>
<File>${build.finalName}.jar</File>
</Files>
</Software>
</Packages>
</Profile>
</Resource>

9
distro/web.xml Normal file
View File

@ -0,0 +1,9 @@
<web-app>
<servlet>
<servlet-name>org.gcube.resource.management.quota.manager.service.QuotaService</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>org.gcube.resource.management.quota.manager.service.QuotaService</servlet-name>
<url-pattern>/gcube/service/*</url-pattern>
</servlet-mapping>
</web-app>

301
pom.xml Normal file
View File

@ -0,0 +1,301 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>maven-parent</artifactId>
<groupId>org.gcube.tools</groupId>
<version>1.0.0</version>
</parent>
<groupId>org.gcube.resource.management</groupId>
<artifactId>quota-manager</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>quota-service</name>
<packaging>war</packaging>
<properties>
<webappDirectory>${project.basedir}/src/main/webapp/WEB-INF</webappDirectory>
<distroDirectory>${project.basedir}/distro</distroDirectory>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>maven-smartgears-bom</artifactId>
<version>LATEST</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-smartgears-app</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-smartgears</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.resource.management</groupId>
<artifactId>quota-library</artifactId>
<version>[1.0.0-SNAPSHOT, 2.0.0-SNAPSHOT)</version>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-encryption</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-scope-maps</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-scope</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-encryption</artifactId>
</dependency>
<!-- jersey -->
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.13</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers.glassfish</groupId>
<artifactId>jersey-gf-cdi</artifactId>
<version>2.13</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>javax.transaction-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
<scope>runtime</scope>
</dependency>
<!-- weld -->
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.1</version>
</dependency>
<!-- DELETE TEST -->
<dependency>
<groupId>org.jboss.weld.servlet</groupId>
<artifactId>weld-servlet</artifactId>
<version>2.2.4.Final</version>
</dependency>
<dependency>
<groupId>org.jboss</groupId>
<artifactId>jandex</artifactId>
<version>1.2.2.Final</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.14.8</version>
</dependency>
<dependency>
<artifactId>eclipselink</artifactId>
<groupId>org.eclipse.persistence</groupId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.0.13</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-simple</artifactId>
<version>2.17</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>10.8.2.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
<version>10.8.2.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.googlecode.jeeunit</groupId>
<artifactId>jeeunit</artifactId>
<version>1.0.0</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.gcube.accounting</groupId>
<artifactId>accounting-analytics</artifactId>
<version>[2.4.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>
<dependency>
<groupId>org.gcube.accounting</groupId>
<artifactId>accounting-lib</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>
<!-- H2 DB -->
<!--
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.187</version>
</dependency>
-->
<!-- use only for test -->
<dependency>
<groupId>org.gcube.resources.discovery</groupId>
<artifactId>discovery-client</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.resources</groupId>
<artifactId>common-gcore-resources</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.resources.discovery</groupId>
<artifactId>ic-client</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.4</version>
</dependency>
</dependencies>
<build>
<finalName>${artifactId}</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>copy-profile</id>
<goals>
<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-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warName>quota-manager</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptors>
<descriptor>${distroDirectory}/descriptor.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>servicearchive</id>
<phase>install</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,89 @@
package org.gcube.resource.management.quota.manager.check;
import java.util.Timer;
import org.gcube.accounting.analytics.persistence.AccountingPersistenceQuery;
import org.gcube.accounting.analytics.persistence.AccountingPersistenceQueryFactory;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.resource.management.quota.manager.persistence.QuotaDBPersistence;
import org.gcube.resource.management.quota.manager.util.Constants;
import org.gcube.resource.management.quota.manager.util.DiscoveryConfiguration;
import org.gcube.smartgears.ApplicationManager;
import org.gcube.smartgears.ContextProvider;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* MyApp Manager
*
* @author Alessandro Pieve (alessandro.pieve@isti.cnr.it)
*
*/
public class MyAppManager implements ApplicationManager {
private static Logger logger = LoggerFactory.getLogger(MyAppManager.class);
ApplicationContext ctx = ContextProvider.get();
Timer timer = null;
public String dbName;
private QuotaUsage quotaUsage;
private QuotaDBPersistence quotaDbPersistence;
@Override
public void onInit() {
//do something on init
logger.info("QuotaCheckTask on init");
String token = SecurityTokenProvider.instance.get();
String context = ScopeProvider.instance.get();
logger.info("QuotaCheckTask on discovery");
DiscoveryConfiguration discoveryCheck =new DiscoveryConfiguration(context);
logger.info("QuotaCheckTask DiscoveryConfiguration complete");
dbName=discoveryCheck.getDbname();
quotaDbPersistence= new QuotaDBPersistence(discoveryCheck.getDatabasePath(),discoveryCheck.getDbname(),
discoveryCheck.getUsernameDb(),discoveryCheck.getPwdnameDb());
quotaUsage =new QuotaUsage(discoveryCheck);
AccountingPersistenceQuery apq = AccountingPersistenceQueryFactory.getInstance();
QuotaCheckTask task = new QuotaCheckTask(context, token,quotaUsage,quotaDbPersistence,apq);
Integer refreshTimeQuotaConfiguration=discoveryCheck.getRefreshTimeQuota();
Long refreshTimeQuota;
if (refreshTimeQuotaConfiguration==0){
refreshTimeQuota=Constants.TIME_SCHEDULE_CHECK;
}
else{
refreshTimeQuota=(long) (refreshTimeQuotaConfiguration*60*1000);
}
timer = new Timer(true);
timer.scheduleAtFixedRate(task,Constants.DELAY_SCHEDULE_CHECK, refreshTimeQuota);
logger.info("QuotaCheckTask started in context {}", context);
logger.info("QuotaCheckTask schedule task on:{} milliseconds", refreshTimeQuota);
logger.info("QuotaCheckTask notifierUser :{} notifierAdmin:{}", discoveryCheck.getNotifierUser(),discoveryCheck.getNotifierAdmin());
}
@Override
public void onShutdown() {
timer.cancel();
}
public QuotaUsage getQuotaUsage() {
return quotaUsage;
}
public QuotaDBPersistence getQuotaDbPersistence() {
return quotaDbPersistence;
}
}

View File

@ -0,0 +1,250 @@
package org.gcube.resource.management.quota.manager.check;
import static org.gcube.common.authorization.client.Constants.authorizationService;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.gcube.accounting.analytics.TemporalConstraint;
import org.gcube.accounting.analytics.UsageValue;
import org.gcube.accounting.datamodel.AggregatedUsageRecord;
import org.gcube.common.authorization.library.policies.Policy;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.library.provider.UserInfo;
import org.gcube.resource.management.quota.library.quotalist.Quota;
import org.gcube.resource.management.quota.library.quotalist.QuotaType;
import org.gcube.resource.management.quota.library.quotalist.ServiceQuota;
import org.gcube.resource.management.quota.library.quotalist.StorageQuota;
import org.gcube.resource.management.quota.library.quotalist.TimeInterval;
import org.gcube.resource.management.quota.library.quotedefault.QuotaDefault;
import org.gcube.resource.management.quota.library.quotedefault.ServiceQuotaDefault;
import org.gcube.resource.management.quota.library.quotedefault.StorageQuotaDefault;
import org.gcube.resource.management.quota.manager.persistence.QuotaDBPersistence;
import org.gcube.resource.management.quota.manager.util.QuotaUsageStorageValue;
import org.gcuberesource.management.quota.manager.service.exception.NotFoundQuotaPackageExecption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* QuotaCalculateUtil
*
* @author Alessandro Pieve (alessandro.pieve@isti.cnr.it)
*
*/
public class QuotaCalculateUtil {
private static Logger log = LoggerFactory.getLogger(QuotaCalculateUtil.class);
private QuotaDBPersistence quotaDbPersistence;
private List<QuotaDefault> quoteDefault=null;
public void setQuoteDefault(List<QuotaDefault> quoteDefault) {
this.quoteDefault = quoteDefault;
}
public List<QuotaDefault> getQuoteDefault() {
return quoteDefault;
}
private String context;
private List<UsageValue> usageToBeVerified=new ArrayList<UsageValue>();
public List<UsageValue> getUsageToBeVerified() {
return usageToBeVerified;
}
public QuotaCalculateUtil(String context,QuotaDBPersistence quotaDbPersistence){
this.context=context;
this.quotaDbPersistence=quotaDbPersistence;
}
/**
* Prepare list for of usage value for accounting from Quota
* @param quota
* @throws NotFoundQuotaPackageExecption
*/
public void verifyListUser(List<String> listUser){
for (String identifier: listUser){
log.trace("verify for user:{} in context:{},if have a no default quota",identifier,context);
//loop for each quota default
for (QuotaDefault quotaDefault:quoteDefault){
Quota quotaSpecified=null;
//search a quota specified
quotaSpecified=quotaDbPersistence.getQuotaSpecified(identifier, context,quotaDefault.getQuotaType(),quotaDefault.getTimeInterval(), quotaDefault.getQuotaValue());
log.debug("quota Specified:{} quotaDefault:{}",quotaSpecified,quotaDefault);
//if not have a quota specified, use a default quota
if (quotaSpecified==null){
//log.debug("identifier:{} used quota default for quota type:{}-{}-",identifier,quotaDefault.getQuotaType(),QuotaType.STORAGE.toString());
if (quotaDefault.getQuotaType()==QuotaType.SERVICE){
log.debug("identifier:{} used quota SERVICE",identifier);
ServiceQuotaDefault quotaDefaultService = (ServiceQuotaDefault)quotaDefault;
quotaSpecified = new ServiceQuota(context,identifier,quotaDefaultService.getCallerType(),
quotaDefaultService.getServiceId(),quotaDefaultService.getTimeInterval(),
quotaDefaultService.getQuotaValue(),quotaDefaultService.getAccessType());
}
if (quotaDefault.getQuotaType()==QuotaType.STORAGE){
log.debug("identifier:{} used quota STORAGE",identifier);
StorageQuotaDefault quotaDefaultStorage = (StorageQuotaDefault)quotaDefault;
quotaSpecified = new StorageQuota(context,identifier,quotaDefaultStorage.getCallerType(),
quotaDefaultStorage.getTimeInterval(),quotaDefaultStorage.getQuotaValue());
}
}
try {
log.debug("add quota into list for accounting usage value"+quotaSpecified.toString());
//traduce a quota into list usageValue
AddList(quotaSpecified);
} catch (NotFoundQuotaPackageExecption e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//TODO ADD quote non comprese nel default
}
private void AddList(Quota quota) throws NotFoundQuotaPackageExecption{
TimeInterval interval= quota.getTimeInterval();
QuotaType type =quota.getQuotaType();
//log.info("Quote type:{}, class:{}",type,type.getQuotaTypeClass().getName());
Class<? extends AggregatedUsageRecord<?, ?>> clz=type.getQuotaTypeClass();
log.debug("time interval get Value:{}",interval.getValue());
TemporalConstraint temporalConstraint =null;
if (interval.getValue()!=0){
Calendar endTime = Calendar.getInstance();
Calendar startTime = Calendar.getInstance();
startTime.add(Calendar.DATE,- interval.getValue());
temporalConstraint = new TemporalConstraint(startTime.getTimeInMillis(),
endTime.getTimeInMillis(),interval.getAggregationMode());
}
if (quota.getQuotaType().equals(QuotaType.SERVICE)){
/*
List<FiltersValue> filtersList=null;
filtersList=new ArrayList<FiltersValue>();
ServiceQuota quotaService = (ServiceQuota)quota;
String serviceIdentifier=quotaService.getServiceId();
//translate serviceIdentifier into string
String[] parts = serviceIdentifier.split(":");
String serviceClass = parts[0];
String serviceName = parts[1];
String serviceId = parts[2];
List<Filter> filters =new ArrayList<Filter>();
filters.add(new Filter("serviceClass", serviceClass));
filters.add(new Filter("serviceName", serviceName));
QuotaUsageServiceValue totalFilterQuota =new QuotaUsageServiceValue
(quotaService.getContext(),quotaService.getIdentifier(),clz,temporalConstraint,filters);
totalFilterQuota.setdQuota(quotaService.getQuotaValue());
totalFilterQuota.setCallerType(quotaService.getCallerType());
totalFilterQuota.setAccessType(quotaService.getAccessType());
log.debug("totalfilter:{}",totalFilterQuota.toString());
this.usageToBeVerified.add(totalFilterQuota);
*/
}
else
{
QuotaUsageStorageValue totalFilterQuota =new QuotaUsageStorageValue(quota.getContext(),quota.getIdentifier(),clz,temporalConstraint);
totalFilterQuota.setdQuota(quota.getQuotaValue());
log.debug("totalfilter:{}",totalFilterQuota.toString());
this.usageToBeVerified.add(totalFilterQuota);
}
}
/**
* If your quota is complete insert a policy Block
*
* @param quota
*/
public void insertPolicyBlock(Quota quotaBlocked){
log.info("Quota Execed insert a policy :{}",quotaBlocked.toString());
String token = null;
try {
token = authorizationService().generateUserToken(new UserInfo(quotaBlocked.getContext(), new ArrayList<String>()), quotaBlocked.getContext());
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
SecurityTokenProvider.instance.set(token);
List<Policy> policies = new ArrayList<Policy>();
if (quotaBlocked.getQuotaType().equals(QuotaType.SERVICE)){
//TODO todo complete
/*
ServiceQuota quotaService = (ServiceQuota)quotaBlocked;
//AccessType accessType=quotaService.getAccessType();
Action access =Action.valueOf(quotaService.getAccessType().toString());
Long servicePackgeId=quotaService.getServicePackageId();
try {
ServicePackage servicepackage=quotaPackagePersistence.getPackage(servicePackgeId);
for (ServicePackageDetail servicePackageDetail:servicepackage.getServicesPackageDetail()){
String contentService=servicePackageDetail.getContent();
String[] serviceFilter=contentService.split(":");
String serviceClass=serviceFilter[0];
String serviceName="*";
if (serviceFilter.length>1){
serviceName=serviceFilter[1];
}
String serviceId="*";
ServiceAccess service=new ServiceAccess(serviceName, serviceClass, serviceId);
log.info("Quota Execed caller type :{}",quotaBlocked.getCallerType());
log.info("Quota Execed caller type string :{}",quotaBlocked.getCallerType().toString());
if (quotaBlocked.getCallerType().equals(CallerType.USER)){
log.debug("add policy with user"+quotaBlocked.toString());
//verificare se non e' gia presente
//altrimenti non inserire
policies.add(new User2ServicePolicy(quotaBlocked.getContext(),
service, Users.one(quotaBlocked.getIdentifier()), access ));
}
if (quotaBlocked.getCallerType().equals(CallerType.ROLE)){
log.debug("add policy with role"+quotaBlocked.toString());
//verificare se non e' gia presente
//altrimenti non inserire
policies.add(new User2ServicePolicy(quotaBlocked.getContext(),
service, Roles.one(quotaBlocked.getIdentifier()), access ));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
}
if (quotaBlocked.getQuotaType().equals(QuotaType.STORAGE)){
}
try {
log.debug("insert policy for quota:"+policies.toString());
authorizationService().addPolicies(policies);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,134 @@
package org.gcube.resource.management.quota.manager.check;
import java.util.ArrayList;
import java.util.List;
import org.gcube.accounting.analytics.UsageValue;
import org.gcube.accounting.analytics.persistence.AccountingPersistenceQuery;
import org.gcube.resource.management.quota.library.quotalist.QuotaType;
import org.gcube.resource.management.quota.manager.defaults.InformationSystemQuery;
import org.gcube.resource.management.quota.manager.persistence.QuotaDBPersistence;
import org.gcube.resource.management.quota.manager.util.Constants;
import org.gcube.resource.management.quota.manager.util.DiscoveryListUser;
import org.gcube.resource.management.quota.manager.util.QuotaUsageServiceValue;
import org.gcube.resource.management.quota.manager.util.QuotaUsageStorageValue;
import org.gcube.resource.management.quota.manager.util.ReadFileProperties;
import org.gcuberesource.management.quota.manager.service.exception.NotFoundQuotaExecption;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.couchbase.client.deps.io.netty.handler.timeout.TimeoutException;
/**
* Quota check use a specify context
* Verify for context all quota inserted
*
* @author Alessandro Pieve (alessandro.pieve@isti.cnr.it)
*
*/
public class QuotaCheck {
private static Logger log = LoggerFactory.getLogger(QuotaCheck.class);
private QuotaUsage queryQuotaUsage;
private QuotaDBPersistence quotaDbPersistence;
private AccountingPersistenceQuery apq;
private String context=null;
/**
* List quota for specify context
* @param context
* @throws NotFoundQuotaExecption
* @throws JSONException
*/
public QuotaCheck(String context,QuotaUsage queryQuotaUsage,QuotaDBPersistence quotaDbPersistence,AccountingPersistenceQuery apq) throws NotFoundQuotaExecption{
this.context=context;
this.queryQuotaUsage=queryQuotaUsage;
this.quotaDbPersistence=quotaDbPersistence;
this.apq=apq;
}
public void getQuotaCheck() throws Exception{
log.info("QuotaCheck - init quota check task");
QuotaCalculateUtil quotaUtility= new QuotaCalculateUtil(context,quotaDbPersistence);
//create a list quota found on information System
InformationSystemQuery informationSystemQuery =new InformationSystemQuery();
log.debug("QuotaCheck - context:{}, setQuoteDefault:{}",context,informationSystemQuery.getListQuotaDefault());
//set quota utility with quota default found on is
quotaUtility.setQuoteDefault(informationSystemQuery.getListQuotaDefault());
//TODO verify of not a quota default and get file properties
if (quotaUtility.getQuoteDefault()==null){
log.debug("QuotaCheck - No quota default found on IS");
ReadFileProperties fileQuota = new ReadFileProperties(Constants.FILE_PROPERTIES_QUOTA);
quotaUtility.setQuoteDefault(fileQuota.getListQuotaDefault());
}
//list of user for specify context
DiscoveryListUser discoveryListUser= new DiscoveryListUser(this.context);
log.debug("QuotaCheck - for context:{} , list user:{}",context,discoveryListUser.getListUser());
//verify for each user if have a specify quota and Overwrite if exist and traduce into object for query accounting
quotaUtility.verifyListUser(discoveryListUser.getListUser());
log.debug("QuotaCheck - quotaUtility.getUsageToBeVerified():{}",quotaUtility.getUsageToBeVerified());
Boolean error=true;
//init accounting Persistence
//AccountingPersistenceQuery apq = AccountingPersistenceQueryFactory.getInstance();
List<UsageValue> quoteChecked=new ArrayList<UsageValue>();
try {
quoteChecked=apq.getUsageValueQuotaTotal(quotaUtility.getUsageToBeVerified());
error=false;
}catch(TimeoutException te){
log.error("error timeout on call accounting",te);
quoteChecked=apq.getUsageValueQuotaTotal(quotaUtility.getUsageToBeVerified());
}
catch (Exception e) {
log.error("error on call accounting",e);
quoteChecked=apq.getUsageValueQuotaTotal(quotaUtility.getUsageToBeVerified());
}
log.error("error:{}",error);
if (!error){
log.debug("return quota usage:{}",quoteChecked);
//insert into db
for(UsageValue usageIndex:quotaUtility.getUsageToBeVerified()){
if (usageIndex.getClz()==QuotaType.STORAGE.getQuotaTypeClass()){
log.debug("save quota storage identifier:{},temporalConstraint:{}",usageIndex.getIdentifier(),usageIndex.getTemporalConstraint());
QuotaUsageStorageValue usageStorVal=(QuotaUsageStorageValue) usageIndex;
queryQuotaUsage.insertStorageQuota(usageStorVal);
}
if (usageIndex.getClz()==QuotaType.SERVICE.getQuotaTypeClass()){
log.debug("save quota service identifier:{},temporalConstraint:{}",usageIndex.getIdentifier(),usageIndex.getTemporalConstraint());
QuotaUsageServiceValue usageSerVal=(QuotaUsageServiceValue) usageIndex;
queryQuotaUsage.insertServiceQuota(usageSerVal);
}
}
queryQuotaUsage.SendNotificationAdmin();
}
//TODO
/*
log.info("Checked quota:{}",quoteChecked);
for(UsageValue usageValue:quoteChecked){
//set in quota entity usageValue
quotaPersistence.setUsageQuota(quoteInsert.get(usageValue.getIdentifier()),usageValue.getD());
log.info("For identifier:{} quota/usage is:{}/{}",usageValue.getIdentifier(),quoteInsert.get(usageValue.getIdentifier()),usageValue.getD());
if (usageValue.getD()>quoteInsert.get(usageValue.getIdentifier()).getQuotaValue()){
insertPolicyBlock(quoteInsert.get(usageValue.getIdentifier()));
}
}
log.info("QuotaCheck end");
*/
}
}

View File

@ -0,0 +1,62 @@
package org.gcube.resource.management.quota.manager.check;
import java.util.Date;
import java.util.TimerTask;
import org.gcube.accounting.analytics.persistence.AccountingPersistenceQuery;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.resource.management.quota.manager.persistence.QuotaDBPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Quota Check Task
* Run with timerTask each DELAY_SCHEDULE_CHEK
*
*
*@author Alessandro Pieve (alessandro.pieve@isti.cnr.it)
*
*/
public class QuotaCheckTask extends TimerTask {
private static Logger log = LoggerFactory.getLogger(QuotaCheckTask.class);
String context;
String token;
private QuotaUsage quotaUsage;
private QuotaDBPersistence quotaDbPersistence;
private AccountingPersistenceQuery apq;
public QuotaCheckTask(String context, String token, QuotaUsage quotaUsage,QuotaDBPersistence quotaDbPersistence,AccountingPersistenceQuery apq) {
super();
this.context = context;
this.token = token;
this.quotaUsage = quotaUsage;
this.quotaDbPersistence = quotaDbPersistence;
this.apq=apq;
}
@Override
public void run() {
//TODO Prendere il contesto del token
String context=ScopeProvider.instance.get();
ScopeProvider.instance.set(context);
log.info("Timer task run at:{} in this context:{}",new Date(),context);
try {
QuotaCheck quotaCheck= new QuotaCheck(context,quotaUsage,quotaDbPersistence,apq);
quotaCheck.getQuotaCheck();
log.info("Timer finish");
} catch (Exception e) {
log.warn("No quota found!");
}
}
}

View File

@ -0,0 +1,343 @@
package org.gcube.resource.management.quota.manager.check;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.gcube.accounting.analytics.Filter;
import org.gcube.resource.management.quota.library.quotalist.TimeInterval;
import org.gcube.resource.management.quota.library.status.QuotaStorageStatus;
import org.gcube.resource.management.quota.manager.util.Constants;
import org.gcube.resource.management.quota.manager.util.ConstantsDb;
import org.gcube.resource.management.quota.manager.util.DiscoveryConfiguration;
import org.gcube.resource.management.quota.manager.util.QuotaUsageServiceValue;
import org.gcube.resource.management.quota.manager.util.QuotaUsageStorageValue;
import org.gcube.resource.management.quota.manager.util.SendNotification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* QuotaUsage
*
* @author Alessandro Pieve (alessandro.pieve@isti.cnr.it)
*
*/
public class QuotaUsage {
private static Logger log = LoggerFactory.getLogger(QuotaUsage.class);
private DiscoveryConfiguration discoveryCheck;
private SendNotification sendNotification;
public QuotaUsage(DiscoveryConfiguration discoveryCheck){
super();
this.discoveryCheck=discoveryCheck;
sendNotification=new SendNotification(discoveryCheck);
};
public List<String> userExceedQuota =new ArrayList<String>();
public void insertServiceQuota(QuotaUsageServiceValue usageSerVal) throws Exception {
String context_label=usageSerVal.getContext().replace('/', '_').toUpperCase();
Connection connection = getDBConnection();
Statement stmt = null;
try {
connection.setAutoCommit(false);
stmt = connection.createStatement();
String periodQuota=usageSerVal.getTemporalConstraint().getAggregationMode().toString();
if (!verifyTable(connection,ConstantsDb.DATABASE_PREFIX+ConstantsDb.SEPARATOR+ConstantsDb.DATABASE_TYPE_SERVICE+ConstantsDb.SEPARATOR+
context_label+ConstantsDb.SEPARATOR+periodQuota)){
String queryCreate="CREATE TABLE "+ConstantsDb.DATABASE_PREFIX+ConstantsDb.SEPARATOR+ConstantsDb.DATABASE_TYPE_SERVICE+ConstantsDb.SEPARATOR+
context_label+ConstantsDb.SEPARATOR+periodQuota+""
+ "(CALLERTYPE varchar(255),IDENTIFIER varchar(255) ,SERVICE varchar(255),"
+ "ACCESSTYPE varchar(50),QUOTAASSIGNED DOUBLE PRECISION, QUOTAUSAGE DOUBLE PRECISION,POLICY integer,"
+ "primary key(CALLERTYPE,IDENTIFIER,SERVICE))";
stmt.execute(queryCreate);
}
String serviceIdentifier = "";
for (Filter tmp:usageSerVal.getFilters()){
serviceIdentifier=serviceIdentifier+tmp.getValue()+":";
}
//TODO
serviceIdentifier=serviceIdentifier+"0";
String queryVerify="SELECT count(*) FROM "+ConstantsDb.DATABASE_PREFIX+ConstantsDb.SEPARATOR+ConstantsDb.DATABASE_TYPE_STORAGE+ConstantsDb.SEPARATOR+periodQuota+""
+ " WHERE IDENTIFIER ='"+usageSerVal.getIdentifier()+"'";
ResultSet rs = stmt.executeQuery(queryVerify);
rs.next();
String queryInsert;
if (rs.getInt(1)==0){
queryInsert="INSERT into "+ConstantsDb.DATABASE_PREFIX+ConstantsDb.SEPARATOR+ConstantsDb.DATABASE_TYPE_SERVICE+ConstantsDb.SEPARATOR+
context_label+ConstantsDb.SEPARATOR+periodQuota+""
+ " (CALLERTYPE,IDENTIFIER, SERVICE,ACCESSTYPE,QUOTAASSIGNED, QUOTAUSAGE) VALUES('"+usageSerVal.getCallerType()+"',"
+ "'"+usageSerVal.getIdentifier()+"','"+serviceIdentifier+"',"
+"'"+usageSerVal.getAccessType()+"'," +usageSerVal.getdQuota()+","+usageSerVal.getD()+")";
}else{
queryInsert="UPDATE "+ConstantsDb.DATABASE_PREFIX+ConstantsDb.SEPARATOR+ConstantsDb.DATABASE_TYPE_SERVICE+ConstantsDb.SEPARATOR+
context_label+ConstantsDb.SEPARATOR+periodQuota+""
+ "SET ACCESSTYPE='"+usageSerVal.getAccessType()+"' ,"
+ "QUOTAASSIGNED="+usageSerVal.getdQuota()+" ,"
+ "QUOTAUSAGE="+usageSerVal.getD()+""
+ "WHERE CALLERTYPE='"+usageSerVal.getCallerType()+"' AND"
+ " IDENTIFIER='"+usageSerVal.getIdentifier()+"' AND"
+ " SERVICE='"+serviceIdentifier+"'";
}
log.debug("Insert data into table:{}",queryInsert);
stmt.execute(queryInsert);
stmt.close();
connection.commit();
} catch (SQLException e) {
log.error("Sql error Message " + e);
} catch (Exception e) {
log.error("Exception error Message " + e);
} finally {
connection.close();
}
}
public void insertStorageQuota(QuotaUsageStorageValue usageStorVal) throws Exception {
Connection connection = getDBConnection();
Statement stmt = null;
try {
Boolean notificationWarning1 =false;
Boolean notificationWarning2 =false;
Boolean notificationExceed =false;
Double quotaAssignedOld = 0.0;
connection.setAutoCommit(false);
stmt = connection.createStatement();
String periodQuota=ConstantsDb.DATABASE_PERIOD_TOTAL;
if (usageStorVal.getTemporalConstraint()!=null){
periodQuota=usageStorVal.getTemporalConstraint().getAggregationMode().toString();
}
if (!verifyTable(connection,ConstantsDb.DATABASE_PREFIX+ConstantsDb.SEPARATOR+ConstantsDb.DATABASE_TYPE_STORAGE+
ConstantsDb.SEPARATOR+periodQuota)){
String queryCreate="CREATE TABLE "+ConstantsDb.DATABASE_PREFIX+ConstantsDb.SEPARATOR+ConstantsDb.DATABASE_TYPE_STORAGE+ConstantsDb.SEPARATOR+periodQuota+""
+ "(IDENTIFIER varchar(255) primary key,QUOTAASSIGNED DOUBLE PRECISION, QUOTAUSAGE DOUBLE PRECISION, "
+ "NOTIFICATIONWARNING1 boolean default false,NOTIFICATIONWARNING2 boolean default false,NOTIFICATIONEXCEED boolean default false)";
log.debug("Create table:{}",queryCreate);
stmt.execute(queryCreate);
}
Double percent=((usageStorVal.getD()/usageStorVal.getdQuota())*100);
percent=Math.round(percent * 100.0) / 100.0;
log.debug("Quota Percent quota:{} used:{},use:{}",usageStorVal.getdQuota(),usageStorVal.getD(),percent);
String queryVerify="SELECT NOTIFICATIONWARNING1,NOTIFICATIONWARNING2,NOTIFICATIONEXCEED,QUOTAASSIGNED FROM "+ConstantsDb.DATABASE_PREFIX+ConstantsDb.SEPARATOR+ConstantsDb.DATABASE_TYPE_STORAGE+ConstantsDb.SEPARATOR+periodQuota+""
+ " WHERE IDENTIFIER ='"+usageStorVal.getIdentifier()+"'";
ResultSet rs = stmt.executeQuery(queryVerify);
while (rs.next()) {
notificationWarning1 = rs.getBoolean("NOTIFICATIONWARNING1");
notificationWarning2 = rs.getBoolean("NOTIFICATIONWARNING2");
notificationExceed = rs.getBoolean("NOTIFICATIONEXCEED");
quotaAssignedOld= rs.getDouble("QUOTAASSIGNED");
}
if (quotaAssignedOld!=usageStorVal.getdQuota()){
//verify if your quota assigned is changed
log.debug("quota changed old value:{} new value:{}",quotaAssignedOld,usageStorVal.getdQuota());
}
//verify if a getdQuota() == -1 considery a infinity quota
log.debug("usageStorVal.getdQuota()!=-1 :"+usageStorVal.getdQuota());
if (usageStorVal.getdQuota()!=-1){
if ((percent>Constants.LIMIT_MSG_QUOTA_PERC_USAGE_1)&&(percent<Constants.LIMIT_MSG_QUOTA_PERC_USAGE_2)){
//verify if your quota is between 90 and 95 % first warning
if (!notificationWarning1){
sendNotification.sendNotificationUser(usageStorVal.getIdentifier(),usageStorVal.getdQuota(),usageStorVal.getD(),percent,"warning");
notificationWarning1=true;
notificationWarning2=false;
notificationExceed=false;
}
}
else if ((percent>Constants.LIMIT_MSG_QUOTA_PERC_USAGE_2)&&(percent<100)){
//verify if your quota is between 95 and 100 % second warning
if (!notificationWarning2){
sendNotification.sendNotificationUser(usageStorVal.getIdentifier(),usageStorVal.getdQuota(),usageStorVal.getD(),percent,"warning");
notificationWarning2=true;
notificationExceed=false;
}
}
else if ((percent>=100)){
//your quota is exceed
log.debug("Quota exceed for:{} identifier:{} notification:{} ",percent,usageStorVal.getIdentifier(),notificationExceed);
if (!notificationExceed){
sendNotification.sendNotificationUser(usageStorVal.getIdentifier(),usageStorVal.getdQuota(),usageStorVal.getD(),percent,"exceed");
userExceedQuota.add(usageStorVal.getIdentifier());
notificationExceed=true;
}
}
else if (notificationWarning1 || notificationWarning2 || notificationExceed){
//your quota value is restored
log.debug("---Quota reset for identifier:{} and usage :{} and quota:{}",
usageStorVal.getIdentifier(),usageStorVal.getdQuota(),usageStorVal.getD());
log.debug("---Quota reset for notificationWarning1:{} and notificationWarning2 :{} and notificationExceed:{}",
notificationWarning1,notificationWarning2,notificationExceed);
sendNotification.sendNotificationUser(usageStorVal.getIdentifier(),usageStorVal.getdQuota(),usageStorVal.getD(),percent,"reset");
notificationWarning1=false;
notificationWarning2=false;
notificationExceed=false;
}
}
queryVerify="SELECT count(*) FROM "+ConstantsDb.DATABASE_PREFIX+ConstantsDb.SEPARATOR+ConstantsDb.DATABASE_TYPE_STORAGE+ConstantsDb.SEPARATOR+periodQuota+""
+ " WHERE IDENTIFIER ='"+usageStorVal.getIdentifier()+"'";
rs = stmt.executeQuery(queryVerify);
rs.next();
String queryInsert;
if (rs.getInt(1)==0){
queryInsert="INSERT into "+ConstantsDb.DATABASE_PREFIX+ConstantsDb.SEPARATOR+ConstantsDb.DATABASE_TYPE_STORAGE+ConstantsDb.SEPARATOR+periodQuota+""
+ " (IDENTIFIER, QUOTAASSIGNED, QUOTAUSAGE,NOTIFICATIONWARNING1,NOTIFICATIONWARNING2,NOTIFICATIONEXCEED) VALUES('"+usageStorVal.getIdentifier()+"',"
+usageStorVal.getdQuota()+","+usageStorVal.getD()+","+notificationWarning1+""
+ ","+notificationWarning2+""
+ ","+notificationExceed+")";
}else{
queryInsert="UPDATE "+ConstantsDb.DATABASE_PREFIX+ConstantsDb.SEPARATOR+ConstantsDb.DATABASE_TYPE_STORAGE+ConstantsDb.SEPARATOR+periodQuota+""
+ " set QUOTAASSIGNED="+usageStorVal.getdQuota()+","
+ "QUOTAUSAGE="+usageStorVal.getD()+" ,"
+ "NOTIFICATIONEXCEED="+notificationExceed+" ,"
+ "NOTIFICATIONWARNING1="+notificationWarning1+","
+ "NOTIFICATIONWARNING2="+notificationWarning2+" "
+ "where IDENTIFIER='"+usageStorVal.getIdentifier()+"'";
}
log.debug("Insert data into table:{}",queryInsert);
stmt.execute(queryInsert);
stmt.close();
connection.commit();
} catch (SQLException e) {
log.error("Sql error Message " + e);
} catch (Exception e) {
log.error("Exception error Message " + e);
} finally {
connection.close();
}
}
public void SendNotificationAdmin() {
try {
log.debug("Send Notification to Admin");
sendNotification.SendNotificationAdmin(userExceedQuota);
userExceedQuota.clear();
} catch (Exception e) {
e.printStackTrace();
}
}
public QuotaStorageStatus selectStorageQuota(String identifier, TimeInterval interval)throws Exception {
Connection connection = getDBConnection();
QuotaStorageStatus quotaStorageStatus = null;
Statement stmt = null;
try {
connection.setAutoCommit(false);
stmt = connection.createStatement();
String periodQuota=ConstantsDb.DATABASE_PERIOD_TOTAL;
Double quotaAssigned = 0.0;
Double quotaUsage=0.0;
//Quota Storage Total
if (interval.equals(TimeInterval.FOREVER)){
String query="SELECT * FROM "+ConstantsDb.DATABASE_PREFIX+ConstantsDb.SEPARATOR+ConstantsDb.DATABASE_TYPE_STORAGE+ConstantsDb.SEPARATOR+periodQuota+""
+ " WHERE IDENTIFIER='"+identifier+"'";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
quotaAssigned=rs.getDouble("QUOTAASSIGNED");
quotaUsage=rs.getDouble("QUOTAUSAGE");
}
}
stmt.close();
connection.commit();
quotaStorageStatus =new QuotaStorageStatus(identifier,interval,quotaAssigned,quotaUsage);
} catch (SQLException e) {
log.error("Sql error Message " + e);
} catch (Exception e) {
log.error("Exception error Message " + e);
} finally {
connection.close();
}
return quotaStorageStatus;
}
/**
* Verify if exist a table
* @param connection
* @param tableName
* @return boolean true if exist
* @throws SQLException
*/
private Boolean verifyTable(Connection connection, String tableName) throws SQLException{
boolean tExists = false;
DatabaseMetaData dbm = connection.getMetaData();
ResultSet tables = dbm.getTables(null, null, tableName, null);
if (tables.next()) {
tExists = true;
}
log.trace("verifyTable :{} result:{}",tableName,tExists);
return tExists;
}
/**
* Init connection db
* @return connection
*/
private Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName(ConstantsDb.DB_DRIVER);
} catch (ClassNotFoundException e) {
log.error("error class not found exception",e);
}
try {
String nameConnection="jdbc:postgresql://"+discoveryCheck.getDatabasePath()+"/"+discoveryCheck.getDbname();
dbConnection = DriverManager.getConnection(nameConnection, discoveryCheck.getUsernameDb(),discoveryCheck.getPwdnameDb());
return dbConnection;
} catch (SQLException e) {
log.error("error connecting to db",e);
}
return dbConnection;
}
}

View File

@ -0,0 +1,70 @@
package org.gcube.resource.management.quota.manager.defaults;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import org.gcube.common.resources.gcore.GenericResource;
import org.gcube.resource.management.quota.library.quotedefault.QuotaDefault;
import org.gcube.resource.management.quota.library.quotedefault.QuotaDefaultList;
import org.gcube.resource.management.quota.manager.util.Constants;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.gcube.resources.discovery.icclient.ICFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* InformationSystemQuery
*
* @author Alessandro Pieve (alessandro.pieve@isti.cnr.it)
*
*/
public class InformationSystemQuery {
private static Logger log = LoggerFactory
.getLogger(InformationSystemQuery.class);
private List<QuotaDefault> listQuotaDefault=new ArrayList<QuotaDefault>();
/**
* Query at information System for retrive a list quote default
*/
public InformationSystemQuery(){
SimpleQuery query = ICFactory.queryFor(GenericResource.class);
query.addCondition(
"$resource/Profile/SecondaryType/text() eq '"
+ Constants.QUOTA_CATEGORY + "'")
.addCondition(
"$resource/Profile/Name/text() eq '"
+ Constants.QUOTA_NAME + "'")
.setResult("$resource");
DiscoveryClient<GenericResource> client = ICFactory
.clientFor(GenericResource.class);
List<GenericResource> quotaResources = client.submit(query);
QuotaDefaultList quotalist=null;
if (quotaResources.size()>0){
String resource=quotaResources.get(0).profile().bodyAsString();
try {
JAXBContext jaxbContext = JAXBContext.newInstance(QuotaDefaultList.class);
quotalist = (QuotaDefaultList) jaxbContext.createUnmarshaller().unmarshal(new StringReader(resource.toString()));
listQuotaDefault=quotalist.getQuotaDefaultList();
log.debug("From IS found a quota default:{}",quotalist.toString());
}catch (Exception e) {
log.error("--:{}",e.getLocalizedMessage());
e.printStackTrace();
}
}
}
public List<QuotaDefault> getListQuotaDefault() {
return listQuotaDefault;
}
}

View File

@ -0,0 +1,346 @@
package org.gcube.resource.management.quota.manager.persistence;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import lombok.extern.slf4j.Slf4j;
import org.gcube.resource.management.quota.library.quotalist.Quota;
import org.gcube.resource.management.quota.library.quotalist.QuotaType;
import org.gcube.resource.management.quota.library.quotalist.ServiceQuota;
import org.gcube.resource.management.quota.library.quotalist.StorageQuota;
import org.gcube.resource.management.quota.library.quotalist.TimeInterval;
import org.gcube.resource.management.quota.manager.persistence.entities.QuotaEntity;
import org.gcube.resource.management.quota.manager.persistence.entities.ServiceQuotaEntity;
import org.gcube.resource.management.quota.manager.persistence.entities.StorageQuotaEntity;
import org.gcuberesource.management.quota.manager.service.exception.NotFoundQuotaExecption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* Persistence for quota DB manager
* @author Alessandro Pieve (alessandro.pieve@isti.cnr.it)
*
*/
@Singleton
@Slf4j
public class QuotaDBPersistence{
protected EntityManagerFactory emFactory;
public QuotaDBPersistence(String db_Connection, String db_Name, String db_User,String db_Password){
Map<String, String> persistenceMap = new HashMap<String, String>();
persistenceMap.put("javax.persistence.jdbc.url", "jdbc:postgresql://"+db_Connection+":5432/"+db_Name);
persistenceMap.put("javax.persistence.jdbc.user", db_User);
persistenceMap.put("javax.persistence.jdbc.password", db_Password);
persistenceMap.put("javax.persistence.jdbc.driver", "org.postgresql.Driver");
emFactory = Persistence.createEntityManagerFactory("quota_persistence", persistenceMap);
}
private static Logger log = LoggerFactory.getLogger(QuotaDBPersistence.class);
/**
* Add Quota to persist
* @param quote
*/
public Quota addQuota(Quota quota) {
EntityManager em = emFactory.createEntityManager();
try{
QuotaEntity quotaEntity = null;
if (quota.getQuotaType()==QuotaType.SERVICE){
quotaEntity=new ServiceQuotaEntity(quota.getContext(),
quota.getIdentifier(),quota.getCallerType(), quota.getTimeInterval(),quota.getQuotaValue());
}
if (quota.getQuotaType()==QuotaType.STORAGE){
quotaEntity=new StorageQuotaEntity(quota.getContext(),
quota.getIdentifier(),quota.getCallerType(), quota.getTimeInterval(),quota.getQuotaValue());
}
quota.setId(quotaEntity.getId());
quota.setCreationTime(quotaEntity.getCreationTime());
quota.setLastUpdateTime(quotaEntity.getLastUpdateTime());
em.getTransaction().begin();
em.persist(quotaEntity);
em.getTransaction().commit();
return quota;
}catch (Exception e) {
log.error("addQuota except:{}",e);
em.getTransaction().rollback();
//em.close();
return null;
}
finally{
em.close();
}
}
/**
* Add Quote to persist
* @param quote
*/
public void addQuote(List<Quota> quote) {
EntityManager em = emFactory.createEntityManager();
try{
em.getTransaction().begin();
for (Quota quota: quote){
log.debug("addQuote quota string:{}",quota.toString());
log.debug("addQuote:{}",quota.getQuotaType());
log.debug("Type service:{}, storage:{}",QuotaType.SERVICE,QuotaType.STORAGE);
QuotaEntity quotaEntity=null;
/*TODO DA completare per la parte dei service*/
if (quota.getQuotaType()==QuotaType.SERVICE){
log.debug("addQuote:service");
ServiceQuota quotaService = (ServiceQuota)quota;
quotaEntity=new ServiceQuotaEntity(quotaService.getContext(),
quotaService.getIdentifier(), quotaService.getCallerType(),quotaService.getServiceId(), quotaService.getTimeInterval(),quotaService.getQuotaValue(),quotaService.getAccessType());
}
if (quota.getQuotaType()==QuotaType.STORAGE){
log.debug("addQuote:storage");
StorageQuota quotaStorage = (StorageQuota)quota;
quotaEntity=new StorageQuotaEntity(quotaStorage.getContext(),
quotaStorage.getIdentifier(), quotaStorage.getCallerType(), quotaStorage.getTimeInterval(),quotaStorage.getQuotaValue());
}
em.persist(quotaEntity);
em.flush();
}
em.getTransaction().commit();
}catch (Exception e) {
log.error("addQuote except:{}",e);
em.getTransaction().rollback();
//em.close();
}
finally{
em.close();
}
}
/**
* Get a specify quota
* @param quotaId
* @return Quota
*/
public Quota getQuota(long quotaId) {
EntityManager em = emFactory.createEntityManager();
try{
QuotaEntity quotaEntity= em.find(QuotaEntity.class, quotaId);
Quota quota=null;
//TODO da completare per la parte dei service
if (quotaEntity instanceof ServiceQuotaEntity){
log.debug("getQuote entity---if service");
ServiceQuotaEntity quotaEntityService = (ServiceQuotaEntity)quotaEntity;
quota = new ServiceQuota(quotaEntityService.getContext(),quotaEntityService.getIdentifier(),quotaEntityService.getCallerType(),quotaEntityService.getServicePackageId(),quotaEntityService.getTimeInterval(),quotaEntityService.getQuotaValue(),quotaEntityService.getAccessType());
}
if (quotaEntity instanceof StorageQuotaEntity){
StorageQuotaEntity quotaEntityStorage = (StorageQuotaEntity)quotaEntity;
quota =new StorageQuota(quotaEntityStorage.getContext(),quotaEntityStorage.getIdentifier(),quotaEntityStorage.getCallerType(),quotaEntityStorage.getTimeInterval(),quotaEntityStorage.getQuotaValue());
}
quota.setId(quotaEntity.getId());
quota.setCreationTime(quotaEntity.getCreationTime());
quota.setLastUpdateTime(quotaEntity.getLastUpdateTime());
return quota;
}catch (Exception e) {
log.error("getQuota except:{}",e);
em.getTransaction().rollback();
//em.close();
return null;
}
finally{
em.close();
}
}
/**
* Remove quote to persist
* @param quotaId
*/
public void removeQuota(long quotaId) {
EntityManager em = emFactory.createEntityManager();
try{
em.getTransaction().begin();
QuotaEntity entity = em.find(QuotaEntity.class, quotaId);
if (entity!= null){
em.remove(entity);
}
else{
log.warn("quote with id {} not found", quotaId);
}
em.getTransaction().commit();
}catch (Exception e) {
log.error("error removing quote with id {}", quotaId);
//em.close();
}
finally{
em.close();
}
}
/**
* Get list quote from context
* @param context
* @return List<Quota>
* @throws NotFoundQuotaExecption
*/
public List<Quota> getQuote(String context) throws NotFoundQuotaExecption {
List<Quota> quoteToReturn = new ArrayList<Quota>();
EntityManager em = emFactory.createEntityManager();
try{
TypedQuery<QuotaEntity> query = em.createNamedQuery("Quota.all", QuotaEntity.class);
//log.warn("getQuote---query");
query.setParameter("context", context);
//log.warn("getQuote---context:"+context);
if (query.getResultList().size()>0){
for (QuotaEntity qEntity: query.getResultList()){
log.debug("---getQuote---Entity list:"+qEntity.toString());
Quota quota=null;
//TODO for complete a service quota
//log.debug("qEntity.getQuotaType():{},QuotaType.SERVICE.toString():{}",qEntity.getQuotaType(),QuotaType.SERVICE.toString());
if (qEntity instanceof ServiceQuotaEntity){
log.debug("getQuote entity---if service");
ServiceQuotaEntity quotaEntityService = (ServiceQuotaEntity)qEntity;
quota = new ServiceQuota(quotaEntityService.getContext(),quotaEntityService.getIdentifier(),quotaEntityService.getCallerType(),quotaEntityService.getServicePackageId(),quotaEntityService.getTimeInterval(),quotaEntityService.getQuotaValue(),quotaEntityService.getAccessType());
}
if (qEntity instanceof StorageQuotaEntity){
log.debug("getQuote entity---if storage");
StorageQuotaEntity quotaEntityStorage = (StorageQuotaEntity)qEntity;
quota = new StorageQuota(quotaEntityStorage.getContext(),quotaEntityStorage.getIdentifier(),quotaEntityStorage.getCallerType(),quotaEntityStorage.getTimeInterval(),quotaEntityStorage.getQuotaValue());
}
quota.setId(qEntity.getId());
quota.setCreationTime(qEntity.getCreationTime());
quota.setLastUpdateTime(qEntity.getLastUpdateTime());
quoteToReturn.add(quota);
log.debug("getQuote---quoteToReturn:"+quota.toString());
}
}
else{
throw new NotFoundQuotaExecption("No quote found");
}
}
catch (Exception e) {
log.error("getQuote error {}",e);
//em.close();
}
finally{
em.close();
}
return quoteToReturn;
}
/***
*
*/
public Quota getQuotaByIdentifier(String identifier) {
Quota quotaToReturn = null;
EntityManager em = emFactory.createEntityManager();
try{
TypedQuery<QuotaEntity> query = em.createNamedQuery("Quota.getByIdentifier", QuotaEntity.class);
query.setParameter("identifier", identifier);
for (QuotaEntity qEntity: query.getResultList()){
if (qEntity.getQuotaType().equals(QuotaType.SERVICE.toString())){
ServiceQuotaEntity quotaEntityService = (ServiceQuotaEntity)qEntity;
quotaToReturn = new ServiceQuota(quotaEntityService.getContext(),quotaEntityService.getIdentifier(),quotaEntityService.getCallerType(),quotaEntityService.getTimeInterval(),quotaEntityService.getQuotaValue(),quotaEntityService.getAccessType());
}
if (qEntity.getQuotaType().equals(QuotaType.STORAGE.toString())){
quotaToReturn = new StorageQuota(qEntity.getContext(),qEntity.getIdentifier(),qEntity.getCallerType(),qEntity.getTimeInterval(),qEntity.getQuotaValue());
}
quotaToReturn.setId(qEntity.getId());
quotaToReturn.setCreationTime(qEntity.getCreationTime());
quotaToReturn.setLastUpdateTime(qEntity.getLastUpdateTime());
}
}catch (Exception e) {
log.error("getQuotaByIdentifier error retrive a quota for this identifier:{} error:{}",identifier, e);
//em.close();
}finally{
em.close();
}
return quotaToReturn;
}
/**
*
* @param identifier
* @param context
* @param quotaType
* @param timeInterval
* @param quotaValue
* @return
*/
public Quota getQuotaSpecified(String identifier, String context,QuotaType quotaType,TimeInterval timeInterval,Double quotaValue){
//log.debug("getQuotaSpecified init:{}");
Quota quotaToReturn = null;
EntityManager em = emFactory.createEntityManager();
//log.debug("getQuotaSpecified createEntityManager:{}");
try{
TypedQuery<QuotaEntity> query = em.createNamedQuery("Quota.getSpecified", QuotaEntity.class);
query.setParameter("identifier", identifier);
query.setParameter("context", context);
query.setParameter("quotaType", quotaType.toString());
query.setParameter("timeInterval", timeInterval);
//query.setParameter("quotaValue", quotaValue);
for (QuotaEntity qEntity: query.getResultList()){
//log.debug("getQuotaSpecified found a QuotaEntity:{}",qEntity.toString());
if (qEntity.getQuotaType().equals(QuotaType.SERVICE.toString())){
//log.debug("getQuotaSpecified found a Service");
ServiceQuotaEntity quotaEntityService = (ServiceQuotaEntity)qEntity;
quotaToReturn = new ServiceQuota(quotaEntityService.getContext(),quotaEntityService.getIdentifier(),quotaEntityService.getCallerType(),quotaEntityService.getTimeInterval(),quotaEntityService.getQuotaValue(),quotaEntityService.getAccessType());
}
if (qEntity.getQuotaType().equals(QuotaType.STORAGE.toString())){
//log.debug("getQuotaSpecified found a Storage");
quotaToReturn = new StorageQuota(qEntity.getContext(),qEntity.getIdentifier(),qEntity.getCallerType(),qEntity.getTimeInterval(),qEntity.getQuotaValue());
}
//log.debug("getQuotaSpecified Id quote found:{}",qEntity.getId());
quotaToReturn.setId(qEntity.getId());
}
}catch (Exception e) {
log.error("getQuotaSpecified error retrive a quota for this identifier:{} error:{}",identifier, e);
return null;
}finally{
em.close();
}
return quotaToReturn;
}
/**
* Update a specify quota
* @param quotaId
* @return Quota
*/
/*
public Quota updateQuota(long quotaId, String context,
String identifier, ManagerType managerType, TimeInterval timeInterval, Double quotaValue) {
EntityManager em = emFactory.createEntityManager();
em.getTransaction().begin();
try{
Quota quota = em.find(Quota.class, quotaId);
quota.setContext(context);
quota.setIdentifier(identifier);
quota.setManagerType(managerType);
quota.setTimeInterval(timeInterval);
quota.setQuotaValue(quotaValue);
em.getTransaction().commit();
return em.find(Quota.class, quotaId);
}finally{
em.close();
}
}
*/
}

View File

@ -0,0 +1,184 @@
package org.gcube.resource.management.quota.manager.persistence;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import lombok.extern.slf4j.Slf4j;
import org.gcube.resource.management.quota.library.quotalist.ServicePackage;
import org.gcube.resource.management.quota.library.quotalist.ServicePackageDetail;
import org.gcube.resource.management.quota.manager.persistence.entities.ServicePackageDetailEntity;
import org.gcube.resource.management.quota.manager.persistence.entities.ServicePackageManagerEntity;
import org.gcuberesource.management.quota.manager.service.exception.NotFoundQuotaPackageExecption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* QuotaPackageDBPersistence
*
* @author Alessandro Pieve (alessandro.pieve@isti.cnr.it)
*
*/
@Singleton
@Slf4j
public class QuotaPackageDBPersistence {
private static QuotaPackageDBPersistence instance;
private QuotaPackageDBPersistence(){}
public static synchronized QuotaPackageDBPersistence getInstance()
{
if (instance == null)
instance = new QuotaPackageDBPersistence();
return instance;
}
private static Logger log = LoggerFactory.getLogger(QuotaPackageDBPersistence.class);
protected EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("quota_persistence");
/**
* Add Quota to persist
* @param quote
*/
public void addPackage(ServicePackage servicePackages) {
EntityManager em = emFactory.createEntityManager();
try{
ServicePackageManagerEntity servicePackageManager= new ServicePackageManagerEntity(servicePackages.getName());
em.getTransaction().begin();
em.persist(servicePackageManager);
em.flush();
for (ServicePackageDetail servicePackageDetail:servicePackages.getServicesPackageDetail()){
ServicePackageDetailEntity servicePackageDetailEntity=new ServicePackageDetailEntity(servicePackageManager,servicePackageDetail.getContent());
servicePackageDetailEntity.setServicePackage(servicePackageManager);
em.persist(servicePackageDetailEntity);
}
em.getTransaction().commit();
}catch (Exception e) {
log.error("addPackage except:{}",e);
em.getTransaction().rollback();
}
finally{
em.close();
}
}
/**
* Get list package
* @return List<Quota>
* @throws NotFoundQuotaPackageExecption
*/
public List<ServicePackage> getPackages() throws NotFoundQuotaPackageExecption {
List<ServicePackage> packagesToReturn = new ArrayList<ServicePackage>();
EntityManager em = emFactory.createEntityManager();
try{
TypedQuery<ServicePackageManagerEntity> query = em.createNamedQuery("ServicePackage.all", ServicePackageManagerEntity.class);
if (query.getResultList().size()>0){
for (ServicePackageManagerEntity serEntity: query.getResultList()){
List<ServicePackageDetail> servicePackageDetaiListl = new ArrayList<ServicePackageDetail>();
for(ServicePackageDetailEntity serDetEntity: serEntity.getListdetail()){
ServicePackageDetail servicePackageDetail= new ServicePackageDetail(serDetEntity.getServicePackage().getId(),
serDetEntity.getContent());
servicePackageDetail.setId(serDetEntity.getId());
servicePackageDetaiListl.add(servicePackageDetail);
}
ServicePackage servicePackage =new ServicePackage(serEntity.getName(), servicePackageDetaiListl);
servicePackage.setId(serEntity.getId());
packagesToReturn.add(servicePackage);
}
}
else{
throw new NotFoundQuotaPackageExecption("No packages found");
}
}finally{
em.close();
}
return packagesToReturn;
}
/**
* Remove package to persist
* @param servicePackageId
*/
public void removePackage(long servicePackageId) {
EntityManager em = emFactory.createEntityManager();
try{
em.getTransaction().begin();
ServicePackageManagerEntity entity = em.find(ServicePackageManagerEntity.class, servicePackageId);
if (entity!= null){
em.remove(entity);
}
else{
log.warn("package with id {} not found", servicePackageId);
}
em.getTransaction().commit();
}catch (Exception e) {
log.error("error removing package with id {}", servicePackageId);
em.close();
}
}
/**
* Remove package detail to persist
* @param servicePackageId
*/
public void removePackageDetail(long servicePackageDetailId) {
EntityManager em = emFactory.createEntityManager();
try{
em.getTransaction().begin();
ServicePackageDetailEntity entity=em.find(ServicePackageDetailEntity.class,servicePackageDetailId);
if (entity!= null){
em.remove(entity);
em.flush();
}
else{
log.warn("package detail with id {} not found", servicePackageDetailId);
}
em.getTransaction().commit();
}catch (Exception e) {
log.error("error removing package detail with id {}", servicePackageDetailId);
em.close();
}
}
public ServicePackage getPackage(long servicepackage_id) throws NotFoundQuotaPackageExecption {
EntityManager em = emFactory.createEntityManager();
ServicePackage servicePackage=null;
try{
TypedQuery<ServicePackageManagerEntity> query = em.createNamedQuery("ServicePackage.getById", ServicePackageManagerEntity.class);
query.setParameter("id", servicepackage_id);
if (query.getResultList().size()>0){
for (ServicePackageManagerEntity serEntity: query.getResultList()){
List<ServicePackageDetail> servicePackageDetaiListl = new ArrayList<ServicePackageDetail>();
for(ServicePackageDetailEntity serDetEntity: serEntity.getListdetail()){
ServicePackageDetail servicePackageDetail= new ServicePackageDetail(serDetEntity.getServicePackage().getId(),
serDetEntity.getContent());
servicePackageDetail.setId(serDetEntity.getId());
servicePackageDetaiListl.add(servicePackageDetail);
}
servicePackage =new ServicePackage(serEntity.getName(), servicePackageDetaiListl);
servicePackage.setId(serEntity.getId());
}
}
else{
throw new NotFoundQuotaPackageExecption("No packages found");
}
}finally{
em.close();
}
return servicePackage;
}
}

View File

@ -0,0 +1,14 @@
package org.gcube.resource.management.quota.manager.persistence.entities;
/**
* EntityConstants
*
* @author Alessandro Pieve (alessandro.pieve@isti.cnr.it)
*
*/
public class EntityConstants {
public static final String STORAGE_QUOTA="STORAGE";
public static final String SERVICE_QUOTA="SERVICE";
}

View File

@ -0,0 +1,157 @@
package org.gcube.resource.management.quota.manager.persistence.entities;
import java.util.Calendar;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.gcube.resource.management.quota.library.quotalist.CallerType;
import org.gcube.resource.management.quota.library.quotalist.TimeInterval;
/**
* QuotaEntity
* composed:
* id: identifier quota
* context: for specificy quota
* identifier: identifiy name of user/service/role
* callerType: caller type:USER(1),ROLE(2),SERVICE(3);
* managerType: STORAGE,SERVICE,PORTLET
* timeInterval: DAILY,MONTHLY,YEARLY
* quotaValue: value of quota
* creationTime: time of insert into db and creation Quota
* lastUpdateTime: time last update into db
*
* @author Alessandro Pieve (alessandro.pieve@isti.cnr.it)
*/
@Entity
@Inheritance
@DiscriminatorColumn(name="QuotaType")
@Table(name="Quota")
@NamedQueries({
@NamedQuery(name="Quota.all", query="SELECT quota FROM QuotaEntity quota WHERE "
+ " quota.context=:context"),
@NamedQuery(name="Quota.getByIdentifier", query="SELECT quota FROM QuotaEntity quota WHERE "
+ " quota.identifier=:identifier"),
@NamedQuery(name="Quota.getSpecified", query="SELECT quota FROM QuotaEntity quota WHERE "
+ "quota.identifier=:identifier and "
+ "quota.context=:context and "
+ "quota.quotaType=:quotaType and "
+ "quota.timeInterval=:timeInterval"
)
})
public abstract class QuotaEntity {
@Column
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected long id;
@Column(nullable=true)
protected String context;
@Column(name="QuotaType")
private String quotaType;
@Column(nullable=true)
protected String identifier;
@Column(nullable=true)
protected CallerType callerType;
@Column(nullable=true)
protected TimeInterval timeInterval;
@Column(nullable= true)
protected Double quotaValue;
@Temporal(TemporalType.TIMESTAMP)
@Column(nullable= true)
protected Calendar creationTime;
@Temporal(TemporalType.TIMESTAMP)
@Column(nullable= true)
protected Calendar lastUpdateTime;
/*
@Column(nullable= true)
protected Double quotaUsageValue;
*/
protected QuotaEntity() {}
public QuotaEntity(String context ,String quotaType, String identifier,CallerType callerType ,TimeInterval timeInterval,Double quotaValue) {
super();
this.quotaType=quotaType;
this.context=context;
this.callerType=callerType;
this.identifier=identifier;
//this.managerType=managerType;
this.timeInterval=timeInterval;
this.quotaValue=quotaValue;
Calendar now = Calendar.getInstance();
this.creationTime = now;
this.lastUpdateTime = now;
}
public long getId() {
return id;
}
public String getContext() {
return context;
}
public String getIdentifier() {
return identifier;
}
public CallerType getCallerType() {
return callerType;
}
public TimeInterval getTimeInterval() {
return timeInterval;
}
public Double getQuotaValue() {
return quotaValue;
}
public Calendar getLastUpdateTime() {
return lastUpdateTime;
}
public void setLastUpdateTime(Calendar lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
public Calendar getCreationTime() {
return creationTime;
}
public String getQuotaType() {
return quotaType;
}
/*
public Double getQuotaUsageValue(){
return quotaUsageValue;
}
public void setQuotaUsageValue(Double usageValue){
this.quotaUsageValue=usageValue;
}
*/
}

View File

@ -0,0 +1,76 @@
package org.gcube.resource.management.quota.manager.persistence.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* ServicePackageDetailEntity
* composed:
* id: identifier db
* servicepackage: id service package master
* content: name service package
*
* @author Alessandro Pieve (alessandro.pieve@isti.cnr.it)
*/
@Entity
@Inheritance
@Table(name="ServicePackageDetail")
public class ServicePackageDetailEntity {
@Column
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected long id;
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="SERVICE_PACKAGE_ID", updatable = true,insertable = true )
private ServicePackageManagerEntity servicepackage;
@Column(nullable=false)
protected String content;
protected ServicePackageDetailEntity() {}
public ServicePackageDetailEntity(ServicePackageManagerEntity servicepackage, String content) {
super();
this.servicepackage=servicepackage;
this.content=content;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public ServicePackageManagerEntity getServicePackage() {
return servicepackage;
}
public void setServicePackage(ServicePackageManagerEntity servicepackage) {
this.servicepackage = servicepackage;
if (!servicepackage.getListdetail().contains(this)) {
servicepackage.getListdetail().add(this);
}
}
}

View File

@ -0,0 +1,99 @@
package org.gcube.resource.management.quota.manager.persistence.entities;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* ServicePackageManagerEntity
* composed:
* id: identifier db
* name: name of package
* listdetail: list detail of service contain this package
*
* @author Alessandro Pieve (alessandro.pieve@isti.cnr.it)
*/
@Entity
@Inheritance
@NamedQueries({
@NamedQuery(name="ServicePackage.all", query="SELECT servicePackagesManager FROM ServicePackageManagerEntity servicePackagesManager"),
@NamedQuery(name="ServicePackage.getById", query="SELECT servicePackagesManager FROM ServicePackageManagerEntity servicePackagesManager WHERE "
+ " servicePackagesManager.id=:id")
})
@Table(name="ServicePackage")
public class ServicePackageManagerEntity {
@Column (name="PACK_ID")
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected long id;
@Column(unique=true)
protected String name;
@OneToMany(cascade = {CascadeType.ALL},mappedBy="servicepackage")
private List<ServicePackageDetailEntity> listdetail;
public void addPackageDetail(ServicePackageDetailEntity listdetail) {
this.listdetail.add(listdetail);
if (listdetail.getServicePackage() != this) {
listdetail.setServicePackage(this);
}
}
public ServicePackageManagerEntity(){
listdetail = new ArrayList<ServicePackageDetailEntity>();
}
public ServicePackageManagerEntity(String name) {
super();
this.name = name;
}
public ServicePackageManagerEntity(String name, List<ServicePackageDetailEntity> listdetail) {
super();
this.name = name;
this.listdetail = listdetail;
}
// protected ServicePackageManagerEntity() {}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<ServicePackageDetailEntity> getListdetail() {
return listdetail;
}
public void setListdetail(List<ServicePackageDetailEntity> listdetail) {
this.listdetail = listdetail;
}
}

View File

@ -0,0 +1,83 @@
package org.gcube.resource.management.quota.manager.persistence.entities;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import org.gcube.resource.management.quota.library.quotalist.AccessType;
import org.gcube.resource.management.quota.library.quotalist.CallerType;
import org.gcube.resource.management.quota.library.quotalist.TimeInterval;
/**
* ServiceQuotaEntity
* composed:
* id: identifier quota
* context: for specificy quota
* identifier: identifiy name of user/service/role
* callerType: caller type:USER(1),ROLE(2),SERVICE(3);
* managerType: STORAGE,SERVICE,PORTLET
* timeInterval: DAILY,MONTHLY,YEARLY
* quotaValue: value of quota
* creationTime: time of insert into db and creation Quota
* lastUpdateTime: time last update into db
*
* @author Alessandro Pieve (alessandro.pieve@isti.cnr.it)
*/
@Entity
@DiscriminatorValue(EntityConstants.SERVICE_QUOTA)
public class ServiceQuotaEntity extends QuotaEntity {
protected ServiceQuotaEntity() {
super();
}
@Column(nullable=true)
private AccessType accessType;
@Column(nullable=true)
private String servicePackageId;
public ServiceQuotaEntity(String context ,String identifier,CallerType callerType ,String servicePackageId, TimeInterval timeInterval,Double quotaValue,AccessType accessType) {
super(context,EntityConstants.SERVICE_QUOTA,identifier,callerType,timeInterval,quotaValue);
this.accessType=accessType;
this.servicePackageId=servicePackageId;
}
public ServiceQuotaEntity(String context ,String identifier,CallerType callerType , TimeInterval timeInterval,Double quotaValue) {
super(context,EntityConstants.SERVICE_QUOTA,identifier,callerType,timeInterval,quotaValue);
}
public AccessType getAccessType() {
return accessType;
}
public void setAccessType(AccessType accessType) {
this.accessType = accessType;
}
public String getServicePackageId() {
return servicePackageId;
}
public void setServicePackageId(String servicePackageId) {
this.servicePackageId = servicePackageId;
}
@Override
public String toString() {
return "ServiceQuotaEntity [accessType=" + accessType
+ ", servicePackageId=" + servicePackageId + ", id=" + id
+ ", context=" + context + ", identifier=" + identifier
+ ", callerType=" + callerType + ", timeInterval="
+ timeInterval + ", quotaValue=" + quotaValue
+ ", creationTime=" + creationTime + ", lastUpdateTime="
+ lastUpdateTime + "]";
}
}

View File

@ -0,0 +1,52 @@
package org.gcube.resource.management.quota.manager.persistence.entities;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import org.gcube.resource.management.quota.library.quotalist.CallerType;
import org.gcube.resource.management.quota.library.quotalist.TimeInterval;
/**
* StorageQuotaEntity
* composed:
* id: identifier quota
* context: for specificy quota
* identifier: identifiy name of user/service/role
* callerType: caller type:USER(1),ROLE(2),SERVICE(3);
* managerType: STORAGE,SERVICE,PORTLET
* timeInterval: DAILY,MONTHLY,YEARLY
* quotaValue: value of quota
* creationTime: time of insert into db and creation Quota
* lastUpdateTime: time last update into db
*
* @author Alessandro Pieve (alessandro.pieve@isti.cnr.it)
*/
@Entity
@DiscriminatorValue(EntityConstants.STORAGE_QUOTA)
public class StorageQuotaEntity extends QuotaEntity {
protected StorageQuotaEntity() {
super();
}
public StorageQuotaEntity(String context ,String identifier,CallerType callerType ,TimeInterval timeInterval,Double quotaValue) {
super(context,EntityConstants.STORAGE_QUOTA,identifier,callerType,timeInterval,quotaValue);
}
@Override
public String toString() {
return "StorageQuotaEntity [id=" + id + ", context=" + context
+ ", identifier=" + identifier + ", callerType=" + callerType
+ ", timeInterval=" + timeInterval + ", quotaValue="
+ quotaValue + ", creationTime=" + creationTime
+ ", lastUpdateTime=" + lastUpdateTime + "]";
}
}

View File

@ -0,0 +1,38 @@
package org.gcube.resource.management.quota.manager.persistence.entities.converters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
/**
* StringListConverter
*
* @author Alessandro Pieve (alessandro.pieve@isti.cnr.it)
*
*/
@Converter
public class StringListConverter implements AttributeConverter<List<String>, String>{
@Override
public String convertToDatabaseColumn(List<String> list) {
if (list!=null && list.size()>0){
StringBuilder builder = new StringBuilder();
for (String value: list)
builder.append(value).append(",||,");
return builder.substring(builder.length()-4, builder.length());
} else return "";
}
@Override
public List<String> convertToEntityAttribute(String dbEntry) {
if (dbEntry!=null && !dbEntry.isEmpty()){
return Arrays.asList(dbEntry.split(",\\|\\|,"));
}
else return new ArrayList<String>(0);
}
}

View File

@ -0,0 +1,108 @@
package org.gcube.resource.management.quota.manager.service;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.resource.management.quota.library.QuotaList;
import org.gcube.resource.management.quota.library.quotalist.Quota;
import org.gcube.resource.management.quota.manager.check.MyAppManager;
import org.gcube.resource.management.quota.manager.persistence.QuotaDBPersistence;
import org.gcube.smartgears.ApplicationManagerProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Manage quota into persistence
* @author Alessandro Pieve (alessandro.pieve@isti.cnr.it)
*
*/
@Path("quotaManager")
public class QuotaManager {
private static Logger log = LoggerFactory.getLogger(QuotaManager.class);
QuotaDBPersistence quotaPersistence;
private MyAppManager appManager = (MyAppManager)ApplicationManagerProvider.get(MyAppManager.class);
@POST
@Consumes(MediaType.TEXT_XML)
@Path("/insert")
public Response insertQuote(QuotaList quote) {
try{
log.info("insert quote init");
log.info("insert quote: {}", quote.getQuotaList().toString());
quotaPersistence =appManager.getQuotaDbPersistence();
quotaPersistence.addQuote(quote.getQuotaList());
}catch(Exception e){
log.error("error insert quote",e);
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("Error insert quote: "+e.getMessage()).type(MediaType.TEXT_PLAIN).build());
}
return Response.ok().build();
}
@GET
@Path("/detail/{quota_id}")
@Produces(MediaType.TEXT_XML)
public Quota getDetailQuota(@NotNull @PathParam("quota_id") long quotaId) {
try{
log.info("retrieving detail quote {}",quotaId);
quotaPersistence =appManager.getQuotaDbPersistence();
Quota quota =quotaPersistence.getQuota(quotaId);
log.info("quota {}",quota);
return quota;
}catch(Exception e){
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("Error : "+e.getMessage()).type(MediaType.TEXT_PLAIN).build());
}
}
@DELETE
@Path("/remove/{quota_id}")
public Response removeQuota(@Null @PathParam("quota_id") long quotaId) {
try{
log.info("removing quota with id {}", quotaId);
quotaPersistence =appManager.getQuotaDbPersistence();
quotaPersistence.removeQuota(quotaId);
}catch(Exception e){
log.error("error removing quota", e);
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("Error removing quota: "+e.getMessage()).type(MediaType.TEXT_PLAIN).build());
}
return Response.ok().build();
}
@GET
@Produces(MediaType.APPLICATION_XML)
@Path("/list")
public QuotaList getQuotePerContext() {
String context = ScopeProvider.instance.get();
try{
log.info("retrieving quote in context {}", context);
quotaPersistence =appManager.getQuotaDbPersistence();
return new QuotaList(quotaPersistence.getQuote(context));
}catch(Exception e){
log.error("error retrieving quote per context {}", context, e);
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("Error retrieving quote: "+e.getMessage()).type(MediaType.TEXT_PLAIN).build());
}
}
}

View File

@ -0,0 +1,154 @@
package org.gcube.resource.management.quota.manager.service;
import javax.ws.rs.Path;
/***
*
* QuotaPackageManager
* Service for manager package (insert,list, and remove)
*
* @author alessandro.pieve@isti.cnr.it
*
*/
@Path("quotaPackageManager")
public class QuotaPackageManager {
/**
* insert a package
* quotaPackageManager/insert
* content-type:text/xml
* Request Method: POST
*<servicepackage>
* <name>Pacchetto 2</name>
* <servicesPackagesDetail>
* <content>Nome servizio 2-1</content>
* </servicesPackagesDetail>
* <servicesPackagesDetail>
* <content>Nome servizio 2-2</content>
* </servicesPackagesDetail>
*</servicepackage>
* @param servicePackages
* @return
*/
/*
@POST
@Consumes(MediaType.TEXT_XML)
@Path("/insert/")
public Response insertPackage(ServicePackage servicePackages) {
try{
log.info("insert service packages: {}", servicePackages.getServicePackagesAsString());
quotaPackagePersistence.addPackage(servicePackages);
}catch(Exception e){
log.error("error service packages",e);
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("Error insert service packages: "+e.getMessage()).type(MediaType.TEXT_PLAIN).build());
}
return Response.ok().build();
}
*/
/**
* list of package
* example:
* <servicepackages>
* <servicepackage>
* <id>4</id>
* <name>Pacchetto 1</name>
* <servicesPackagesDetail>
* <id>9</id>
* <idServicesPackage>4</idServicesPackage>
* <content>Nome servizio 2</content>
* </servicesPackagesDetail>
* <servicesPackagesDetail>
* <id>10</id>
* <idServicesPackage>4</idServicesPackage>
* <content>Nome servizio 1</content>
* </servicesPackagesDetail>
* </servicepackage>
*</servicepackages>
* @return
*/
/*
@GET
@Produces(MediaType.APPLICATION_XML)
@Path("/")
public ServicePackages getPackages() {
try{
log.info("retrieving packages {}");
return new ServicePackages(quotaPackagePersistence.getPackages());
}catch(Exception e){
log.error("error retrieving list packages ", e);
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("Error retrieving list packages: "+e.getMessage()).type(MediaType.TEXT_PLAIN).build());
}
}
*/
/*
@GET
@Path("/detail/{servicepackage_id}")
@Produces(MediaType.TEXT_XML)
public ServicePackage getDetailPackage(@NotNull @PathParam("servicepackage_id") long servicepackage_id) {
try{
log.info("retrieving detail package {}",servicepackage_id);
ServicePackage servicePackage = quotaPackagePersistence.getPackage(servicepackage_id);
log.info("ServicePackage getDetailPackage:{}",servicePackage);
return servicePackage;
}catch(Exception e){
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("Error : "+e.getMessage()).type(MediaType.TEXT_PLAIN).build());
}
}
*/
/**
* Remove a package
* @param servicepackagedetailId
* @return
*/
/*
@DELETE
@Path("/remove/{servicepackage_id}")
public Response removePackage(@Null @PathParam("servicepackage_id") long servicepackageId) {
try{
log.info("removing Package with id {}", servicepackageId);
quotaPackagePersistence.removePackage(servicepackageId);
}catch(Exception e){
log.error("error removing package", e);
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("Error removing package: "+e.getMessage()).type(MediaType.TEXT_PLAIN).build());
}
return Response.ok().build();
}
*/
/**
* Remove a detail package
* @param servicepackagedetailId
* @return
*/
/*
@DELETE
@Path("/removedetail/{servicepackagedetail_id}")
public Response removePackageDetail(@Null @PathParam("servicepackagedetail_id") long servicepackagedetailId) {
try{
log.info("removing Package detail with id {}", servicepackagedetailId);
quotaPackagePersistence.removePackageDetail(servicepackagedetailId);
}catch(Exception e){
log.error("error removing package detail", e);
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("Error removing package detail: "+e.getMessage()).type(MediaType.TEXT_PLAIN).build());
}
return Response.ok().build();
}
*/
}

View File

@ -0,0 +1,16 @@
package org.gcube.resource.management.quota.manager.service;
import javax.ws.rs.ApplicationPath;
import org.glassfish.jersey.server.ResourceConfig;
/**
* StringListConverter
*
* @author Alessandro Pieve (alessandro.pieve@isti.cnr.it)
*
*/
@ApplicationPath("/gcube/service/")
public class QuotaService extends ResourceConfig {
public QuotaService(){
packages("org.gcube.resource.management.quota.manager.service");
}
}

View File

@ -0,0 +1,60 @@
package org.gcube.resource.management.quota.manager.service;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.resource.management.quota.library.quotalist.TimeInterval;
import org.gcube.resource.management.quota.library.status.QuotaStorageStatus;
import org.gcube.resource.management.quota.manager.check.MyAppManager;
import org.gcube.resource.management.quota.manager.check.QuotaUsage;
import org.gcube.smartgears.ApplicationManagerProvider;
import org.gcube.smartgears.annotations.ManagedBy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Query quota Status
* @author Alessandro Pieve (alessandro.pieve@isti.cnr.it)
*
*/
@Path("quotaStatus")
@ManagedBy(MyAppManager.class)
public class QuotaStatus {
private static Logger log = LoggerFactory.getLogger(QuotaStatus.class);
private MyAppManager appManager = (MyAppManager)ApplicationManagerProvider.get(MyAppManager.class);
//http://.....quota-manager/gcube/service/quotaStatus/detail/?timeinterval=MONTHLY&gcube-token=...
@GET
@Path("/detail/")
@Produces(MediaType.APPLICATION_XML)
public QuotaStorageStatus getQuotaStorageStatus(@QueryParam("timeinterval") String timeinterval) {
Caller caller=AuthorizationProvider.instance.get();
String identifier = caller.getClient().getId();
QuotaUsage queryUsage =appManager.getQuotaUsage();
QuotaStorageStatus quotaStorageStatus;
try{
log.info("retrieving quote for identifier:{} and time:{}",identifier,timeinterval);
quotaStorageStatus =queryUsage.selectStorageQuota(identifier,TimeInterval.valueOf(timeinterval) );
}catch(Exception e){
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("Error : "+e.getMessage()).type(MediaType.TEXT_PLAIN).build());
}
return quotaStorageStatus;
}
}

View File

@ -0,0 +1,28 @@
package org.gcube.resource.management.quota.manager.util;
/**
* Constant use for schedule a check quota
* @author pieve
*
*/
public class Constants {
public static final Long TIME_SCHEDULE_CHECK = 180*1000L;
public static final Long DELAY_SCHEDULE_CHECK = (long) (30*1000);
// IS Resource
public static final String QUOTA_NAME = "QuotaDefault";
public static final String QUOTA_CATEGORY = "Quota";
//File properties
public static final String FILE_PROPERTIES_QUOTA="/tmp/quota.xml";
//Limit msg for quota
public static final Integer LIMIT_MSG_QUOTA_PERC_USAGE_1=90;
public static final Integer LIMIT_MSG_QUOTA_PERC_USAGE_2=95;
}

View File

@ -0,0 +1,17 @@
package org.gcube.resource.management.quota.manager.util;
public class ConstantsDb {
//CONNECTION DB
//public static final String DB_DRIVER_TEST = "org.h2.Driver";
//
//public static final String DB_CONNECTION_TEST = "jdbc:h2:~/DbQuota;";
//public static final String DB_USER = "sa";
//public static final String DB_PASSWORD = "";
public static final String DB_DRIVER = "org.postgresql.Driver";
public static final String SEPARATOR="_";
public static final String DATABASE_PREFIX="quotausage";
public static final String DATABASE_TYPE_STORAGE="storage";
public static final String DATABASE_TYPE_SERVICE="service";
public static final String DATABASE_PERIOD_TOTAL="total";
}

View File

@ -0,0 +1,255 @@
package org.gcube.resource.management.quota.manager.util;
import static org.gcube.resources.discovery.icclient.ICFactory.clientFor;
import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
import java.security.Key;
import java.util.List;
import java.util.Map;
import org.gcube.common.encryption.StringEncrypter;
import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.Property;
import org.gcube.common.resources.gcore.utils.Group;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DiscoveryConfiguration {
private String databasePath = null;
private String usernameDb = null;
private String pwdnameDb = null;
private String dbname=null;
private Boolean notifierUser=false;
private Boolean notifierAdmin=false;
private Integer refreshTimeQuota=0;
private String textQuotaUserWarning="Hi {identifier}, your storage space is almost full, Your quota occupation is {percent} %, you are using {quotaUsage} out of {quotaAssigned} available.Please be adviced.";
private String textQuotaUserWarningSubject="WARNING Your storage space is about to exceed quota capacity";
private String textQuotaUserExceedSubject="ATTENTION Your storage space exceeds the assigned quota capacity";
private String textQuotaUserExceed="Hi {identifier}, your storage space is full, Your quota occupation is {percent}% , you are using {quotaUsage} out of {quotaAssigned} available. Please free up some space.";
private String textQuotaAdminExceedSubject="INFO List User quota Exceed";
private String textQuotaAdminExceed="Dear, now this user have a quota exceed: {listuser}";
private String textQuotaUserReset="Hi {identifier}, Your quota occupation decreased and is now {percent}%, you are using {quotaUsage}, out of {quotaAssigned} available. Good job!";
private String textQuotaUserResetSubject="INFO Your storage space is now sufficiently below the quota capacity";
private String roleNotifier="Administrator";
private static Logger logger = LoggerFactory.getLogger(DiscoveryConfiguration.class);
private final static String RUNTIME_RESOURCE_NAME = "Persistence";
private final static String CATEGORY = "Quota";
private final static String ACCESS_POINT_NAME="postgresql Server";
private final static String DB_NAME="dbname";
private final static String NOTIFIER_USER="notifierUser";
private final static String NOTIFIER_ADMINISTRATOR="notifierAdministrator";
private final static String REFRESH_TIME_QUOTA="refreshTimeQuota";
private final static String TEXT_QUOTA_USER_WARNING_SUBJECT="textQuotaUserWarningSubject";
private final static String TEXT_QUOTA_USER_WARNING="textQuotaUserWarning";
private final static String TEXT_QUOTA_USER_EXCEED_SUBJECT="textQuotaUserExceedSubject";
private final static String TEXT_QUOTA_USER_EXCEED="textQuotaUserExceed";
private final static String TEXT_QUOTA_ADMIN_EXCEED_SUBJECT="textQuotaAdminExceedSubject";
private final static String TEXT_QUOTA_ADMIN_EXCEED="textQuotaAdminExceed";
private final static String TEXT_QUOTA_USER_RESET_SUBJECT="textQuotaUserResetSubject";
private final static String TEXT_QUOTA_USER_RESET_EXCEED="textQuotaUserReset";
private final static String ROLE_NOTIFIER="roleNotifier";
public DiscoveryConfiguration(String context){
if(context == null || context.isEmpty())
throw new IllegalArgumentException("A valid context is needed to discover the service");
logger.debug("find a resources from service end point in context:{}",context);
String oldContext = ScopeProvider.instance.get();
logger.debug("find a resources from service end point oldContext:{}",oldContext);
ScopeProvider.instance.set(context);
try{
ServiceEndpoint resources =getServiceEndpoint(context);
logger.debug("find a resources from service end point");
setValues(resources);
}catch(Exception e){
logger.error("Unable to retrieve such service endpoint information!", e);
}finally{
if(oldContext != null && !oldContext.equals(context))
ScopeProvider.instance.set(oldContext);
}
logger.info("Found base path " + databasePath + " for the service");
}
/**
* Retrieve endpoints information from IS for DB
* @return list of endpoints
* @throws Exception
*/
protected ServiceEndpoint getServiceEndpoint(String context){
SimpleQuery query = queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Name/text() eq '"+ RUNTIME_RESOURCE_NAME +"'");
query.addCondition("$resource/Profile/Category/text() eq '"+ CATEGORY +"'");
query.setResult("$resource");
logger.debug("DiscoveryConfiguration query:{}",query.toString());
DiscoveryClient<ServiceEndpoint> client = clientFor(ServiceEndpoint.class);
List<ServiceEndpoint> serviceEndpoints = client.submit(query);
return serviceEndpoints.get(0);
}
protected void setValues(ServiceEndpoint serviceEndpoint) throws Exception{
Group<AccessPoint> accessPoints = serviceEndpoint.profile().accessPoints();
for(AccessPoint accessPoint : accessPoints){
logger.debug("accessPoint:{}",accessPoint.name());
if(accessPoint.name().compareTo(ACCESS_POINT_NAME)==0){
databasePath=accessPoint.address();
usernameDb=accessPoint.username();
pwdnameDb=decrypt(accessPoint.password());
Map<String, Property> propertyMap = accessPoint.propertyMap();
for(String key : propertyMap.keySet()){
Property property = propertyMap.get(key);
String value = property.value();
if(property.isEncrypted()){
value = decrypt(value);
}
switch (key) {
case DB_NAME:
dbname=value;
break;
case NOTIFIER_USER:
notifierUser=Boolean.valueOf(value);
break;
case NOTIFIER_ADMINISTRATOR:
notifierAdmin=Boolean.valueOf(value);
break;
case REFRESH_TIME_QUOTA:
refreshTimeQuota=Integer.valueOf(value);
break;
case TEXT_QUOTA_USER_WARNING_SUBJECT:
textQuotaUserWarningSubject=value;
break;
case TEXT_QUOTA_USER_WARNING:
textQuotaUserWarning=value;
break;
case TEXT_QUOTA_USER_EXCEED_SUBJECT:
textQuotaUserExceedSubject=value;
break;
case TEXT_QUOTA_USER_EXCEED:
textQuotaUserExceed=value;
break;
case TEXT_QUOTA_ADMIN_EXCEED_SUBJECT:
textQuotaAdminExceedSubject=value;
break;
case TEXT_QUOTA_ADMIN_EXCEED:
textQuotaAdminExceed=value;
break;
case TEXT_QUOTA_USER_RESET_SUBJECT:
textQuotaUserResetSubject=value;
break;
case TEXT_QUOTA_USER_RESET_EXCEED:
textQuotaUserReset=value;
break;
case ROLE_NOTIFIER:
roleNotifier=value;
break;
}
}
}
}
}
private static String decrypt(String encrypted, Key... key) throws Exception {
return StringEncrypter.getEncrypter().decrypt(encrypted);
}
@Override
public String toString() {
return "DiscoveryConfiguration [databasePath=" + databasePath
+ ", usernameDb=" + usernameDb + ", pwdnameDb=" + pwdnameDb
+ ", dbname=" + dbname + ", notifierUser=" + notifierUser
+ ", notifierAdmin=" + notifierAdmin + ", refreshTimeQuota="
+ refreshTimeQuota + "]";
}
public String getDatabasePath() {
return databasePath;
}
public String getUsernameDb() {
return usernameDb;
}
public String getPwdnameDb() {
return pwdnameDb;
}
public String getDbname() {
return dbname;
}
public Boolean getNotifierUser() {
return notifierUser;
}
public Boolean getNotifierAdmin() {
return notifierAdmin;
}
public Integer getRefreshTimeQuota() {
return refreshTimeQuota;
}
public String getTextQuotaUserWarningSubject() {
return textQuotaUserWarningSubject;
}
public String getTextQuotaUserWarning() {
return textQuotaUserWarning;
}
public String getTextQuotaUserExceedSubject() {
return textQuotaUserExceedSubject;
}
public String getTextQuotaUserExceed() {
return textQuotaUserExceed;
}
public String getTextQuotaAdminExceedSubject() {
return textQuotaAdminExceedSubject;
}
public String getTextQuotaAdminExceed() {
return textQuotaAdminExceed;
}
public String getTextQuotaUserReset() {
return textQuotaUserReset;
}
public String getTextQuotaUserResetSubject() {
return textQuotaUserResetSubject;
}
public String getRoleNotifier() {
return roleNotifier;
}
}

View File

@ -0,0 +1,110 @@
package org.gcube.resource.management.quota.manager.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
/**
* Retrieves the list user form the base url of the social-networking service in the scope provided
* @author Alessandro Pieve at ISTI-CNR
* (alessandro.pieve@isti.cnr.it)
*/
public class DiscoveryListUser {
private static Logger log = LoggerFactory.getLogger(DiscoveryListUser.class);
private final static String NAME_SERVICE_ALL_USERNAMES = "2/users/get-all-usernames?gcube-token";
private List<String> listUser = null;
public DiscoveryListUser(String context) {
String token =SecurityTokenProvider.instance.get();
log.debug("scope:{} ,tokend:{}",context,token);
DiscoveryService discoveryList= new DiscoveryService(context);
String urlService=discoveryList.getBasePath()+NAME_SERVICE_ALL_USERNAMES+"="+token;
log.debug("service DiscoveryServiceListUser:"+urlService);
String data = getJSON(urlService);
log.debug("data read:{}",data);
ListUser msg = new Gson().fromJson(data, ListUser.class);
//TODO for debug limit a list user:
//listUser=msg.getResult();
//REMOVE TODO
listUser=new ArrayList<String>();
listUser.add("lucio.lelii");
listUser.add("alessandro.pieve");
listUser.add("scarponi");
listUser.add("giancarlo.panichi");
listUser.add("costantino.perciante");
listUser.add("luca.frosini");
listUser.add("roberto.cirillo");
}
/**
* Get the base path of the social networking service
* @return
*/
public List<String> getListUser() {
return listUser;
}
/**
*
* @param url
* @return String response content
*/
public String getJSON(String url) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setInstanceFollowRedirects(true);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
log.error("MalformedURLException:{}",ex);
} catch (IOException ex) {
log.error("IOException:{}",ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
log.error("Exception:{}",ex);
}
}
}
return null;
}
}

View File

@ -0,0 +1,108 @@
package org.gcube.resource.management.quota.manager.util;
import static org.gcube.resources.discovery.icclient.ICFactory.clientFor;
import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
import java.util.Iterator;
import java.util.List;
import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Retrieves the base url of the social-networking service in the scope provided
* @author Costantino Perciante at ISTI-CNR
* (costantino.perciante@isti.cnr.it)
*/
public class DiscoveryService {
private String basePath = null;
private static Logger logger = LoggerFactory.getLogger(DiscoveryService.class);
private final static String RUNTIME_RESOURCE_NAME = "SocialNetworking";
private final static String CATEGORY = "Portal";
//private final static String NAME_SERVICE_ALL_USERNAMES = "2/users/get-all-usernames?gcube-token";
public DiscoveryService(String context){
if(context == null || context.isEmpty())
throw new IllegalArgumentException("A valid context is needed to discover the service");
String oldContext = ScopeProvider.instance.get();
ScopeProvider.instance.set(context);
try{
List<ServiceEndpoint> resources = getConfigurationFromIS();
if (resources.size() == 0){
logger.error("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME +" and Category " + CATEGORY + " in this scope.");
throw new Exception("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME +" and Category " + CATEGORY + " in this scope.");
}
else {
for (ServiceEndpoint res : resources) {
Iterator<AccessPoint> accessPointIterator = res.profile().accessPoints().iterator();
while (accessPointIterator.hasNext()) {
ServiceEndpoint.AccessPoint accessPoint = (ServiceEndpoint.AccessPoint) accessPointIterator
.next();
// get base path
basePath = accessPoint.address();
break;
}
}
}
}catch(Exception e){
logger.error("Unable to retrieve such service endpoint information!", e);
}finally{
if(oldContext != null && !oldContext.equals(context))
ScopeProvider.instance.set(oldContext);
}
//logger.info("Found base path " + basePath + " for the service");
}
/**
* Retrieve endpoints information from IS for DB
* @return list of endpoints for ckan database
* @throws Exception
*/
private List<ServiceEndpoint> getConfigurationFromIS() throws Exception{
SimpleQuery query = queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Name/text() eq '"+ RUNTIME_RESOURCE_NAME +"'");
query.addCondition("$resource/Profile/Category/text() eq '"+ CATEGORY +"'");
DiscoveryClient<ServiceEndpoint> client = clientFor(ServiceEndpoint.class);
List<ServiceEndpoint> toReturn = client.submit(query);
return toReturn;
}
/**
* Get the base path of the social networking service
* @return
*/
public String getBasePath() {
//return basePath+NAME_SERVICE_ALL_USERNAMES;
return basePath;
}
}

View File

@ -0,0 +1,38 @@
package org.gcube.resource.management.quota.manager.util;
import java.util.List;
/**
*
* @author pieve
*
*/
public class ListUser {
/*
"success" : false,
"message" : "String index out of range: 5",
"result" : null
*/
private Boolean success;
private String message;
private List<String> result;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<String> getResult() {
return result;
}
public void setResult(List<String> result) {
this.result = result;
}
}

View File

@ -0,0 +1,52 @@
package org.gcube.resource.management.quota.manager.util;
import java.util.List;
import org.gcube.accounting.analytics.Filter;
import org.gcube.accounting.analytics.TemporalConstraint;
import org.gcube.accounting.analytics.UsageServiceValue;
import org.gcube.accounting.datamodel.AggregatedUsageRecord;
import org.gcube.resource.management.quota.library.quotalist.AccessType;
import org.gcube.resource.management.quota.library.quotalist.CallerType;
public class QuotaUsageServiceValue extends UsageServiceValue{
protected Double dQuota;
protected CallerType callerType;
protected AccessType accessType;
public QuotaUsageServiceValue(){}
public QuotaUsageServiceValue(String context,String identifier,Class<? extends AggregatedUsageRecord<?, ?>> clz,TemporalConstraint temporalConstraint,List<Filter> filters){
super();
this.context=context;
this.filters=filters;
this.clz=clz;
this.temporalConstraint=temporalConstraint;
this.identifier=identifier;
}
public Double getdQuota() {
return dQuota;
}
public void setdQuota(Double dQuota) {
this.dQuota = dQuota;
}
public CallerType getCallerType() {
return callerType;
}
public void setCallerType(CallerType callerType) {
this.callerType = callerType;
}
public AccessType getAccessType() {
return accessType;
}
public void setAccessType(AccessType accessType) {
this.accessType = accessType;
}
}

View File

@ -0,0 +1,31 @@
package org.gcube.resource.management.quota.manager.util;
import org.gcube.accounting.analytics.TemporalConstraint;
import org.gcube.accounting.analytics.UsageStorageValue;
import org.gcube.accounting.datamodel.AggregatedUsageRecord;
public class QuotaUsageStorageValue extends UsageStorageValue{
public QuotaUsageStorageValue(){}
public QuotaUsageStorageValue(String context,String identifier,Class<? extends AggregatedUsageRecord<?, ?>> clz,TemporalConstraint temporalConstraint){
super();
this.context=context;
this.identifier=identifier;
this.clz=clz;
this.temporalConstraint=temporalConstraint;
}
protected Double dQuota;
public Double getdQuota() {
return dQuota;
}
public void setdQuota(Double dQuota) {
this.dQuota = dQuota;
}
}

View File

@ -0,0 +1,52 @@
package org.gcube.resource.management.quota.manager.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import org.gcube.resource.management.quota.library.quotedefault.QuotaDefault;
import org.gcube.resource.management.quota.library.quotedefault.QuotaDefaultList;
import org.gcube.resource.management.quota.manager.check.QuotaCheck;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ReadFileProperties {
private static Logger log = LoggerFactory.getLogger(QuotaCheck.class);
private InputStream input =null ;
private String fileProperties=null;
private List<QuotaDefault> listQuotaDefault=new ArrayList<QuotaDefault>();
public ReadFileProperties(String fileProperties){
this.fileProperties = fileProperties;
}
public String getFileProperties() {
return fileProperties;
}
public List<QuotaDefault> getListQuotaDefault() {
try {
input = new FileInputStream(fileProperties);
JAXBContext jaxbContext = JAXBContext.newInstance(QuotaDefaultList.class);
QuotaDefaultList quotalist = (QuotaDefaultList) jaxbContext.createUnmarshaller().unmarshal(input);
listQuotaDefault=quotalist.getQuotaDefaultList();
} catch (Exception ex) {
log.error("--:{}",ex.getLocalizedMessage());
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return listQuotaDefault;
}
}

View File

@ -0,0 +1,289 @@
package org.gcube.resource.management.quota.manager.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.resource.management.quota.manager.check.QuotaUsage;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SendNotification {
private String identifier;
private Double quotaAssigned;
private Double quotaUsage;
private Double percent;
private String urlService;
private DiscoveryConfiguration discoveryCheck;
private final static String WRITE_MESSAGE = "2/messages/write-message";
private final static String NAME_USERNAME_GLOBAL_ROLE = "2/users/get-usernames-by-global-role?role-name=Administrator&gcube-token";
private static Logger log = LoggerFactory.getLogger(QuotaUsage.class);
public SendNotification(DiscoveryConfiguration discoveryCheck){
this.discoveryCheck=discoveryCheck;
String context = ScopeProvider.instance.get();
DiscoveryService discoveryList= new DiscoveryService(context);
urlService=discoveryList.getBasePath()+WRITE_MESSAGE;
}
public void configure(String identifier,Double quotaAssigned,Double quotaUsage,Double percent){
this.identifier=identifier;
this.quotaAssigned=quotaAssigned;
this.quotaUsage=quotaUsage;
this.percent=percent;
}
public void sendNotificationUser(String identifier, Double quotaAssigned, Double quotaUsage, Double percent, String type) throws JSONException{
if (discoveryCheck.getNotifierUser()){
Boolean resultSend= false;
configure(identifier, quotaAssigned, quotaUsage, percent);
log.debug("Notification Quota limit used:{} identifier:{} quotaAssigned:{} quotaUsage:{} ",this.percent,this.identifier,this.quotaAssigned,this.quotaUsage);
String body=null;
String subject=null;
if (type=="warning"){
body=CleanNotification(discoveryCheck.getTextQuotaUserWarning());
subject=discoveryCheck.getTextQuotaUserWarningSubject();
}
if (type=="exceed"){
body=CleanNotification(discoveryCheck.getTextQuotaUserExceed());
subject=discoveryCheck.getTextQuotaUserExceedSubject();
}
if (type=="reset"){
body=CleanNotification(discoveryCheck.getTextQuotaUserReset());
subject=discoveryCheck.getTextQuotaUserResetSubject();
}
String token = SecurityTokenProvider.instance.get();
JSONObject urlParameters = new JSONObject();
List<String> user=new ArrayList<String>();
//TODO delete
//user.add("alessandro.pieve");
user.add(identifier);
urlParameters.put("recipients", user);
urlParameters.put("body", body);
urlParameters.put("subject", subject);
try {
resultSend = writeMsg(urlService, urlParameters,token);
} catch (Exception e) {
e.printStackTrace();
}
log.debug("sendNotification user:{} url:{}, body:{}, subject:{}, send:{}",user,body,subject,resultSend);
}
else{
log.debug("Not notification Quota limit used:{} identifier:{} quotaAssigned:{} quotaUsage:{} ",percent,identifier,quotaAssigned,quotaUsage);
}
}
/**
* Send notification with a list of user exceed to admin role
* @param userExceedQuota
* @throws Exception
*/
public void SendNotificationAdmin(List<String> userExceedQuota) throws Exception{
log.debug("SendNotificationAdmin for user:{}",userExceedQuota.toString());
if (userExceedQuota.size()>0){
if (discoveryCheck.getNotifierAdmin()){
Boolean resultSend= false;
String token = SecurityTokenProvider.instance.get();
String context = ScopeProvider.instance.get();
DiscoveryService discoveryList= new DiscoveryService(context);
List<String> sendersList=sendersList(discoveryList.getBasePath()+NAME_USERNAME_GLOBAL_ROLE,token,discoveryCheck.getRoleNotifier());
configure(identifier, quotaAssigned, quotaUsage, percent);
String text=CleanNotification(discoveryCheck.getTextQuotaAdminExceed());
String listUser = "";
for (String s : userExceedQuota)
{
if (s!=null){
listUser += "\n"+ s;
}
}
text=text.replace("{listuser}", listUser);
discoveryList= new DiscoveryService(context);
String urlService=discoveryList.getBasePath()+WRITE_MESSAGE;
log.debug("urlService:{}, text msg:{}",urlService,text);
JSONObject urlParameters = new JSONObject();
List<String> user=new ArrayList<String>();
identifier="alessandro.pieve";
for (String cc :sendersList){
// user.add(cc);
}
user.add(identifier);
urlParameters.put("recipients", user);
urlParameters.put("body", text);
urlParameters.put("subject", discoveryCheck.getTextQuotaAdminExceedSubject());
try {
resultSend = writeMsg(urlService, urlParameters,token);
} catch (Exception e) {
e.printStackTrace();
}
log.debug("send notification quota exceed:{} send:{}",userExceedQuota.toString(),resultSend);
}
else{
log.debug("not send notification quota exceed :{}",userExceedQuota.toString());
}
}
}
/**
* Clean a quota msg for notification
* @param notification
* @return notification with user,quota and percent
*/
private String CleanNotification(String notification){
if (notification.contains("{identifier}")){
notification=notification.replace("{identifier}", identifier);
}
String quotaAssignedLabel;
String quotaUsageLabel;
if (quotaAssigned>1024){
quotaAssignedLabel=String.valueOf(Math.round((quotaAssigned/1024) * 100.0) / 100.0)+"GB";
quotaUsageLabel= String.valueOf(Math.round((quotaUsage/1024) * 100.0) / 100.0)+"GB";
}
else{
quotaAssignedLabel=String.valueOf(quotaAssigned)+"MB";
quotaUsageLabel= String.valueOf(quotaUsage)+"MB";
}
if (notification.contains("{quotaAssigned}")){
notification=notification.replace("{quotaAssigned}", quotaAssignedLabel);
}
if (notification.contains("{quotaUsage}")){
notification=notification.replace("{quotaUsage}", quotaUsageLabel);
}
if (notification.contains("{percent}")){
notification=notification.replace("{percent}", percent.toString());
}
return notification;
}
/**
*
* @param url
* @return String response content
* @throws IOException
* @throws ClientProtocolException
* @throws JSONException
*/
public Boolean writeMsg(String path, JSONObject urlParameters,String token) throws Exception {
Boolean result=false;
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
CloseableHttpClient httpClient = clientBuilder.build();
HttpPost request = new HttpPost(path);
request.addHeader("gcube-token", token);
request.addHeader("Content-type", ContentType.APPLICATION_JSON.toString());
StringEntity params = new StringEntity(urlParameters.toString(), ContentType.APPLICATION_JSON);
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
log.debug("writeMsg path:{} urlParameters:{} request:{}",path,urlParameters,request.toString());
/*
log.info("urlParameters:{}",urlParameters.toString());
log.info("request:{}",request.toString());
*/
int status = response.getStatusLine().getStatusCode();
// check the response status and look if it was a redirect problem
if (status != HttpURLConnection.HTTP_OK && (status == HttpURLConnection.HTTP_MOVED_TEMP ||
status == HttpURLConnection.HTTP_MOVED_PERM ||
status == HttpURLConnection.HTTP_SEE_OTHER)) {
// redirect -> fetch new location
Header[] locations = response.getHeaders("Location");
Header lastLocation = locations[locations.length - 1];
String realLocation = lastLocation.getValue();
log.debug("New location is " + realLocation);
// perform again the same request
request = new HttpPost(realLocation);
request.addHeader("gcube-token", token);
request.addHeader("Content-type", ContentType.APPLICATION_JSON.toString());
params = new StringEntity(urlParameters.toString(), ContentType.APPLICATION_JSON);
request.setEntity(params);
response = httpClient.execute(request);
log.info(" " + response.getStatusLine().getStatusCode() + " and response message is " + response.getStatusLine().getReasonPhrase());
} else{
log.debug(" " + response.getStatusLine().getStatusCode() + " and response message is " + response.getStatusLine().getReasonPhrase());
result=true;
}
return result;
}
/**
* Return a list user from global role
* @param url
* @param token
* @param role
* @return list of identifier for send msg
*/
public List<String> sendersList(String url,String token,String role){
url=url+"?role-name="+role+"&gcube-token="+token;
List<String>userList=new ArrayList<String>();
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setInstanceFollowRedirects(true);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
userList.add(line);
}
br.close();
}
} catch (MalformedURLException ex) {
log.error("MalformedURLException:{}",ex);
} catch (IOException ex) {
log.error("IOException:{}",ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
log.error("Exception:{}",ex);
}
}
}
log.debug("url:{} return list:{}",url,userList.toString());
return userList;
}
}

View File

@ -0,0 +1,28 @@
package org.gcuberesource.management.quota.manager.service.exception;
/**
* ExistingQuotaException
*
* @author Alessandro Pieve (alessandro.pieve@isti.cnr.it)
*
*/
public class ExistingQuotaException extends Exception{
private static final long serialVersionUID = -2255657546267656458L;
/**
*
*/
public ExistingQuotaException() {
super();
}
/**
* @param message
*/
public ExistingQuotaException(String message) {
super(message);
}
public ExistingQuotaException(String message,Throwable t) {
super(message,t);
}
}

View File

@ -0,0 +1,28 @@
package org.gcuberesource.management.quota.manager.service.exception;
/**
* NotFoundQuotaExecption
*
* @author Alessandro Pieve (alessandro.pieve@isti.cnr.it)
*
*/
public class NotFoundQuotaExecption extends Exception{
private static final long serialVersionUID = -3481086211695773825L;
public NotFoundQuotaExecption() {
super();
}
/**
* @param message
*/
public NotFoundQuotaExecption(String message) {
super(message);
}
public NotFoundQuotaExecption(String message,Throwable t) {
super(message,t);
}
}

View File

@ -0,0 +1,20 @@
package org.gcuberesource.management.quota.manager.service.exception;
public class NotFoundQuotaPackageExecption extends Exception{
private static final long serialVersionUID = -3481086211695773825L;
public NotFoundQuotaPackageExecption() {
super();
}
/**
* @param message
*/
public NotFoundQuotaPackageExecption(String message) {
super(message);
}
public NotFoundQuotaPackageExecption(String message,Throwable t) {
super(message,t);
}
}

View File

@ -0,0 +1,29 @@
package org.gcuberesource.management.quota.manager.service.exception;
public class ServiceException extends Exception {
private static final long serialVersionUID = -2255657546267656458L;
/**
*
*/
public ServiceException() {
super();
}
/**
* @param message
*/
public ServiceException(String message) {
super(message);
}
public ServiceException(String message,Throwable t) {
super(message,t);
}
}

View File

@ -0,0 +1,44 @@
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="quota_persistence"
transaction-type="RESOURCE_LOCAL">
<provider>
org.eclipse.persistence.jpa.PersistenceProvider
</provider>
<class>org.gcube.resource.management.quota.manager.persistence.entities.QuotaEntity</class>
<class>org.gcube.resource.management.quota.manager.persistence.entities.ServicePackageManagerEntity</class>
<class>org.gcube.resource.management.quota.manager.persistence.entities.ServicePackageDetailEntity</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:h2:~/DbQuota;TRACE_LEVEL_FILE=3;TRACE_LEVEL_SYSTEM_OUT=3;LOCK_MODE=3" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="eclipselink.ddl-generation.output-mode"
value="database" />
<!-- <property name="eclipselink.ddl-generation" value="drop-and-create-tables"
/> -->
<property name="eclipselink.ddl-generation.output-mode"
value="database" />
<property name="eclipselink.persistence-context.flush-mode"
value="COMMIT" />
<property name="eclipselink.cache.shared.default" value="false"/>
<property name="eclipselink.cache.size.default" value="0"/>
<property name="eclipselink.cache.type.default" value="None"/>
<property name="eclipselink.logging.level" value="INFO" />
<property name="eclipselink.logging.level.sql" value="FINE" />
<property name="eclipselink.logging.parameters" value="true" />
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,313 @@
European Union Public Licence V. 1.1
EUPL © the European Community 2007
This European Union Public Licence (the “EUPL”) applies to the Work or Software
(as defined below) which is provided under the terms of this Licence. Any use of
the Work, other than as authorised under this Licence is prohibited (to the
extent such use is covered by a right of the copyright holder of the Work).
The Original Work is provided under the terms of this Licence when the Licensor
(as defined below) has placed the following notice immediately following the
copyright notice for the Original Work:
Licensed under the EUPL V.1.1
or has expressed by any other mean his willingness to license under the EUPL.
1. Definitions
In this Licence, the following terms have the following meaning:
- The Licence: this Licence.
- The Original Work or the Software: the software distributed and/or
communicated by the Licensor under this Licence, available as Source Code and
also as Executable Code as the case may be.
- Derivative Works: the works or software that could be created by the Licensee,
based upon the Original Work or modifications thereof. This Licence does not
define the extent of modification or dependence on the Original Work required
in order to classify a work as a Derivative Work; this extent is determined by
copyright law applicable in the country mentioned in Article 15.
- The Work: the Original Work and/or its Derivative Works.
- The Source Code: the human-readable form of the Work which is the most
convenient for people to study and modify.
- The Executable Code: any code which has generally been compiled and which is
meant to be interpreted by a computer as a program.
- The Licensor: the natural or legal person that distributes and/or communicates
the Work under the Licence.
- Contributor(s): any natural or legal person who modifies the Work under the
Licence, or otherwise contributes to the creation of a Derivative Work.
- The Licensee or “You”: any natural or legal person who makes any usage of the
Software under the terms of the Licence.
- Distribution and/or Communication: any act of selling, giving, lending,
renting, distributing, communicating, transmitting, or otherwise making
available, on-line or off-line, copies of the Work or providing access to its
essential functionalities at the disposal of any other natural or legal
person.
2. Scope of the rights granted by the Licence
The Licensor hereby grants You a world-wide, royalty-free, non-exclusive,
sub-licensable licence to do the following, for the duration of copyright vested
in the Original Work:
- use the Work in any circumstance and for all usage, reproduce the Work, modify
- the Original Work, and make Derivative Works based upon the Work, communicate
- to the public, including the right to make available or display the Work or
- copies thereof to the public and perform publicly, as the case may be, the
- Work, distribute the Work or copies thereof, lend and rent the Work or copies
- thereof, sub-license rights in the Work or copies thereof.
Those rights can be exercised on any media, supports and formats, whether now
known or later invented, as far as the applicable law permits so.
In the countries where moral rights apply, the Licensor waives his right to
exercise his moral right to the extent allowed by law in order to make effective
the licence of the economic rights here above listed.
The Licensor grants to the Licensee royalty-free, non exclusive usage rights to
any patents held by the Licensor, to the extent necessary to make use of the
rights granted on the Work under this Licence.
3. Communication of the Source Code
The Licensor may provide the Work either in its Source Code form, or as
Executable Code. If the Work is provided as Executable Code, the Licensor
provides in addition a machine-readable copy of the Source Code of the Work
along with each copy of the Work that the Licensor distributes or indicates, in
a notice following the copyright notice attached to the Work, a repository where
the Source Code is easily and freely accessible for as long as the Licensor
continues to distribute and/or communicate the Work.
4. Limitations on copyright
Nothing in this Licence is intended to deprive the Licensee of the benefits from
any exception or limitation to the exclusive rights of the rights owners in the
Original Work or Software, of the exhaustion of those rights or of other
applicable limitations thereto.
5. Obligations of the Licensee
The grant of the rights mentioned above is subject to some restrictions and
obligations imposed on the Licensee. Those obligations are the following:
Attribution right: the Licensee shall keep intact all copyright, patent or
trademarks notices and all notices that refer to the Licence and to the
disclaimer of warranties. The Licensee must include a copy of such notices and a
copy of the Licence with every copy of the Work he/she distributes and/or
communicates. The Licensee must cause any Derivative Work to carry prominent
notices stating that the Work has been modified and the date of modification.
Copyleft clause: If the Licensee distributes and/or communicates copies of the
Original Works or Derivative Works based upon the Original Work, this
Distribution and/or Communication will be done under the terms of this Licence
or of a later version of this Licence unless the Original Work is expressly
distributed only under this version of the Licence. The Licensee (becoming
Licensor) cannot offer or impose any additional terms or conditions on the Work
or Derivative Work that alter or restrict the terms of the Licence.
Compatibility clause: If the Licensee Distributes and/or Communicates Derivative
Works or copies thereof based upon both the Original Work and another work
licensed under a Compatible Licence, this Distribution and/or Communication can
be done under the terms of this Compatible Licence. For the sake of this clause,
“Compatible Licence” refers to the licences listed in the appendix attached to
this Licence. Should the Licensees obligations under the Compatible Licence
conflict with his/her obligations under this Licence, the obligations of the
Compatible Licence shall prevail.
Provision of Source Code: When distributing and/or communicating copies of the
Work, the Licensee will provide a machine-readable copy of the Source Code or
indicate a repository where this Source will be easily and freely available for
as long as the Licensee continues to distribute and/or communicate the Work.
Legal Protection: This Licence does not grant permission to use the trade names,
trademarks, service marks, or names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the copyright notice.
6. Chain of Authorship
The original Licensor warrants that the copyright in the Original Work granted
hereunder is owned by him/her or licensed to him/her and that he/she has the
power and authority to grant the Licence.
Each Contributor warrants that the copyright in the modifications he/she brings
to the Work are owned by him/her or licensed to him/her and that he/she has the
power and authority to grant the Licence.
Each time You accept the Licence, the original Licensor and subsequent
Contributors grant You a licence to their contributions to the Work, under the
terms of this Licence.
7. Disclaimer of Warranty
The Work is a work in progress, which is continuously improved by numerous
contributors. It is not a finished work and may therefore contain defects or
“bugs” inherent to this type of software development.
For the above reason, the Work is provided under the Licence on an “as is” basis
and without warranties of any kind concerning the Work, including without
limitation merchantability, fitness for a particular purpose, absence of defects
or errors, accuracy, non-infringement of intellectual property rights other than
copyright as stated in Article 6 of this Licence.
This disclaimer of warranty is an essential part of the Licence and a condition
for the grant of any rights to the Work.
8. Disclaimer of Liability
Except in the cases of wilful misconduct or damages directly caused to natural
persons, the Licensor will in no event be liable for any direct or indirect,
material or moral, damages of any kind, arising out of the Licence or of the use
of the Work, including without limitation, damages for loss of goodwill, work
stoppage, computer failure or malfunction, loss of data or any commercial
damage, even if the Licensor has been advised of the possibility of such
damage. However, the Licensor will be liable under statutory product liability
laws as far such laws apply to the Work.
9. Additional agreements
While distributing the Original Work or Derivative Works, You may choose to
conclude an additional agreement to offer, and charge a fee for, acceptance of
support, warranty, indemnity, or other liability obligations and/or services
consistent with this Licence. However, in accepting such obligations, You may
act only on your own behalf and on your sole responsibility, not on behalf of
the original Licensor or any other Contributor, and only if You agree to
indemnify, defend, and hold each Contributor harmless for any liability incurred
by, or claims asserted against such Contributor by the fact You have accepted
any such warranty or additional liability.
10. Acceptance of the Licence
The provisions of this Licence can be accepted by clicking on an icon “I agree”
placed under the bottom of a window displaying the text of this Licence or by
affirming consent in any other similar way, in accordance with the rules of
applicable law. Clicking on that icon indicates your clear and irrevocable
acceptance of this Licence and all of its terms and conditions.
Similarly, you irrevocably accept this Licence and all of its terms and
conditions by exercising any rights granted to You by Article 2 of this Licence,
such as the use of the Work, the creation by You of a Derivative Work or the
Distribution and/or Communication by You of the Work or copies thereof.
11. Information to the public
In case of any Distribution and/or Communication of the Work by means of
electronic communication by You (for example, by offering to download the Work
from a remote location) the distribution channel or media (for example, a
website) must at least provide to the public the information requested by the
applicable law regarding the Licensor, the Licence and the way it may be
accessible, concluded, stored and reproduced by the Licensee.
12. Termination of the Licence
The Licence and the rights granted hereunder will terminate automatically upon
any breach by the Licensee of the terms of the Licence.
Such a termination will not terminate the licences of any person who has
received the Work from the Licensee under the Licence, provided such persons
remain in full compliance with the Licence.
13. Miscellaneous
Without prejudice of Article 9 above, the Licence represents the complete
agreement between the Parties as to the Work licensed hereunder.
If any provision of the Licence is invalid or unenforceable under applicable
law, this will not affect the validity or enforceability of the Licence as a
whole. Such provision will be construed and/or reformed so as necessary to make
it valid and enforceable.
The European Commission may publish other linguistic versions and/or new
versions of this Licence, so far this is required and reasonable, without
reducing the scope of the rights granted by the Licence. New versions of the
Licence will be published with a unique version number.
All linguistic versions of this Licence, approved by the European Commission,
have identical value. Parties can take advantage of the linguistic version of
their choice.
14. Jurisdiction
Any litigation resulting from the interpretation of this License, arising
between the European Commission, as a Licensor, and any Licensee, will be
subject to the jurisdiction of the Court of Justice of the European Communities,
as laid down in article 238 of the Treaty establishing the European Community.
Any litigation arising between Parties, other than the European Commission, and
resulting from the interpretation of this License, will be subject to the
exclusive jurisdiction of the competent court where the Licensor resides or
conducts its primary business.
15. Applicable Law
This Licence shall be governed by the law of the European Union country where
the Licensor resides or has his registered office.
This licence shall be governed by the Belgian law if:
- a litigation arises between the European Commission, as a Licensor, and any
- Licensee; the Licensor, other than the European Commission, has no residence
- or registered office inside a European Union country.
===
Appendix
“Compatible Licences” according to article 5 EUPL are:
- GNU General Public License (GNU GPL) v. 2
- Open Software License (OSL) v. 2.1, v. 3.0
- Common Public License v. 1.0
- Eclipse Public License v. 1.0
- Cecill v. 2.0

View File

@ -0,0 +1,75 @@
The gCube System - quota-service
--------------------------------------------------
${description}
This software is part of the gCube Framework (https://www.gcube-system.org/): an
open-source software toolkit used for building and operating Hybrid Data
Infrastructures enabling the dynamic deployment of Virtual Research Environments
by favouring the realisation of reuse oriented policies.
The projects leading to this software have received funding from a series of
European Union programmes including:
* the Sixth Framework Programme for Research and Technological Development -
DILIGENT (grant no. 004260);
* the Seventh Framework Programme for research, technological development and
demonstration - D4Science (grant no. 212488), D4Science-II (grant no.
239019),ENVRI (grant no. 283465), EUBrazilOpenBio (grant no. 288754), iMarine
(grant no. 283644);
* the H2020 research and innovation programme - BlueBRIDGE (grant no. 675680),
EGIEngage (grant no. 654142), ENVRIplus (grant no. 654182), Parthenos (grant
no. 654119), SoBigData (grant no. 654024);
Version
--------------------------------------------------
1.0.0-SNAPSHOT (2017-02-16)
Please see the file named "changelog.xml" in this directory for the release notes.
Authors
--------------------------------------------------
* Alessandro Pieve(alessandro.pieve-AT-isti.cnr.it), CNR, Italy
Maintainers
--------------------------------------------------
* Alessandro Pieve(alessandro.pieve-AT-isti.cnr.it), CNR, Italy
Download information
--------------------------------------------------
Source code is available from SVN:
${scm.url}
Binaries can be downloaded from the gCube website:
https://www.gcube-system.org/
Installation
--------------------------------------------------
Installation documentation is available on-line in the gCube Wiki:
https://wiki.gcube-system.org/gcube/index.php
Documentation
--------------------------------------------------
Documentation is available on-line in the gCube Wiki:
https://wiki.gcube-system.org/gcube/index.php
Support
--------------------------------------------------
Bugs and support requests can be reported in the gCube issue tracking tool:
https://support.d4science.org/projects/gcube/
Licensing
--------------------------------------------------
This software is licensed under the terms you may find in the file named "LICENSE" in this directory.

View File

@ -0,0 +1,5 @@
<ReleaseNotes>
<Changeset component="org.gcube.information-system.quota-manager.1-0-0" date="2015-04-28">
<Change>First Release</Change>
</Changeset>
</ReleaseNotes>

View File

@ -0,0 +1,35 @@
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>servicearchive</id>
<formats>
<format>tar.gz</format>
</formats>
<baseDirectory>/</baseDirectory>
<fileSets>
<fileSet>
<directory>/home/pieve/workspace/quota-manager/distro</directory>
<outputDirectory>/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
<includes>
<include>README</include>
<include>LICENSE</include>
<include>changelog.xml</include>
</includes>
<fileMode>755</fileMode>
<filtered>true</filtered>
</fileSet>
</fileSets>
<files>
<file>
<source>/home/pieve/workspace/quota-manager/distro/profile.xml</source>
<outputDirectory>/</outputDirectory>
<filtered>true</filtered>
</file>
<file>
<source>target/quota-manager.war</source>
<outputDirectory>/quota-manager</outputDirectory>
</file>
</files>
</assembly>

View File

@ -0,0 +1,8 @@
<application mode='online'>
<name>QuotaManager</name>
<group>InformationSystem</group>
<version>1.0.0-SNAPSHOT</version>
<description>quota mananger webapp</description>
<local-persistence location='target' />
</application>

View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<Resource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ID />
<Type>Service</Type>
<Profile>
<Description>${description}</Description>
<Class>InformationSystem</Class>
<Name>quota-manager</Name>
<Version>1.0.0</Version>
<Packages>
<Software>
<Name>quota-manager</Name>
<Version>1.0.0-SNAPSHOT</Version>
<MavenCoordinates>
<groupId>org.gcube.resource.management</groupId>
<artifactId>quota-manager</artifactId>
<version>1.0.0-SNAPSHOT</version>
</MavenCoordinates>
<Files>
<File>quota-manager.jar</File>
</Files>
</Software>
</Packages>
</Profile>
</Resource>

View File

@ -0,0 +1,9 @@
<web-app>
<servlet>
<servlet-name>org.gcube.resource.management.quota.manager.service.QuotaService</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>org.gcube.resource.management.quota.manager.service.QuotaService</servlet-name>
<url-pattern>/gcube/service/*</url-pattern>
</servlet-mapping>
</web-app>

View File

@ -0,0 +1,45 @@
package org.gcube.resource.management.quota;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.resource.management.quota.manager.util.DiscoveryConfiguration;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class QuotaCheckTaskTest {
private static Logger log = LoggerFactory.getLogger(DiscoveryConfiguration.class);
@Before
public void before() throws Exception{
String token="3acdde42-6883-4564-b3ba-69f6486f6fe0-98187548";
SecurityTokenProvider.instance.set(token);
String context="/gcube";
ScopeProvider.instance.set(context);
}
@Test
public void QuotaCheckTest() throws Exception{
//String context=ScopeProvider.instance.get();
//QuotaCheck quotaCheck =new QuotaCheck(context);
//quotaCheck.getQuotaCheck();
}
@Test
public void QuotaConfigurationTest() throws Exception{
String context=ScopeProvider.instance.get();
DiscoveryConfiguration discoveryCheck =new DiscoveryConfiguration(context);
log.debug(discoveryCheck.toString());
}
}

View File

@ -0,0 +1,65 @@
package org.gcube.resource.management.quota;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;
import org.gcube.resource.management.quota.library.QuotaList;
import org.gcube.resource.management.quota.library.quotalist.AccessType;
import org.gcube.resource.management.quota.library.quotalist.CallerType;
import org.gcube.resource.management.quota.library.quotalist.Quota;
import org.gcube.resource.management.quota.library.quotalist.ServiceQuota;
import org.gcube.resource.management.quota.library.quotalist.StorageQuota;
import org.gcube.resource.management.quota.library.quotalist.TimeInterval;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@Slf4j
public class QuotaManagerTest extends JerseyTest{
/*
@Override
protected Application configure() {
AbstractBinder binder = new AbstractBinder() {
@Override
protected void configure() {
}
};
ResourceConfig config = new ResourceConfig(QuotaManager.class);
config.register(binder);
return config;
}
*/
List<Quota> quoteList;
QuotaList retrievedQuota;
@Before
public void reset(){
retrievedQuota = null;
quoteList = null;
}
@Test
public void add() throws Exception{
quoteList = new ArrayList<Quota>();
quoteList.add(new ServiceQuota("/gcube","alessandro.pieve",CallerType.USER,TimeInterval.DAILY,100.0,AccessType.ACCESS));
quoteList.add(new StorageQuota("/gcube","lucio.lelii",CallerType.USER,TimeInterval.DAILY,100.0));
Response response = target("quotaManager/insert").request()
.post(Entity.xml(new QuotaList(quoteList)), Response.class);
Assert.assertEquals(200, response.getStatus());
}
@Test
public void deleteOne() throws Exception{
}
}