service is working

This commit is contained in:
Alfredo Oliviero 2024-05-16 17:59:39 +02:00
parent a2a1c03067
commit b4a6cb5539
19 changed files with 869 additions and 290 deletions

75
pom.xml
View File

@ -9,20 +9,29 @@
</parent> </parent>
<groupId>org.gcube.social_networking</groupId> <groupId>org.gcube.social_networking</groupId>
<artifactId>social-service</artifactId> <artifactId>social-service</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging> <packaging>war</packaging>
<name>Social Service</name> <name>Social Service</name>
<description>This is the social service</description> <description>This is the social service</description>
<properties> <properties>
<java.version>11</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source> <maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target> <maven.compiler.target>${java.version}</maven.compiler.target>
<!-- OPTIONAL. for authorization-control-library -->
<aspectj-plugin.version>1.14.0</aspectj-plugin.version>
<webappDirectory> <webappDirectory>
${project.basedir}${file.separator}src${file.separator}main${file.separator}webapp${file.separator}WEB-INF</webappDirectory> ${project.basedir}${file.separator}src${file.separator}main${file.separator}webapp${file.separator}WEB-INF</webappDirectory>
<enunciate.version>2.14.0</enunciate.version> <enunciate.version>2.14.0</enunciate.version>
<cassandra.driver.oss.version>4.13.0</cassandra.driver.oss.version> <cassandra.driver.oss.version>4.13.0</cassandra.driver.oss.version>
<!-- only for serializers in example folder -->
<!-- <jackson.version>2.15.3</jackson.version> -->
</properties> </properties>
<scm> <scm>
@ -112,7 +121,15 @@
<version>2.6</version> <version>2.6</version>
</dependency> </dependency>
<!-- <dependency>
<groupId>org.gcube.common</groupId>
<artifactId>common-authorization</artifactId>
</dependency> -->
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>authorization-control-library</artifactId>
</dependency>
<dependency> <dependency>
@ -133,7 +150,16 @@
<version>${enunciate.version}</version> <version>${enunciate.version}</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<!-- only for serializers in example folder -->
<!-- <dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson.version}</version>
</dependency> -->
<!-- END Required for Enunciate plugin --> <!-- END Required for Enunciate plugin -->
<!-- Test libraries --> <!-- Test libraries -->
@ -150,10 +176,6 @@
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/jakarta.mail/jakarta.mail-api --> <!-- https://mvnrepository.com/artifact/jakarta.mail/jakarta.mail-api -->
<dependency> <dependency>
<groupId>jakarta.mail</groupId> <groupId>jakarta.mail</groupId>
@ -166,7 +188,7 @@
<artifactId>ehcache</artifactId> <artifactId>ehcache</artifactId>
<version>2.10.0</version> <version>2.10.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.gcube.dvos</groupId> <groupId>org.gcube.dvos</groupId>
<artifactId>usermanagement-core</artifactId> <artifactId>usermanagement-core</artifactId>
@ -186,13 +208,18 @@
<artifactId>jakarta.servlet-api</artifactId> <artifactId>jakarta.servlet-api</artifactId>
<version>4.0.4</version> <version>4.0.4</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.gcube.idm</groupId> <groupId>org.gcube.idm</groupId>
<artifactId>idm-common-library</artifactId> <artifactId>idm-common-library</artifactId>
<version>0.0.2-SNAPSHOT</version> <version>0.0.2-SNAPSHOT</version>
</dependency> </dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-cdi2-se</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -249,6 +276,34 @@
</configuration> </configuration>
</plugin> </plugin>
<!-- OPTIONAL. authorization-control-library: add this plugin if you
want to use gcube
authorization control funzionalities -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>${aspectj-plugin.version}</version>
<configuration>
<complianceLevel>${java.version}</complianceLevel>
<source>${java.version}</source>
<target>${java.version}</target>
<aspectLibraries>
<aspectLibrary>
<groupId>org.gcube.common</groupId>
<artifactId>authorization-control-library</artifactId>
</aspectLibrary>
</aspectLibraries>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins> </plugins>
</build> </build>

View File

@ -1,25 +0,0 @@
package org.gcube.social_networking;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Application;
import org.gcube.social_networking.rest.HelloWorld;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashSet;
import java.util.Set;
@Path("social-service")
public class SocialService extends Application {
private static Logger logger = LoggerFactory.getLogger(SocialService.class);
@Override
public Set<Class<?>> getClasses() {
logger.info("/social-service/ here");
final Set<Class<?>> classes = new HashSet<Class<?>>();
// register resources and features
classes.add(HelloWorld.class);
return classes;
}
}

View File

@ -1,67 +1,49 @@
package org.gcube.social_networking; package org.gcube.social_networking;
import org.gcube.common.security.providers.SecretManagerProvider; import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.smartgears.ApplicationManager; import org.gcube.smartgears.ApplicationManager;
import org.gcube.smartgears.ContextProvider;
import org.gcube.smartgears.configuration.Mode;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Ahmed Ibrahim
*/ */
public class SocialServiceApplicationManager implements ApplicationManager { public class SocialServiceApplicationManager implements ApplicationManager {
Logger logger = LoggerFactory.getLogger(SocialServiceApplicationManager.class);
/** /**
* Logger
*/
private static Logger logger = LoggerFactory.getLogger(SocialServiceApplicationManager.class);
public static boolean initialised;
/**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public synchronized void onInit() { public void onInit() {
if (ContextProvider.get().container().configuration().mode() == Mode.offline) {
logger.info("Starting social service"); logger.debug("init called in offline mode");
try{ } else {
String context = SecretManagerProvider.get().getContext(); Secret secret = SecretManagerProvider.get();
logger.info( if (secret != null) {
"\n-------------------------------------------------------\n" logger.debug("init called in context {}", secret.getContext());
+ "Social Service is Starting on context {}\n" } else {
+ "-------------------------------------------------------", logger.debug("init called in null context");
context); }
}catch (Throwable e) {
logger.error("unexpected error initiliazing storagehub",e);
} }
// ApplicationContext applicationContext = ContextProvider.get();
// String helloWorldEServiceID = applicationContext.id();
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public synchronized void onShutdown(){ public void onShutdown() {
if (ContextProvider.get().container().configuration().mode() == Mode.offline) {
String context = SecretManagerProvider.get().getContext(); logger.debug("shutDown called in offline mode");
} else {
logger.trace( Secret secret = SecretManagerProvider.get();
"\n-------------------------------------------------------\n" if (secret != null) {
+ "Hello World Service is Stopping on context {}\n" logger.debug("shutDown called in context {}", secret.getContext());
+ "-------------------------------------------------------", } else {
context); logger.debug("shutDown called in null context");
}
}
logger.trace(
"\n-------------------------------------------------------\n"
+ "Hello World Service Stopped Successfully on context {}\n"
+ "-------------------------------------------------------",
context);
} }
} }

View File

@ -0,0 +1,56 @@
package org.gcube.social_networking.mappers;
import org.gcube.social_networking.utils.ResponseBean;
import jakarta.ws.rs.ForbiddenException;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;
/**
* @author Alfredo Oliviero (ISTI - CNR)
*/
@Provider
public class ForbiddenExceptionMapper implements ExceptionMapper<ForbiddenException> {
@Override
public Response toResponse(ForbiddenException exception) {
Status status = Status.INTERNAL_SERVER_ERROR;
String exceptionMessage = exception.getMessage();
ResponseBean responseBean = null;
try {
if (exception.getCause() != null) {
exceptionMessage = exception.getCause().getMessage();
}
} catch (Exception e) {
exceptionMessage = exception.getMessage();
}
MediaType mediaType = MediaType.TEXT_PLAIN_TYPE;
if (WebApplicationException.class.isAssignableFrom(exception.getClass())) {
Response gotResponse = ((WebApplicationException) exception).getResponse();
Object entity = gotResponse.getEntity();
if (entity != null && ResponseBean.class.isAssignableFrom(entity.getClass())) {
responseBean = (ResponseBean) entity;
}
status = Status.fromStatusCode(gotResponse.getStatusInfo().getStatusCode());
}
if (responseBean == null) {
responseBean = new ResponseBean();
}
responseBean.setSuccess(false);
responseBean.setMessage(exceptionMessage);
// responseBean.set
return Response.status(status).entity(responseBean).type(mediaType).build();
}
}

View File

@ -0,0 +1,55 @@
package org.gcube.social_networking.mappers;
import org.gcube.social_networking.utils.ResponseBean;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;
/**
* @author Luca Frosini (ISTI - CNR)
*/
@Provider
public class IDMExceptionMapper implements ExceptionMapper<Exception> {
@Override
public Response toResponse(Exception exception) {
Status status = Status.INTERNAL_SERVER_ERROR;
String exceptionMessage = exception.getMessage();
ResponseBean responseBean = null;
try {
if (exception.getCause() != null) {
exceptionMessage = exception.getCause().getMessage();
}
} catch (Exception e) {
exceptionMessage = exception.getMessage();
}
MediaType mediaType = MediaType.TEXT_PLAIN_TYPE;
if (WebApplicationException.class.isAssignableFrom(exception.getClass())) {
Response gotResponse = ((WebApplicationException) exception).getResponse();
Object entity = gotResponse.getEntity();
if (entity != null && ResponseBean.class.isAssignableFrom(entity.getClass())) {
responseBean = (ResponseBean) entity;
}
status = Status.fromStatusCode(gotResponse.getStatusInfo().getStatusCode());
}
if (responseBean == null) {
responseBean = new ResponseBean();
}
responseBean.setSuccess(false);
responseBean.setMessage(exceptionMessage);
// responseBean.set
return Response.status(status).entity(responseBean).type(mediaType).build();
}
}

View File

@ -1,66 +0,0 @@
package org.gcube.social_networking.rest;
import com.webcohesion.enunciate.metadata.rs.RequestHeader;
import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
import com.webcohesion.enunciate.metadata.rs.ResourceGroup;
import com.webcohesion.enunciate.metadata.rs.ResourceLabel;
import org.gcube.social_networking.socialnetworking.model.shared.Comment;
import jakarta.ws.rs.*;
import java.util.List;
@Path("comments")
@ResourceGroup("Comments APIs")
@ResourceLabel("Comments APIs")
@RequestHeaders({
@RequestHeader( name = "Authorization", description = "Bearer token, see <a href=\"https://dev.d4science.org/how-to-access-resources\">https://dev.d4science.org/how-to-access-resources</a>")
})
public class Comments {
@POST
@Path("/")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"})
@Consumes({"application/json;charset=UTF-8", "application/vnd.api+json"})
public void addComment(Comment comment) {
}
@GET
@Path("/{id}")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"})
public void readComment(@PathParam("id") String id) {
}
@PUT
@Path("/{id}")
@Consumes({"application/json;charset=UTF-8", "application/vnd.api+json"})
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"})
public void editComment(@PathParam("id") String id, Comment comment) {
}
@DELETE
@Path("/{id}")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"})
public void deleteComment(@PathParam("id") String id) {
}
//the following two methods had vreid why?
@POST
@Path("/{id}/hashtags")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"})
@Consumes({"application/json;charset=UTF-8", "application/vnd.api+json"})
public void saveHashTagsComment(@PathParam("id") String commentId, List<String> hashtags) {
}
@DELETE
@Path("/{id}/hashtags")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"})
@Consumes({"application/json;charset=UTF-8", "application/vnd.api+json"})
public void deleteHashTagsComment(@PathParam("id") String commentId, List<String> hashtags) {
}
}

View File

@ -4,24 +4,51 @@ import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path; import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces; import jakarta.ws.rs.Produces;
import java.util.HashMap;
import java.util.Map;
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.common.security.Owner;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.smartgears.ContextProvider;
import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.utils.InnerMethodName;
import org.gcube.social_networking.rest.examples.serializers.IdmObjectSerializator;
import com.webcohesion.enunciate.metadata.rs.RequestHeader; import com.webcohesion.enunciate.metadata.rs.RequestHeader;
import com.webcohesion.enunciate.metadata.rs.RequestHeaders; import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
import com.webcohesion.enunciate.metadata.rs.ResourceGroup; import com.webcohesion.enunciate.metadata.rs.ResourceGroup;
import com.webcohesion.enunciate.metadata.rs.ResourceLabel; import com.webcohesion.enunciate.metadata.rs.ResourceLabel;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Path("/test") @Path("/test")
@ResourceGroup("Comments APIs") @ResourceGroup("Comments APIs")
@ResourceLabel("Comments APIs") @ResourceLabel("Comments APIs")
@RequestHeaders ({ @RequestHeaders({
@RequestHeader( name = "Authorization", description = "Bearer token, see <a href=\"https://dev.d4science.org/how-to-access-resources\">https://dev.d4science.org/how-to-access-resources</a>") @RequestHeader(name = "Authorization", description = "Bearer token, see <a href=\"https://dev.d4science.org/how-to-access-resources\">https://dev.d4science.org/how-to-access-resources</a>")
}) })
public class TestRest { public class TestRest {
@GET @GET
@Path("/test") @Path("/test")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"}) @Produces({ MediaType.APPLICATION_JSON })
public String test(){ public Response test() {
return "{\"result\":\"funziona!!!\"}";
HashMap<String, Object> resp = new HashMap<String, Object>();
resp.put("result", "funziona");
try {
String jsonData = new ObjectMapper().writeValueAsString(resp);
return Response.ok(jsonData).build();
} catch (JsonProcessingException e) {
e.printStackTrace();
return Response.serverError().build();
}
} }
} }

View File

@ -19,15 +19,15 @@ import jakarta.ws.rs.core.Response;
@ResourceGroup("Attachments APIs") @ResourceGroup("Attachments APIs")
@ResourceLabel("Attachments APIs") @ResourceLabel("Attachments APIs")
@RequestHeaders({ @RequestHeaders({
@RequestHeader( name = "Authorization", description = "Bearer token, see <a href=\"https://dev.d4science.org/how-to-access-resources\">https://dev.d4science.org/how-to-access-resources</a>") @RequestHeader(name = "Authorization", description = "Bearer token, see <a href=\"https://dev.d4science.org/how-to-access-resources\">https://dev.d4science.org/how-to-access-resources</a>")
}) })
public class Attachments extends Collection { public class Attachments extends Collection {
private static final Logger logger = LoggerFactory.getLogger(Attachments.class); private static final Logger logger = LoggerFactory.getLogger(Attachments.class);
private Response ErrorHandler(Exception e, String action, String id){ private Response ErrorHandler(Exception e, String action, String id) {
ResponseBean<Boolean> responseBean = new ResponseBean<>(); ResponseBean<Boolean> responseBean = new ResponseBean<>();
Response.Status status; Response.Status status;
logger.info("Unable to "+action+" attachment {}.", id); logger.info("Unable to " + action + " attachment {}.", id);
logger.info(e.getMessage()); logger.info(e.getMessage());
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false); responseBean.setSuccess(false);
@ -36,15 +36,15 @@ public class Attachments extends Collection {
} }
@POST @POST
@Path("/") @Path("")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public Response createAttachment(Attachment attachment) { public Response createAttachment(Attachment attachment) {
try{ try {
logger.info("Creating attachment with id {}.", attachment.getId()); logger.info("Creating attachment with id {}.", attachment.getId());
return super.create(attachment); return super.create(attachment);
}catch(Exception e){ } catch (Exception e) {
return ErrorHandler(e, "create",attachment.getId()); return ErrorHandler(e, "create", attachment.getId());
} }
} }
@ -52,11 +52,11 @@ public class Attachments extends Collection {
@Path("/{id}") @Path("/{id}")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public Response readAttachment(@NotNull @PathParam("id") String id) { public Response readAttachment(@NotNull @PathParam("id") String id) {
try{ try {
logger.info("Reading attachment with id {}.", id); logger.info("Reading attachment with id {}.", id);
return super.read(id, ResourceNames.Attachment); return super.read(id, ResourceNames.Attachment);
}catch(Exception e){ } catch (Exception e) {
return ErrorHandler(e, "fetch",id); return ErrorHandler(e, "fetch", id);
} }
} }
@ -64,11 +64,11 @@ public class Attachments extends Collection {
@Path("/{id}") @Path("/{id}")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public Response deleteAttachment(@NotNull @PathParam("id") String id) { public Response deleteAttachment(@NotNull @PathParam("id") String id) {
try{ try {
logger.info("Deleting attachment with id {}.", id); logger.info("Deleting attachment with id {}.", id);
return super.delete(id,ResourceNames.Attachment); return super.delete(id, ResourceNames.Attachment);
}catch(Exception e){ } catch (Exception e) {
return ErrorHandler(e, "delete",id); return ErrorHandler(e, "delete", id);
} }
} }
@ -77,11 +77,11 @@ public class Attachments extends Collection {
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public Response updateAttachment(@NotNull @PathParam("id") String id, @NotNull Attachment attachment) { public Response updateAttachment(@NotNull @PathParam("id") String id, @NotNull Attachment attachment) {
try{ try {
logger.info("Updating attachment with id {}", id); logger.info("Updating attachment with id {}", id);
return super.update(id, attachment); return super.update(id, attachment);
}catch(Exception e){ } catch (Exception e) {
return ErrorHandler(e, "update",id); return ErrorHandler(e, "update", id);
} }
} }
} }

View File

@ -37,8 +37,9 @@ public class Entities extends Collection {
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
// TODO: unificare con getRecentPosts
@GET @GET
@Path("users/{id}/posts") @Path("users/{id}/allposts")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"}) @Produces({"application/json;charset=UTF-8", "application/vnd.api+json"})
public Response getAllPostsByUser(@NotNull @PathParam("id") String id, public Response getAllPostsByUser(@NotNull @PathParam("id") String id,
@QueryParam("liked") boolean liked, @QueryParam("liked") boolean liked,

View File

@ -17,20 +17,20 @@ import jakarta.ws.rs.core.GenericType;
import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.Response;
import java.util.*; import java.util.*;
@Path("vres") @Path("vres")
@ResourceGroup("Vres APIs") @ResourceGroup("Vres APIs")
@ResourceLabel("Vres APIs") @ResourceLabel("Vres APIs")
@RequestHeaders({ @RequestHeaders({
@RequestHeader( name = "Authorization", description = "Bearer token, see <a href=\"https://dev.d4science.org/how-to-access-resources\">https://dev.d4science.org/how-to-access-resources</a>") @RequestHeader(name = "Authorization", description = "Bearer token, see <a href=\"https://dev.d4science.org/how-to-access-resources\">https://dev.d4science.org/how-to-access-resources</a>")
}) })
public class Vres extends Collection { public class Vres extends Collection {
private static final Logger logger = LoggerFactory.getLogger(Vres.class); private static final Logger logger = LoggerFactory.getLogger(Vres.class);
private Response ErrorHandler(Exception e, String action, String id){
private Response ErrorHandler(Exception e, String action, String id) {
ResponseBean<Boolean> responseBean = new ResponseBean<>(); ResponseBean<Boolean> responseBean = new ResponseBean<>();
Response.Status status; Response.Status status;
logger.info("Unable to "+action+" vre {}.", id); logger.info("Unable to " + action + " vre {}.", id);
logger.info(e.getMessage()); logger.info(e.getMessage());
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false); responseBean.setSuccess(false);
@ -38,193 +38,219 @@ public class Vres extends Collection {
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
@GET // @GET
@Path("/{id}/posts") // @Path("/{id}/posts")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"}) // @Produces({ "application/json;charset=UTF-8", "application/vnd.api+json" })
public Response getAllPostsByVre(@NotNull @PathParam("id") String id){ // public Response getAllPostsByVre(@NotNull @PathParam("id") String id) {
try{ // try {
logger.info("Getting all posts of VRE: " + id); // logger.info("Getting all posts of VRE: " + id);
return super.readChildOf(id, ResourceNames.VRE, ResourceNames.POST); // return super.readChildOf(id, ResourceNames.VRE, ResourceNames.POST);
}catch(Exception e){ // } catch (Exception e) {
return ErrorHandler(e, "fetch posts of",id); // return ErrorHandler(e, "fetch posts of", id);
} // }
} // }
@GET @GET
@Path("/") @Path("/")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"}) @Produces({ "application/json;charset=UTF-8", "application/vnd.api+json" })
public Response getAllVreIds(){ public Response getAllVreIds() {
try{ try {
logger.info("Getting all VRE IDs"); logger.info("Getting all VRE IDs");
List<String> ids = new ArrayList<>(); List<String> ids = new ArrayList<>();
List<Vre> vres = super.readAll(ResourceNames.VRE).readEntity(new GenericType<ResponseBean<List<Vre>>>(){}).getResult(); List<Vre> vres = super.readAll(ResourceNames.VRE).readEntity(new GenericType<ResponseBean<List<Vre>>>() {
for(Vre vre: vres){ }).getResult();
for (Vre vre : vres) {
ids.add(vre.getId()); ids.add(vre.getId());
} }
Response.Status status = Response.Status.OK; Response.Status status = Response.Status.OK;
ResponseBean <List<String>> responseBean = new ResponseBean<>(); ResponseBean<List<String>> responseBean = new ResponseBean<>();
responseBean.setMessage("vre ids fetched Successfully"); responseBean.setMessage("vre ids fetched Successfully");
responseBean.setSuccess(true); responseBean.setSuccess(true);
responseBean.setResult(ids); responseBean.setResult(ids);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
}catch(Exception e){ } catch (Exception e) {
return ErrorHandler(e, "fetch ids of",""); return ErrorHandler(e, "fetch ids of", "");
} }
} }
// TODO: verificare limit null
@GET @GET
@Path("/{id}/posts") @Path("/{id}/posts")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"}) @Produces({ "application/json;charset=UTF-8", "application/vnd.api+json" })
public Response getRecentPostsByVre(@NotNull @PathParam("id") String id, @QueryParam("limit") @DefaultValue("10") int limit){ public Response getRecentPostsByVre(@NotNull @PathParam("id") String id,
try{ @QueryParam("limit") Integer limit) {
logger.info("Getting most recent {} posts of VRE {} " , limit, id); try {
return super.readChildOfWithParameter(id, ParameterNames.RECENT_LIMIT, String.valueOf(limit), ResourceNames.VRE, ResourceNames.POST); logger.info("Getting most recent {} posts of VRE {} ", limit, id);
}catch(Exception e){ if (limit != null)
return ErrorHandler(e, "fetch recent posts of",id); return super.readChildOfWithParameter(id, ParameterNames.RECENT_LIMIT, String.valueOf(limit),
ResourceNames.VRE, ResourceNames.POST);
else
return super.readChildOf(id, ResourceNames.VRE, ResourceNames.POST);
} catch (Exception e) {
return ErrorHandler(e, "fetch recent posts of", id);
} }
} }
@POST @POST
@Path("/{id}/posts") @Path("/{id}/posts")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"}) @Produces({ "application/json;charset=UTF-8", "application/vnd.api+json" })
@Consumes({"application/json;charset=UTF-8", "application/vnd.api+json"}) @Consumes({ "application/json;charset=UTF-8", "application/vnd.api+json" })
public Response savePostToVRETimeline(@NotNull @PathParam("id") String id, @NotNull Post post){ public Response savePostToVRETimeline(@NotNull @PathParam("id") String id, @NotNull Post post) {
try{ try {
logger.info("saving post {} to VRE {} " , post.getKey(), id); logger.info("saving post {} to VRE {} ", post.getKey(), id);
return super.createChildOf(id, post, ResourceNames.VRE); return super.createChildOf(id, post, ResourceNames.VRE);
}catch(Exception e){ } catch (Exception e) {
return ErrorHandler(e, "save post to",id); return ErrorHandler(e, "save post to", id);
} }
} }
// @GET
// @Path("/{id}/hashtags")
// @Produces({"application/json;charset=UTF-8", "application/vnd.api+json"})
// public Response getVREHashtagsWithOccurrence(@NotNull @PathParam("id") String
// id){
// try{
// logger.info("getting hashtags of VRE {} " , id);
// return super.readChildOf(id, ResourceNames.VRE, ResourceNames.HASHTAG);
// }catch(Exception e){
// return ErrorHandler(e, "get hashtags of",id);
// }
// }
// TODO: verificare implementazione con timestamp null
@GET @GET
@Path("/{id}/hashtags") @Path("/{id}/hashtags")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"}) @Produces({ "application/json;charset=UTF-8", "application/vnd.api+json" })
public Response getVREHashtagsWithOccurrence(@NotNull @PathParam("id") String id){ public Response getVREHashtagsWithOccurrenceFilteredByTime(@NotNull @PathParam("id") String id,
try{ @QueryParam("time") Long timestamp) {
logger.info("getting hashtags of VRE {} " , id); try {
return super.readChildOf(id, ResourceNames.VRE, ResourceNames.HASHTAG); logger.info("getting hashtags of VRE {} starting {} ", id, timestamp);
}catch(Exception e){ if (timestamp == null) {
return ErrorHandler(e, "get hashtags of",id); return super.readChildOf(id, ResourceNames.VRE, ResourceNames.HASHTAG);
} }
} return super.readChildOfWithParameter(id, ParameterNames.TIME, String.valueOf(timestamp), ResourceNames.VRE,
ResourceNames.HASHTAG);
} catch (Exception e) {
@GET return ErrorHandler(e, "get time_filtered hashtags of", id);
@Path("/{id}/hashtags")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"})
public Response getVREHashtagsWithOccurrenceFilteredByTime(@NotNull @PathParam("id") String id, @NotNull @QueryParam("time") long timestamp){
try{
logger.info("getting hashtags of VRE {} starting {} " , id, timestamp);
return super.readChildOfWithParameter(id, ParameterNames.TIME, String.valueOf(timestamp), ResourceNames.VRE, ResourceNames.HASHTAG);
}catch(Exception e){
return ErrorHandler(e, "get time_filtered hashtags of",id);
} }
} }
@GET @GET
@Path("/{id}/hashtags/{hashtag}/posts") @Path("/{id}/hashtags/{hashtag}/posts")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"}) @Produces({ "application/json;charset=UTF-8", "application/vnd.api+json" })
public Response getVREPostsByHashtag(@NotNull @PathParam("id") String id, @NotNull @PathParam("hashtag") String hashtag){ public Response getVREPostsByHashtag(@NotNull @PathParam("id") String id,
try{ @NotNull @PathParam("hashtag") String hashtag) {
logger.info("getting posts containing hashtags in VRE {}" , id); try {
return super.readChildOfWithParameter(id, ParameterNames.HASHTAG, hashtag, ResourceNames.VRE, ResourceNames.POST); logger.info("getting posts containing hashtags in VRE {}", id);
}catch(Exception e){ return super.readChildOfWithParameter(id, ParameterNames.HASHTAG, hashtag, ResourceNames.VRE,
return ErrorHandler(e, "get posts containing hashtag in",id); ResourceNames.POST);
} catch (Exception e) {
return ErrorHandler(e, "get posts containing hashtag in", id);
} }
} }
@GET @GET
@Path("/{id}/invites/") @Path("/{id}/invites/")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"}) @Produces({ "application/json;charset=UTF-8", "application/vnd.api+json" })
@Consumes({"application/json;charset=UTF-8", "application/vnd.api+json"}) @Consumes({ "application/json;charset=UTF-8", "application/vnd.api+json" })
public Response getInvitedEmailsByVRE(@NotNull @PathParam("id") String id, @NotNull InviteStatus... status){ public Response getInvitedEmailsByVRE(@NotNull @PathParam("id") String id, @NotNull InviteStatus... status) {
try{ try {
logger.info("getting invites in VRE {}" , id); logger.info("getting invites in VRE {}", id);
return super.readChildOfWithParameter(id, ParameterNames.STATUS, Arrays.toString(status), ResourceNames.VRE, ResourceNames.INVITE); return super.readChildOfWithParameter(id, ParameterNames.STATUS, Arrays.toString(status), ResourceNames.VRE,
}catch(Exception e){ ResourceNames.INVITE);
return ErrorHandler(e, "get invites in",id); } catch (Exception e) {
return ErrorHandler(e, "get invites in", id);
} }
} }
@GET @GET
@Path("/{id}/invites/{email}") @Path("/{id}/invites/{email}")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"}) @Produces({ "application/json;charset=UTF-8", "application/vnd.api+json" })
public Response isExistingInvite(@NotNull @PathParam("id") String id, @NotNull @PathParam("email")String email){ public Response isExistingInvite(@NotNull @PathParam("id") String id, @NotNull @PathParam("email") String email) {
try{ try {
logger.info("checking if invite {} exists in VRE {}" , email, id); logger.info("checking if invite {} exists in VRE {}", email, id);
return super.readChildOfWithParameter(id, ParameterNames.EMAIL, email, ResourceNames.VRE, ResourceNames.INVITE); return super.readChildOfWithParameter(id, ParameterNames.EMAIL, email, ResourceNames.VRE,
}catch(Exception e){ ResourceNames.INVITE);
return ErrorHandler(e, "check invite in",id); } catch (Exception e) {
return ErrorHandler(e, "check invite in", id);
} }
} }
@PUT @PUT
@Path("/{id}/invites/{email}") @Path("/{id}/invites/{email}")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"}) @Produces({ "application/json;charset=UTF-8", "application/vnd.api+json" })
@Consumes({"application/json;charset=UTF-8", "application/vnd.api+json"}) @Consumes({ "application/json;charset=UTF-8", "application/vnd.api+json" })
public Response setInviteStatus(@NotNull @PathParam("id") String id, @NotNull @PathParam("email")String email, @NotNull InviteStatus inviteStatus){ public Response setInviteStatus(@NotNull @PathParam("id") String id, @NotNull @PathParam("email") String email,
try{ @NotNull InviteStatus inviteStatus) {
logger.info("setting invite {} status in VRE {}" , email, id); try {
logger.info("setting invite {} status in VRE {}", email, id);
Invite invite = new Invite(); Invite invite = new Invite();
invite.setStatus(inviteStatus); invite.setStatus(inviteStatus);
return super.updateChildOfWithParameter(id, ParameterNames.EMAIL, email, invite, ResourceNames.VRE); return super.updateChildOfWithParameter(id, ParameterNames.EMAIL, email, invite, ResourceNames.VRE);
}catch(Exception e){ } catch (Exception e) {
return ErrorHandler(e, "set invite status in",id); return ErrorHandler(e, "set invite status in", id);
} }
} }
@POST @POST
@Path("/{id}/posts/{postid}/hashtags") @Path("/{id}/posts/{postid}/hashtags")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"}) @Produces({ "application/json;charset=UTF-8", "application/vnd.api+json" })
@Consumes({"application/json;charset=UTF-8", "application/vnd.api+json"}) @Consumes({ "application/json;charset=UTF-8", "application/vnd.api+json" })
public Response saveHashTags(@NotNull @PathParam("id") String id, @NotNull @PathParam("postid") String postid, @NotNull List<Hashtag>hashtags){ public Response saveHashTags(@NotNull @PathParam("id") String id, @NotNull @PathParam("postid") String postid,
try{ @NotNull List<Hashtag> hashtags) {
try {
logger.info("saving post hashtags to VRE {} ", id); logger.info("saving post hashtags to VRE {} ", id);
return super.BatchCreateChildOfWithParameter(id, ResourceNames.POST, postid, new ArrayList<>(hashtags), ResourceNames.VRE, ResourceNames.HASHTAG); return super.BatchCreateChildOfWithParameter(id, ResourceNames.POST, postid, new ArrayList<>(hashtags),
}catch(Exception e){ ResourceNames.VRE, ResourceNames.HASHTAG);
return ErrorHandler(e, "save post hashtags to",id); } catch (Exception e) {
return ErrorHandler(e, "save post hashtags to", id);
} }
} }
@DELETE @DELETE
@Path("/{id}/posts/{postid}/hashtags") @Path("/{id}/posts/{postid}/hashtags")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"}) @Produces({ "application/json;charset=UTF-8", "application/vnd.api+json" })
@Consumes({"application/json;charset=UTF-8", "application/vnd.api+json"}) @Consumes({ "application/json;charset=UTF-8", "application/vnd.api+json" })
public Response deleteHashTags(@NotNull @PathParam("id") String id, @NotNull @PathParam("postid") String postid, @NotNull List<Hashtag>hashtags){ public Response deleteHashTags(@NotNull @PathParam("id") String id, @NotNull @PathParam("postid") String postid,
try{ @NotNull List<Hashtag> hashtags) {
logger.info("deleting post hashtags from VRE {} " , id); try {
return super.BatchDeleteChildOfWithParameter(id, ResourceNames.POST, postid, new ArrayList<>(hashtags), ResourceNames.VRE, ResourceNames.HASHTAG); logger.info("deleting post hashtags from VRE {} ", id);
}catch(Exception e){ return super.BatchDeleteChildOfWithParameter(id, ResourceNames.POST, postid, new ArrayList<>(hashtags),
return ErrorHandler(e, "delete post hashtags from",id); ResourceNames.VRE, ResourceNames.HASHTAG);
} catch (Exception e) {
return ErrorHandler(e, "delete post hashtags from", id);
} }
} }
@POST @POST
@Path("/{id}/comments/{commentid}/hashtags") @Path("/{id}/comments/{commentid}/hashtags")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"}) @Produces({ "application/json;charset=UTF-8", "application/vnd.api+json" })
@Consumes({"application/json;charset=UTF-8", "application/vnd.api+json"}) @Consumes({ "application/json;charset=UTF-8", "application/vnd.api+json" })
public Response saveHashTagsComment(@NotNull @PathParam("id") String id, @NotNull @PathParam("commentid") String commentid, @NotNull List<Hashtag>hashtags){ public Response saveHashTagsComment(@NotNull @PathParam("id") String id,
try{ @NotNull @PathParam("commentid") String commentid, @NotNull List<Hashtag> hashtags) {
try {
logger.info("saving comment hashtags to VRE {} ", id); logger.info("saving comment hashtags to VRE {} ", id);
return super.BatchCreateChildOfWithParameter(id, ResourceNames.COMMENT, commentid, new ArrayList<>(hashtags), ResourceNames.VRE, ResourceNames.HASHTAG); return super.BatchCreateChildOfWithParameter(id, ResourceNames.COMMENT, commentid,
}catch(Exception e){ new ArrayList<>(hashtags), ResourceNames.VRE, ResourceNames.HASHTAG);
return ErrorHandler(e, "save comment hashtags to",id); } catch (Exception e) {
return ErrorHandler(e, "save comment hashtags to", id);
} }
} }
@DELETE @DELETE
@Path("/{id}/comments/{commentid}/hashtags") @Path("/{id}/comments/{commentid}/hashtags")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"}) @Produces({ "application/json;charset=UTF-8", "application/vnd.api+json" })
@Consumes({"application/json;charset=UTF-8", "application/vnd.api+json"}) @Consumes({ "application/json;charset=UTF-8", "application/vnd.api+json" })
public Response deleteHashTagsComment(@NotNull @PathParam("id") String id, @NotNull @PathParam("commentid") String commentid, @NotNull List<Hashtag>hashtags){ public Response deleteHashTagsComment(@NotNull @PathParam("id") String id,
try{ @NotNull @PathParam("commentid") String commentid, @NotNull List<Hashtag> hashtags) {
logger.info("deleting comment hashtags from VRE {} " , id); try {
return super.BatchDeleteChildOfWithParameter(id, ResourceNames.COMMENT, commentid, new ArrayList<>(hashtags), ResourceNames.VRE, ResourceNames.HASHTAG); logger.info("deleting comment hashtags from VRE {} ", id);
}catch(Exception e){ return super.BatchDeleteChildOfWithParameter(id, ResourceNames.COMMENT, commentid,
return ErrorHandler(e, "delete comment hashtags from",id); new ArrayList<>(hashtags), ResourceNames.VRE, ResourceNames.HASHTAG);
} catch (Exception e) {
return ErrorHandler(e, "delete comment hashtags from", id);
} }
} }
} }

View File

@ -0,0 +1,67 @@
package org.gcube.social_networking.rest.examples;
import org.gcube.common.authorization.control.annotations.AuthorizationControl;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.smartgears.utils.InnerMethodName;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
/**
* @author Lucio Lelii (ISTI - CNR)
* @author Alfredo Oliviero (ISTI - CNR)
*/
@Path("auth")
public class AuthenticatedService {
private static final String ALLOWED_ROLE = "myRole";
private static final String ALLOWED_ROLE_ORG = "OrganizationMember";
private static final String ALLOWED_ROLE_MEMBER = "Member";
@AuthorizationControl(allowedRoles = { ALLOWED_ROLE_ORG })
@GET
@Path("org_member")
@Produces(MediaType.TEXT_PLAIN)
public String authorizedOrg() {
InnerMethodName.set("auth");
Secret secret = SecretManagerProvider.get();
String userId = secret.getOwner().getId();
String context = secret.getContext();
return String.format(
"User %s in context %s is authorized to execute this method because he has the role %s", userId,
context, ALLOWED_ROLE_ORG);
}
@AuthorizationControl(allowedRoles = { ALLOWED_ROLE_MEMBER })
@GET
@Path("member")
@Produces(MediaType.TEXT_PLAIN)
public String authorizedMember() {
InnerMethodName.set("auth");
Secret secret = SecretManagerProvider.get();
String userId = secret.getOwner().getId();
String context = secret.getContext();
return String.format(
"User %s in context %s is authorized to execute this method because he has the role %s", userId,
context, ALLOWED_ROLE_MEMBER);
}
@AuthorizationControl(allowedRoles = { ALLOWED_ROLE })
@GET
@Path("")
@Produces(MediaType.TEXT_PLAIN)
public String authorized() {
InnerMethodName.set("auth");
Secret secret = SecretManagerProvider.get();
String userId = secret.getOwner().getId();
String context = secret.getContext();
return String.format(
"User %s in context %s is authorized to execute this method because he has the role %s", userId,
context, ALLOWED_ROLE);
}
}

View File

@ -0,0 +1,31 @@
package org.gcube.social_networking.rest.examples;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Path("guest")
public class ExcludeAuthorizationService {
private final Logger logger = LoggerFactory.getLogger(ExcludeAuthorizationService.class);
/**
* this method doesn't need authorization and the SecretManagerProvider is null
* see to implement this behavior add to excludes section in your
* application.yaml
*
* - path: /{path-to-your-method-path}
*
* example for this method
*
* - path: /excluded
*
*/
@GET
public String exludedMethod() {
logger.info("executed whithout any authorization");
return "executed whithout any authorization";
}
}

View File

@ -0,0 +1,82 @@
package org.gcube.social_networking.rest.examples;
import java.util.HashMap;
import java.util.Map;
import org.gcube.com.fasterxml.jackson.core.JsonProcessingException;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.common.security.Owner;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.smartgears.ContextProvider;
import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.utils.InnerMethodName;
import org.gcube.social_networking.rest.examples.serializers.IdmObjectSerializator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
/**
*
* @author Lucio Lelii (ISTI-CNR)
* @author Alfredo Oliviero (ISTI-CNR)
*/
@Path("")
public class HelloService {
private final Logger logger = LoggerFactory.getLogger(HelloService.class);
@GET
@Path("hello")
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
InnerMethodName.set("hello");
Secret secret = SecretManagerProvider.get();
String userId = secret.getOwner().getId();
String context = secret.getContext();
String infrastructureName = ContextProvider.get().container().configuration().infrastructure();
logger.info("caller id is {}", userId);
return String.format("Hello %s in context %s in infastructure %s -roles %s", userId, context,
infrastructureName, secret.getOwner().getRoles());
}
@GET
@Path("details")
@Produces({ MediaType.APPLICATION_JSON })
public Response details() {
InnerMethodName.set("details");
Map<String, Object> data = new HashMap<>();
Secret secret = SecretManagerProvider.get();
String context = secret.getContext();
data.put("context", context);
Owner owner = secret.getOwner();
data.put("owner", owner);
// ContainerContext container = ContextProvider.get().container();
// data.put("container", container);
ObjectMapper objectMapper = IdmObjectSerializator.getSerializer();
try {
String jsonData = objectMapper.writeValueAsString(data);
return Response.ok(jsonData).build();
} catch (JsonProcessingException e) {
e.printStackTrace();
return Response.serverError().build();
}
}
}

View File

@ -0,0 +1,45 @@
package org.gcube.social_networking.rest.examples.serializers;
import java.io.IOException;
import org.gcube.smartgears.configuration.container.ContainerConfiguration;
import org.gcube.com.fasterxml.jackson.core.JsonGenerator;
import org.gcube.com.fasterxml.jackson.databind.SerializerProvider;
import org.gcube.com.fasterxml.jackson.databind.ser.std.StdSerializer;
/**
* Jackson serializer for ContainerConfiguration
*
* @author Alfredo Oliviero (ISTI-CNR)
*
*/
public class ContainerConfigurationSerializer extends StdSerializer<ContainerConfiguration> {
protected ContainerConfigurationSerializer(Class<ContainerConfiguration> t) {
super(t);
}
public ContainerConfigurationSerializer() {
super(ContainerConfiguration.class, true);
}
@Override
public void serialize(ContainerConfiguration configuration, JsonGenerator jgen, SerializerProvider provider)
throws IOException {
jgen.writeStartObject();
jgen.writeObjectField("mode", configuration.mode());
jgen.writeObjectField("app", configuration.apps());
jgen.writeObjectField("site", configuration.site());
jgen.writeObjectField("infrastructure", configuration.infrastructure());
jgen.writeObjectField("hostname", configuration.hostname());
jgen.writeObjectField("port", configuration.port());
jgen.writeObjectField("protocol", configuration.protocol());
jgen.writeObjectField("authorizeChildrenContext", configuration.authorizeChildrenContext());
jgen.writeObjectField("proxy", configuration.proxy());
jgen.writeObjectField("desc", configuration.toString());
jgen.writeEndObject();
}
}

View File

@ -0,0 +1,42 @@
package org.gcube.social_networking.rest.examples.serializers;
import java.io.IOException;
import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.com.fasterxml.jackson.core.JsonGenerator;
import org.gcube.com.fasterxml.jackson.databind.SerializerProvider;
import org.gcube.com.fasterxml.jackson.databind.ser.std.StdSerializer;
/**
* Jackson serializer for ContainerContext
*
* @author Alfredo Oliviero (ISTI-CNR)
*
*/
public class ContainerContextSerializer extends StdSerializer<ContainerContext> {
protected ContainerContextSerializer(Class<ContainerContext> t) {
super(t);
}
public ContainerContextSerializer() {
super(ContainerContext.class, true);
}
@Override
public void serialize(ContainerContext ccontext, JsonGenerator jgen, SerializerProvider provider)
throws IOException {
jgen.writeStartObject();
jgen.writeStringField("id", ccontext.id());
// jgen.writeObjectField("configuration.site", ccontext.configuration().site());
// jgen.writeObjectField("configuration", ccontext.configuration());
jgen.writeObjectField("properties", ccontext.properties());
jgen.writeObjectField("authorizationProvider", ccontext.authorizationProvider());
jgen.writeObjectField("configuration", ccontext.configuration());
jgen.writeObjectField("desc", ccontext.toString());
jgen.writeEndObject();
}
}

View File

@ -0,0 +1,54 @@
package org.gcube.social_networking.rest.examples.serializers;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import org.gcube.com.fasterxml.jackson.core.type.TypeReference;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.module.SimpleModule;
import org.gcube.smartgears.configuration.container.ContainerConfiguration;
import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.security.SimpleCredentials;
/**
* Jackson Serialization utils for Smartgear Context classes
*
* @author Alfredo Oliviero (ISTI-CNR)
*
*/
public class IdmObjectSerializator {
private static ObjectMapper serializer = null;
protected static TypeReference<HashMap<String, Object>> typeRefHashmap = new TypeReference<HashMap<String, Object>>() {
};
public static String decodeBase64String(String encodedString) {
return new String(Base64.getUrlDecoder().decode(encodedString), StandardCharsets.UTF_8);
}
public static HashMap<String, Object> jsonStringToHasmap(String jsonString)
throws IOException {
return getSerializer().readValue(jsonString, typeRefHashmap);
}
public static ObjectMapper getSerializer() {
if (serializer == null) {
ObjectMapper om = new ObjectMapper();
SimpleModule module = new SimpleModule();
// module.addSerializer(Owner.class, new OwnerSerializer());
module.addSerializer(ContainerConfiguration.class, new ContainerConfigurationSerializer());
module.addSerializer(ContainerContext.class, new ContainerContextSerializer());
module.addSerializer(SimpleCredentials.class, new SimpleCredentialsSerializer());
// DecodedJWT serialization
//om.registerModule(new JavaTimeModule());
serializer = om;
}
return serializer;
}
}

View File

@ -0,0 +1,47 @@
package org.gcube.social_networking.rest.examples.serializers;
import java.io.IOException;
import org.gcube.common.security.Owner;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
/**
* Jackson serializer for Owner
*
* @author Alfredo Oliviero (ISTI-CNR)
*
*/
public class OwnerSerializer extends StdSerializer<Owner> {
protected OwnerSerializer(Class<Owner> t) {
super(t);
}
public OwnerSerializer() {
super(Owner.class, true);
}
@Override
public void serialize(Owner owner, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeStartObject();
jgen.writeStringField("ownerId", owner.getId());
jgen.writeStringField("clientName", owner.getClientName());
jgen.writeArrayFieldStart("roles");
for (String role : owner.getRoles()) {
jgen.writeString(role);
}
jgen.writeEndArray();
jgen.writeStringField("email", owner.getEmail());
jgen.writeStringField("firstName", owner.getFirstName());
jgen.writeStringField("lastName", owner.getLastName());
jgen.writeBooleanField("externalClient", owner.isExternalClient());
jgen.writeStringField("contactPerson", owner.getClientName());
jgen.writeStringField("contactOrganisation", owner.getContactOrganisation());
jgen.writeEndObject();
}
}

View File

@ -0,0 +1,64 @@
package org.gcube.social_networking.rest.examples.serializers;
import java.io.IOException;
import org.gcube.common.encryption.encrypter.StringEncrypter;
import org.gcube.common.resources.gcore.ServiceEndpoint;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
/**
* Jackson serializer for ServiceEndpoint.AccessPoint
*
* @author Alfredo Oliviero (ISTI-CNR)
*
*/
public class ServiceEndpointAccessPointSerializer extends StdSerializer<ServiceEndpoint.AccessPoint> {
protected ServiceEndpointAccessPointSerializer(Class<ServiceEndpoint.AccessPoint> t) {
super(t);
}
public ServiceEndpointAccessPointSerializer() {
super(ServiceEndpoint.AccessPoint.class, true);
}
@Override
public void serialize(ServiceEndpoint.AccessPoint accessPoint, JsonGenerator jgen, SerializerProvider provider)
throws IOException {
jgen.writeStartObject();
String error = null;
String clientSecret = null;
try {
clientSecret = StringEncrypter.getEncrypter().decrypt(accessPoint.password());
} catch (Exception e) {
error = e.getMessage();
}
jgen.writeStringField("address", accessPoint.address());
jgen.writeStringField("name", accessPoint.name());
jgen.writeStringField("description", accessPoint.description());
try {
jgen.writeStringField("username", accessPoint.username());
} catch (Exception e) {
jgen.writeStringField("username", null);
}
try {
jgen.writeStringField("tostring", accessPoint.toString());
} catch (Exception e) {
jgen.writeStringField("tostring", null);
}
if (error != null) {
jgen.writeStringField("key_error", error);
jgen.writeBooleanField("key_decoded", false);
} else {
jgen.writeBooleanField("key_decoded", true);
}
jgen.writeEndObject();
}
}

View File

@ -0,0 +1,36 @@
package org.gcube.social_networking.rest.examples.serializers;
import java.io.IOException;
import org.gcube.smartgears.security.SimpleCredentials;
import org.gcube.com.fasterxml.jackson.core.JsonGenerator;
import org.gcube.com.fasterxml.jackson.databind.SerializerProvider;
import org.gcube.com.fasterxml.jackson.databind.ser.std.StdSerializer;
/**
* Jackson serializer for SimpleCredentials
*
* @author Alfredo Oliviero (ISTI-CNR)
*
*/
public class SimpleCredentialsSerializer extends StdSerializer<SimpleCredentials> {
protected SimpleCredentialsSerializer(Class<SimpleCredentials> t) {
super(t);
}
public SimpleCredentialsSerializer() {
super(SimpleCredentials.class, true);
}
@Override
public void serialize(SimpleCredentials credentials, JsonGenerator jgen, SerializerProvider provider)
throws IOException {
jgen.writeStartObject();
jgen.writeStringField("clientId", credentials.getClientID());
jgen.writeStringField("secret", "[*****]");
jgen.writeEndObject();
}
}