From 78e50b04fb8e0674b35f05b071725a5b7fc5f399 Mon Sep 17 00:00:00 2001 From: Alessandro Pieve Date: Thu, 16 Feb 2017 16:46:46 +0000 Subject: [PATCH] git-svn-id: http://svn.research-infrastructures.eu/public/d4science/gcube/trunk/resource-management/quota-manager@142648 82a268e6-3cf1-43bd-a215-b396298e98cf --- .classpath | 31 ++ .project | 42 +++ .settings/.jsdtscope | 13 + .settings/org.eclipse.core.resources.prefs | 5 + .settings/org.eclipse.jdt.core.prefs | 8 + .settings/org.eclipse.jpt.core.prefs | 3 + .settings/org.eclipse.m2e.core.prefs | 4 + .settings/org.eclipse.wst.common.component | 12 + ...se.wst.common.project.facet.core.prefs.xml | 12 + ....eclipse.wst.common.project.facet.core.xml | 9 + ...rg.eclipse.wst.jsdt.ui.superType.container | 1 + .../org.eclipse.wst.jsdt.ui.superType.name | 1 + .settings/org.eclipse.wst.validation.prefs | 2 + distro/LICENSE | 1 + distro/README | 62 ++++ distro/changelog.xml | 5 + distro/descriptor.xml | 35 ++ distro/gcube-app.xml | 8 + distro/profile.xml | 26 ++ distro/web.xml | 9 + pom.xml | 301 +++++++++++++++ .../quota/manager/check/MyAppManager.java | 89 +++++ .../manager/check/QuotaCalculateUtil.java | 250 +++++++++++++ .../quota/manager/check/QuotaCheck.java | 134 +++++++ .../quota/manager/check/QuotaCheckTask.java | 62 ++++ .../quota/manager/check/QuotaUsage.java | 343 +++++++++++++++++ .../defaults/InformationSystemQuery.java | 70 ++++ .../persistence/QuotaDBPersistence.java | 346 ++++++++++++++++++ .../QuotaPackageDBPersistence.java | 184 ++++++++++ .../persistence/entities/EntityConstants.java | 14 + .../persistence/entities/QuotaEntity.java | 157 ++++++++ .../entities/ServicePackageDetailEntity.java | 76 ++++ .../entities/ServicePackageManagerEntity.java | 99 +++++ .../entities/ServiceQuotaEntity.java | 83 +++++ .../entities/StorageQuotaEntity.java | 52 +++ .../converters/StringListConverter.java | 38 ++ .../quota/manager/service/QuotaManager.java | 108 ++++++ .../manager/service/QuotaPackageManager.java | 154 ++++++++ .../quota/manager/service/QuotaService.java | 16 + .../quota/manager/service/QuotaStatus.java | 60 +++ .../quota/manager/util/Constants.java | 28 ++ .../quota/manager/util/ConstantsDb.java | 17 + .../manager/util/DiscoveryConfiguration.java | 255 +++++++++++++ .../quota/manager/util/DiscoveryListUser.java | 110 ++++++ .../quota/manager/util/DiscoveryService.java | 108 ++++++ .../quota/manager/util/ListUser.java | 38 ++ .../manager/util/QuotaUsageServiceValue.java | 52 +++ .../manager/util/QuotaUsageStorageValue.java | 31 ++ .../manager/util/ReadFileProperties.java | 52 +++ .../quota/manager/util/SendNotification.java | 289 +++++++++++++++ .../exception/ExistingQuotaException.java | 28 ++ .../exception/NotFoundQuotaExecption.java | 28 ++ .../NotFoundQuotaPackageExecption.java | 20 + .../service/exception/ServiceException.java | 29 ++ src/main/resources/META-INF/persistence.xml | 44 +++ src/main/webapp/WEB-INF/LICENSE | 313 ++++++++++++++++ src/main/webapp/WEB-INF/README | 75 ++++ src/main/webapp/WEB-INF/changelog.xml | 5 + src/main/webapp/WEB-INF/descriptor.xml | 35 ++ src/main/webapp/WEB-INF/gcube-app.xml | 8 + src/main/webapp/WEB-INF/profile.xml | 26 ++ src/main/webapp/WEB-INF/web.xml | 9 + .../management/quota/QuotaCheckTaskTest.java | 45 +++ .../management/quota/QuotaManagerTest.java | 65 ++++ 64 files changed, 4635 insertions(+) create mode 100644 .classpath create mode 100644 .project create mode 100644 .settings/.jsdtscope create mode 100644 .settings/org.eclipse.core.resources.prefs create mode 100644 .settings/org.eclipse.jdt.core.prefs create mode 100644 .settings/org.eclipse.jpt.core.prefs create mode 100644 .settings/org.eclipse.m2e.core.prefs create mode 100644 .settings/org.eclipse.wst.common.component create mode 100644 .settings/org.eclipse.wst.common.project.facet.core.prefs.xml create mode 100644 .settings/org.eclipse.wst.common.project.facet.core.xml create mode 100644 .settings/org.eclipse.wst.jsdt.ui.superType.container create mode 100644 .settings/org.eclipse.wst.jsdt.ui.superType.name create mode 100644 .settings/org.eclipse.wst.validation.prefs create mode 100644 distro/LICENSE create mode 100644 distro/README create mode 100644 distro/changelog.xml create mode 100644 distro/descriptor.xml create mode 100644 distro/gcube-app.xml create mode 100644 distro/profile.xml create mode 100644 distro/web.xml create mode 100644 pom.xml create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/check/MyAppManager.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/check/QuotaCalculateUtil.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/check/QuotaCheck.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/check/QuotaCheckTask.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/check/QuotaUsage.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/defaults/InformationSystemQuery.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/persistence/QuotaDBPersistence.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/persistence/QuotaPackageDBPersistence.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/EntityConstants.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/QuotaEntity.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/ServicePackageDetailEntity.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/ServicePackageManagerEntity.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/ServiceQuotaEntity.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/StorageQuotaEntity.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/converters/StringListConverter.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/service/QuotaManager.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/service/QuotaPackageManager.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/service/QuotaService.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/service/QuotaStatus.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/util/Constants.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/util/ConstantsDb.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/util/DiscoveryConfiguration.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/util/DiscoveryListUser.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/util/DiscoveryService.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/util/ListUser.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/util/QuotaUsageServiceValue.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/util/QuotaUsageStorageValue.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/util/ReadFileProperties.java create mode 100644 src/main/java/org/gcube/resource/management/quota/manager/util/SendNotification.java create mode 100644 src/main/java/org/gcuberesource/management/quota/manager/service/exception/ExistingQuotaException.java create mode 100644 src/main/java/org/gcuberesource/management/quota/manager/service/exception/NotFoundQuotaExecption.java create mode 100644 src/main/java/org/gcuberesource/management/quota/manager/service/exception/NotFoundQuotaPackageExecption.java create mode 100644 src/main/java/org/gcuberesource/management/quota/manager/service/exception/ServiceException.java create mode 100644 src/main/resources/META-INF/persistence.xml create mode 100644 src/main/webapp/WEB-INF/LICENSE create mode 100644 src/main/webapp/WEB-INF/README create mode 100644 src/main/webapp/WEB-INF/changelog.xml create mode 100644 src/main/webapp/WEB-INF/descriptor.xml create mode 100644 src/main/webapp/WEB-INF/gcube-app.xml create mode 100644 src/main/webapp/WEB-INF/profile.xml create mode 100644 src/main/webapp/WEB-INF/web.xml create mode 100644 src/test/java/org/gcube/resource/management/quota/QuotaCheckTaskTest.java create mode 100644 src/test/java/org/gcube/resource/management/quota/QuotaManagerTest.java diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..eed8a51 --- /dev/null +++ b/.classpath @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.project b/.project new file mode 100644 index 0000000..71543ff --- /dev/null +++ b/.project @@ -0,0 +1,42 @@ + + + quota-manager + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/.settings/.jsdtscope b/.settings/.jsdtscope new file mode 100644 index 0000000..b72a6a4 --- /dev/null +++ b/.settings/.jsdtscope @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..839d647 --- /dev/null +++ b/.settings/org.eclipse.core.resources.prefs @@ -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/=UTF-8 diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..443e085 --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -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 diff --git a/.settings/org.eclipse.jpt.core.prefs b/.settings/org.eclipse.jpt.core.prefs new file mode 100644 index 0000000..b990e75 --- /dev/null +++ b/.settings/org.eclipse.jpt.core.prefs @@ -0,0 +1,3 @@ +eclipse.preferences.version=1 +org.eclipse.jpt.core.platform=eclipselink2_2 +org.eclipse.jpt.jpa.core.discoverAnnotatedClasses=true diff --git a/.settings/org.eclipse.m2e.core.prefs b/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..f897a7f --- /dev/null +++ b/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/.settings/org.eclipse.wst.common.component b/.settings/org.eclipse.wst.common.component new file mode 100644 index 0000000..fb915f8 --- /dev/null +++ b/.settings/org.eclipse.wst.common.component @@ -0,0 +1,12 @@ + + + + + + + uses + + + + + diff --git a/.settings/org.eclipse.wst.common.project.facet.core.prefs.xml b/.settings/org.eclipse.wst.common.project.facet.core.prefs.xml new file mode 100644 index 0000000..f8c4647 --- /dev/null +++ b/.settings/org.eclipse.wst.common.project.facet.core.prefs.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/.settings/org.eclipse.wst.common.project.facet.core.xml b/.settings/org.eclipse.wst.common.project.facet.core.xml new file mode 100644 index 0000000..00113f6 --- /dev/null +++ b/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/.settings/org.eclipse.wst.jsdt.ui.superType.container b/.settings/org.eclipse.wst.jsdt.ui.superType.container new file mode 100644 index 0000000..3bd5d0a --- /dev/null +++ b/.settings/org.eclipse.wst.jsdt.ui.superType.container @@ -0,0 +1 @@ +org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/.settings/org.eclipse.wst.jsdt.ui.superType.name b/.settings/org.eclipse.wst.jsdt.ui.superType.name new file mode 100644 index 0000000..05bd71b --- /dev/null +++ b/.settings/org.eclipse.wst.jsdt.ui.superType.name @@ -0,0 +1 @@ +Window \ No newline at end of file diff --git a/.settings/org.eclipse.wst.validation.prefs b/.settings/org.eclipse.wst.validation.prefs new file mode 100644 index 0000000..04cad8c --- /dev/null +++ b/.settings/org.eclipse.wst.validation.prefs @@ -0,0 +1,2 @@ +disabled=06target +eclipse.preferences.version=1 diff --git a/distro/LICENSE b/distro/LICENSE new file mode 100644 index 0000000..3695e26 --- /dev/null +++ b/distro/LICENSE @@ -0,0 +1 @@ +${gcube.license} diff --git a/distro/README b/distro/README new file mode 100644 index 0000000..3d2847f --- /dev/null +++ b/distro/README @@ -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. diff --git a/distro/changelog.xml b/distro/changelog.xml new file mode 100644 index 0000000..f4dfd5c --- /dev/null +++ b/distro/changelog.xml @@ -0,0 +1,5 @@ + + + First Release + + \ No newline at end of file diff --git a/distro/descriptor.xml b/distro/descriptor.xml new file mode 100644 index 0000000..5ba272a --- /dev/null +++ b/distro/descriptor.xml @@ -0,0 +1,35 @@ + + servicearchive + + tar.gz + + / + + + ${distroDirectory} + / + true + + README + LICENSE + changelog.xml + + 755 + true + + + + + ${distroDirectory}/profile.xml + / + true + + + target/${build.finalName}.war + /${artifactId} + + + diff --git a/distro/gcube-app.xml b/distro/gcube-app.xml new file mode 100644 index 0000000..8d90846 --- /dev/null +++ b/distro/gcube-app.xml @@ -0,0 +1,8 @@ + + QuotaManager + InformationSystem + ${version} + quota mananger webapp + + + diff --git a/distro/profile.xml b/distro/profile.xml new file mode 100644 index 0000000..f6970f3 --- /dev/null +++ b/distro/profile.xml @@ -0,0 +1,26 @@ + + + + Service + + ${description} + InformationSystem + ${artifactId} + 1.0.0 + + + ${artifactId} + ${version} + + ${groupId} + ${artifactId} + ${version} + + + ${build.finalName}.jar + + + + + + diff --git a/distro/web.xml b/distro/web.xml new file mode 100644 index 0000000..fa5f357 --- /dev/null +++ b/distro/web.xml @@ -0,0 +1,9 @@ + + + org.gcube.resource.management.quota.manager.service.QuotaService + + + org.gcube.resource.management.quota.manager.service.QuotaService + /gcube/service/* + + \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..aeb2196 --- /dev/null +++ b/pom.xml @@ -0,0 +1,301 @@ + + 4.0.0 + + maven-parent + org.gcube.tools + 1.0.0 + + + org.gcube.resource.management + quota-manager + 1.0.0-SNAPSHOT + quota-service + war + + ${project.basedir}/src/main/webapp/WEB-INF + ${project.basedir}/distro + + + + + + org.gcube.distribution + maven-smartgears-bom + LATEST + pom + import + + + + + + + + org.gcube.core + common-smartgears-app + + + org.gcube.core + common-smartgears + + + org.gcube.resource.management + quota-library + [1.0.0-SNAPSHOT, 2.0.0-SNAPSHOT) + + + + org.gcube.core + common-encryption + + + + org.gcube.core + common-scope-maps + + + + org.gcube.core + common-scope + + + + org.gcube.core + common-encryption + + + + + javax.ws.rs + javax.ws.rs-api + 2.0 + + + org.glassfish.jersey.containers + jersey-container-servlet + 2.13 + + + org.glassfish.jersey.containers.glassfish + jersey-gf-cdi + 2.13 + + + + javax.transaction + javax.transaction-api + 1.2 + + + javax.servlet + javax.servlet-api + 3.0.1 + provided + + + + postgresql + postgresql + 9.1-901.jdbc4 + runtime + + + + javax.enterprise + cdi-api + 1.1 + + + + org.jboss.weld.servlet + weld-servlet + 2.2.4.Final + + + + org.jboss + jandex + 1.2.2.Final + + + + + + org.projectlombok + lombok + 1.14.8 + + + + eclipselink + org.eclipse.persistence + 2.5.1 + + + + ch.qos.logback + logback-classic + 1.0.13 + + + + org.glassfish.jersey.test-framework.providers + jersey-test-framework-provider-simple + 2.17 + test + + + + org.apache.derby + derby + 10.8.2.2 + test + + + org.apache.derby + derbyclient + 10.8.2.2 + test + + + + com.googlecode.jeeunit + jeeunit + 1.0.0 + test + + + + com.google.code.gson + gson + 2.7 + + + + + + org.gcube.accounting + accounting-analytics + [2.4.0-SNAPSHOT,3.0.0-SNAPSHOT) + + + org.gcube.accounting + accounting-analytics-persistence-couchbase + [1.0.0-SNAPSHOT,2.0.0-SNAPSHOT) + + + org.gcube.accounting + accounting-lib + provided + + + + org.gcube.common + authorization-client + provided + + + org.gcube.common + common-authorization + provided + + + + + + + org.gcube.resources.discovery + discovery-client + + + org.gcube.resources + common-gcore-resources + + + org.gcube.resources.discovery + ic-client + + + org.apache.httpcomponents + httpclient + 4.3.4 + + + + + + + + + ${artifactId} + + + maven-compiler-plugin + 2.3.2 + + 1.7 + 1.7 + + + + org.apache.maven.plugins + maven-resources-plugin + 2.6 + + + copy-profile + + copy-resources + + process-resources + + ${webappDirectory} + + + ${distroDirectory} + true + + + + + + + + org.apache.maven.plugins + maven-war-plugin + 2.4 + + quota-manager + false + + + + org.apache.maven.plugins + maven-assembly-plugin + + + ${distroDirectory}/descriptor.xml + + + + + servicearchive + install + + single + + + + + + + + + diff --git a/src/main/java/org/gcube/resource/management/quota/manager/check/MyAppManager.java b/src/main/java/org/gcube/resource/management/quota/manager/check/MyAppManager.java new file mode 100644 index 0000000..79f9946 --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/check/MyAppManager.java @@ -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; + } + + + + + + +} diff --git a/src/main/java/org/gcube/resource/management/quota/manager/check/QuotaCalculateUtil.java b/src/main/java/org/gcube/resource/management/quota/manager/check/QuotaCalculateUtil.java new file mode 100644 index 0000000..4b6469f --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/check/QuotaCalculateUtil.java @@ -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 quoteDefault=null; + + public void setQuoteDefault(List quoteDefault) { + this.quoteDefault = quoteDefault; + } + public List getQuoteDefault() { + return quoteDefault; + } + + private String context; + private List usageToBeVerified=new ArrayList(); + + public List 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 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> 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 filtersList=null; + filtersList=new ArrayList(); + 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 filters =new ArrayList(); + 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()), quotaBlocked.getContext()); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + SecurityTokenProvider.instance.set(token); + List policies = new ArrayList(); + 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(); + } + + } +} diff --git a/src/main/java/org/gcube/resource/management/quota/manager/check/QuotaCheck.java b/src/main/java/org/gcube/resource/management/quota/manager/check/QuotaCheck.java new file mode 100644 index 0000000..5151991 --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/check/QuotaCheck.java @@ -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 quoteChecked=new ArrayList(); + 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"); + */ + } + + +} diff --git a/src/main/java/org/gcube/resource/management/quota/manager/check/QuotaCheckTask.java b/src/main/java/org/gcube/resource/management/quota/manager/check/QuotaCheckTask.java new file mode 100644 index 0000000..c3c53d7 --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/check/QuotaCheckTask.java @@ -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!"); + } + + + + } + +} \ No newline at end of file diff --git a/src/main/java/org/gcube/resource/management/quota/manager/check/QuotaUsage.java b/src/main/java/org/gcube/resource/management/quota/manager/check/QuotaUsage.java new file mode 100644 index 0000000..a6388a3 --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/check/QuotaUsage.java @@ -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 userExceedQuota =new ArrayList(); + + 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)&&(percentConstants.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; + } + +} diff --git a/src/main/java/org/gcube/resource/management/quota/manager/defaults/InformationSystemQuery.java b/src/main/java/org/gcube/resource/management/quota/manager/defaults/InformationSystemQuery.java new file mode 100644 index 0000000..16447a0 --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/defaults/InformationSystemQuery.java @@ -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 listQuotaDefault=new ArrayList(); + + + /** + * 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 client = ICFactory + .clientFor(GenericResource.class); + List 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 getListQuotaDefault() { + return listQuotaDefault; + } +} diff --git a/src/main/java/org/gcube/resource/management/quota/manager/persistence/QuotaDBPersistence.java b/src/main/java/org/gcube/resource/management/quota/manager/persistence/QuotaDBPersistence.java new file mode 100644 index 0000000..dcb431b --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/persistence/QuotaDBPersistence.java @@ -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 persistenceMap = new HashMap(); + 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 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 + * @throws NotFoundQuotaExecption + */ + public List getQuote(String context) throws NotFoundQuotaExecption { + List quoteToReturn = new ArrayList(); + EntityManager em = emFactory.createEntityManager(); + try{ + TypedQuery 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 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 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(); + } + } + */ +} diff --git a/src/main/java/org/gcube/resource/management/quota/manager/persistence/QuotaPackageDBPersistence.java b/src/main/java/org/gcube/resource/management/quota/manager/persistence/QuotaPackageDBPersistence.java new file mode 100644 index 0000000..52ac8f0 --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/persistence/QuotaPackageDBPersistence.java @@ -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 + * @throws NotFoundQuotaPackageExecption + */ + public List getPackages() throws NotFoundQuotaPackageExecption { + List packagesToReturn = new ArrayList(); + EntityManager em = emFactory.createEntityManager(); + try{ + TypedQuery query = em.createNamedQuery("ServicePackage.all", ServicePackageManagerEntity.class); + if (query.getResultList().size()>0){ + for (ServicePackageManagerEntity serEntity: query.getResultList()){ + List servicePackageDetaiListl = new ArrayList(); + 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 query = em.createNamedQuery("ServicePackage.getById", ServicePackageManagerEntity.class); + query.setParameter("id", servicepackage_id); + if (query.getResultList().size()>0){ + for (ServicePackageManagerEntity serEntity: query.getResultList()){ + List servicePackageDetaiListl = new ArrayList(); + 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; + + } + + +} diff --git a/src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/EntityConstants.java b/src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/EntityConstants.java new file mode 100644 index 0000000..55ad119 --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/EntityConstants.java @@ -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"; + +} diff --git a/src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/QuotaEntity.java b/src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/QuotaEntity.java new file mode 100644 index 0000000..8b4b613 --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/QuotaEntity.java @@ -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; + } + */ +} diff --git a/src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/ServicePackageDetailEntity.java b/src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/ServicePackageDetailEntity.java new file mode 100644 index 0000000..0c52658 --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/ServicePackageDetailEntity.java @@ -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); + } + } + +} diff --git a/src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/ServicePackageManagerEntity.java b/src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/ServicePackageManagerEntity.java new file mode 100644 index 0000000..8af87f1 --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/ServicePackageManagerEntity.java @@ -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 listdetail; + + + public void addPackageDetail(ServicePackageDetailEntity listdetail) { + this.listdetail.add(listdetail); + if (listdetail.getServicePackage() != this) { + listdetail.setServicePackage(this); + } + } + + public ServicePackageManagerEntity(){ + listdetail = new ArrayList(); + } + + + public ServicePackageManagerEntity(String name) { + super(); + this.name = name; + + } + public ServicePackageManagerEntity(String name, List 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 getListdetail() { + return listdetail; + } + + public void setListdetail(List listdetail) { + this.listdetail = listdetail; + } +} diff --git a/src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/ServiceQuotaEntity.java b/src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/ServiceQuotaEntity.java new file mode 100644 index 0000000..b0e5a36 --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/ServiceQuotaEntity.java @@ -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 + "]"; + } + + + + +} diff --git a/src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/StorageQuotaEntity.java b/src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/StorageQuotaEntity.java new file mode 100644 index 0000000..598d5d4 --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/StorageQuotaEntity.java @@ -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 + "]"; + } + + + + +} diff --git a/src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/converters/StringListConverter.java b/src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/converters/StringListConverter.java new file mode 100644 index 0000000..e3376f9 --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/persistence/entities/converters/StringListConverter.java @@ -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, String>{ + @Override + public String convertToDatabaseColumn(List 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 convertToEntityAttribute(String dbEntry) { + if (dbEntry!=null && !dbEntry.isEmpty()){ + return Arrays.asList(dbEntry.split(",\\|\\|,")); + } + else return new ArrayList(0); + } + + + +} + diff --git a/src/main/java/org/gcube/resource/management/quota/manager/service/QuotaManager.java b/src/main/java/org/gcube/resource/management/quota/manager/service/QuotaManager.java new file mode 100644 index 0000000..6656b1b --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/service/QuotaManager.java @@ -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()); + } + } + +} + + diff --git a/src/main/java/org/gcube/resource/management/quota/manager/service/QuotaPackageManager.java b/src/main/java/org/gcube/resource/management/quota/manager/service/QuotaPackageManager.java new file mode 100644 index 0000000..425f1ab --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/service/QuotaPackageManager.java @@ -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 + * + * Pacchetto 2 + * + * Nome servizio 2-1 + * + * + * Nome servizio 2-2 + * + * + * @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: + * + * + * 4 + * Pacchetto 1 + * + * 9 + * 4 + * Nome servizio 2 + * + * + * 10 + * 4 + * Nome servizio 1 + * + * + * + * @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(); + } + */ + + + +} diff --git a/src/main/java/org/gcube/resource/management/quota/manager/service/QuotaService.java b/src/main/java/org/gcube/resource/management/quota/manager/service/QuotaService.java new file mode 100644 index 0000000..2d109cd --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/service/QuotaService.java @@ -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"); + } +} \ No newline at end of file diff --git a/src/main/java/org/gcube/resource/management/quota/manager/service/QuotaStatus.java b/src/main/java/org/gcube/resource/management/quota/manager/service/QuotaStatus.java new file mode 100644 index 0000000..358b38c --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/service/QuotaStatus.java @@ -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; + } +} + + diff --git a/src/main/java/org/gcube/resource/management/quota/manager/util/Constants.java b/src/main/java/org/gcube/resource/management/quota/manager/util/Constants.java new file mode 100644 index 0000000..fb544f2 --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/util/Constants.java @@ -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; + + +} diff --git a/src/main/java/org/gcube/resource/management/quota/manager/util/ConstantsDb.java b/src/main/java/org/gcube/resource/management/quota/manager/util/ConstantsDb.java new file mode 100644 index 0000000..2003ef0 --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/util/ConstantsDb.java @@ -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"; +} diff --git a/src/main/java/org/gcube/resource/management/quota/manager/util/DiscoveryConfiguration.java b/src/main/java/org/gcube/resource/management/quota/manager/util/DiscoveryConfiguration.java new file mode 100644 index 0000000..c8a9a5b --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/util/DiscoveryConfiguration.java @@ -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 client = clientFor(ServiceEndpoint.class); + List serviceEndpoints = client.submit(query); + + return serviceEndpoints.get(0); + } + + protected void setValues(ServiceEndpoint serviceEndpoint) throws Exception{ + Group 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 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; + } + +} diff --git a/src/main/java/org/gcube/resource/management/quota/manager/util/DiscoveryListUser.java b/src/main/java/org/gcube/resource/management/quota/manager/util/DiscoveryListUser.java new file mode 100644 index 0000000..7fe5598 --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/util/DiscoveryListUser.java @@ -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 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(); + 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 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; + } +} + diff --git a/src/main/java/org/gcube/resource/management/quota/manager/util/DiscoveryService.java b/src/main/java/org/gcube/resource/management/quota/manager/util/DiscoveryService.java new file mode 100644 index 0000000..12cbd96 --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/util/DiscoveryService.java @@ -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 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 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 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 client = clientFor(ServiceEndpoint.class); + List 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; + } + + + +} \ No newline at end of file diff --git a/src/main/java/org/gcube/resource/management/quota/manager/util/ListUser.java b/src/main/java/org/gcube/resource/management/quota/manager/util/ListUser.java new file mode 100644 index 0000000..a5ed97a --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/util/ListUser.java @@ -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 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 getResult() { + return result; + } + public void setResult(List result) { + this.result = result; + } + + +} \ No newline at end of file diff --git a/src/main/java/org/gcube/resource/management/quota/manager/util/QuotaUsageServiceValue.java b/src/main/java/org/gcube/resource/management/quota/manager/util/QuotaUsageServiceValue.java new file mode 100644 index 0000000..81a85a8 --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/util/QuotaUsageServiceValue.java @@ -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> clz,TemporalConstraint temporalConstraint,List 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; + } + +} diff --git a/src/main/java/org/gcube/resource/management/quota/manager/util/QuotaUsageStorageValue.java b/src/main/java/org/gcube/resource/management/quota/manager/util/QuotaUsageStorageValue.java new file mode 100644 index 0000000..bd96dbc --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/util/QuotaUsageStorageValue.java @@ -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> 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; + } + +} diff --git a/src/main/java/org/gcube/resource/management/quota/manager/util/ReadFileProperties.java b/src/main/java/org/gcube/resource/management/quota/manager/util/ReadFileProperties.java new file mode 100644 index 0000000..28b3abe --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/util/ReadFileProperties.java @@ -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 listQuotaDefault=new ArrayList(); + + public ReadFileProperties(String fileProperties){ + this.fileProperties = fileProperties; + } + public String getFileProperties() { + return fileProperties; + } + public List 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; + } +} diff --git a/src/main/java/org/gcube/resource/management/quota/manager/util/SendNotification.java b/src/main/java/org/gcube/resource/management/quota/manager/util/SendNotification.java new file mode 100644 index 0000000..d0d4539 --- /dev/null +++ b/src/main/java/org/gcube/resource/management/quota/manager/util/SendNotification.java @@ -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 user=new ArrayList(); + //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 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 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 user=new ArrayList(); + 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 sendersList(String url,String token,String role){ + url=url+"?role-name="+role+"&gcube-token="+token; + ListuserList=new ArrayList(); + 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; + } +} diff --git a/src/main/java/org/gcuberesource/management/quota/manager/service/exception/ExistingQuotaException.java b/src/main/java/org/gcuberesource/management/quota/manager/service/exception/ExistingQuotaException.java new file mode 100644 index 0000000..5473934 --- /dev/null +++ b/src/main/java/org/gcuberesource/management/quota/manager/service/exception/ExistingQuotaException.java @@ -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); + } + + +} \ No newline at end of file diff --git a/src/main/java/org/gcuberesource/management/quota/manager/service/exception/NotFoundQuotaExecption.java b/src/main/java/org/gcuberesource/management/quota/manager/service/exception/NotFoundQuotaExecption.java new file mode 100644 index 0000000..c2cbcb1 --- /dev/null +++ b/src/main/java/org/gcuberesource/management/quota/manager/service/exception/NotFoundQuotaExecption.java @@ -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); + } + + +} \ No newline at end of file diff --git a/src/main/java/org/gcuberesource/management/quota/manager/service/exception/NotFoundQuotaPackageExecption.java b/src/main/java/org/gcuberesource/management/quota/manager/service/exception/NotFoundQuotaPackageExecption.java new file mode 100644 index 0000000..afa9ae6 --- /dev/null +++ b/src/main/java/org/gcuberesource/management/quota/manager/service/exception/NotFoundQuotaPackageExecption.java @@ -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); + } + + +} \ No newline at end of file diff --git a/src/main/java/org/gcuberesource/management/quota/manager/service/exception/ServiceException.java b/src/main/java/org/gcuberesource/management/quota/manager/service/exception/ServiceException.java new file mode 100644 index 0000000..f72cd0a --- /dev/null +++ b/src/main/java/org/gcuberesource/management/quota/manager/service/exception/ServiceException.java @@ -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); + } + + +} \ No newline at end of file diff --git a/src/main/resources/META-INF/persistence.xml b/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000..78acada --- /dev/null +++ b/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,44 @@ + + + + org.eclipse.persistence.jpa.PersistenceProvider + + org.gcube.resource.management.quota.manager.persistence.entities.QuotaEntity + org.gcube.resource.management.quota.manager.persistence.entities.ServicePackageManagerEntity + org.gcube.resource.management.quota.manager.persistence.entities.ServicePackageDetailEntity + + false + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/webapp/WEB-INF/LICENSE b/src/main/webapp/WEB-INF/LICENSE new file mode 100644 index 0000000..573db28 --- /dev/null +++ b/src/main/webapp/WEB-INF/LICENSE @@ -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 Licensee’s 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 diff --git a/src/main/webapp/WEB-INF/README b/src/main/webapp/WEB-INF/README new file mode 100644 index 0000000..6590020 --- /dev/null +++ b/src/main/webapp/WEB-INF/README @@ -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. diff --git a/src/main/webapp/WEB-INF/changelog.xml b/src/main/webapp/WEB-INF/changelog.xml new file mode 100644 index 0000000..f4dfd5c --- /dev/null +++ b/src/main/webapp/WEB-INF/changelog.xml @@ -0,0 +1,5 @@ + + + First Release + + \ No newline at end of file diff --git a/src/main/webapp/WEB-INF/descriptor.xml b/src/main/webapp/WEB-INF/descriptor.xml new file mode 100644 index 0000000..88f5784 --- /dev/null +++ b/src/main/webapp/WEB-INF/descriptor.xml @@ -0,0 +1,35 @@ + + servicearchive + + tar.gz + + / + + + /home/pieve/workspace/quota-manager/distro + / + true + + README + LICENSE + changelog.xml + + 755 + true + + + + + /home/pieve/workspace/quota-manager/distro/profile.xml + / + true + + + target/quota-manager.war + /quota-manager + + + diff --git a/src/main/webapp/WEB-INF/gcube-app.xml b/src/main/webapp/WEB-INF/gcube-app.xml new file mode 100644 index 0000000..4123269 --- /dev/null +++ b/src/main/webapp/WEB-INF/gcube-app.xml @@ -0,0 +1,8 @@ + + QuotaManager + InformationSystem + 1.0.0-SNAPSHOT + quota mananger webapp + + + diff --git a/src/main/webapp/WEB-INF/profile.xml b/src/main/webapp/WEB-INF/profile.xml new file mode 100644 index 0000000..c98c123 --- /dev/null +++ b/src/main/webapp/WEB-INF/profile.xml @@ -0,0 +1,26 @@ + + + + Service + + ${description} + InformationSystem + quota-manager + 1.0.0 + + + quota-manager + 1.0.0-SNAPSHOT + + org.gcube.resource.management + quota-manager + 1.0.0-SNAPSHOT + + + quota-manager.jar + + + + + + diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..fa5f357 --- /dev/null +++ b/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,9 @@ + + + org.gcube.resource.management.quota.manager.service.QuotaService + + + org.gcube.resource.management.quota.manager.service.QuotaService + /gcube/service/* + + \ No newline at end of file diff --git a/src/test/java/org/gcube/resource/management/quota/QuotaCheckTaskTest.java b/src/test/java/org/gcube/resource/management/quota/QuotaCheckTaskTest.java new file mode 100644 index 0000000..8c44447 --- /dev/null +++ b/src/test/java/org/gcube/resource/management/quota/QuotaCheckTaskTest.java @@ -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()); + + } + + +} diff --git a/src/test/java/org/gcube/resource/management/quota/QuotaManagerTest.java b/src/test/java/org/gcube/resource/management/quota/QuotaManagerTest.java new file mode 100644 index 0000000..45d833a --- /dev/null +++ b/src/test/java/org/gcube/resource/management/quota/QuotaManagerTest.java @@ -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 quoteList; + + QuotaList retrievedQuota; + + @Before + public void reset(){ + retrievedQuota = null; + quoteList = null; + } + + @Test + public void add() throws Exception{ + quoteList = new ArrayList(); + 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{ + } + +}