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>
<groupId>org.gcube.social_networking</groupId>
<artifactId>social-service</artifactId>
<version>1.0.0-SNAPSHOT</version>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Social Service</name>
<description>This is the social service</description>
<properties>
<java.version>11</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<!-- OPTIONAL. for authorization-control-library -->
<aspectj-plugin.version>1.14.0</aspectj-plugin.version>
<webappDirectory>
${project.basedir}${file.separator}src${file.separator}main${file.separator}webapp${file.separator}WEB-INF</webappDirectory>
<enunciate.version>2.14.0</enunciate.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>
<scm>
@ -112,7 +121,15 @@
<version>2.6</version>
</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>
@ -133,7 +150,16 @@
<version>${enunciate.version}</version>
<scope>provided</scope>
</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 -->
<!-- Test libraries -->
@ -150,10 +176,6 @@
</dependency>
<!-- https://mvnrepository.com/artifact/jakarta.mail/jakarta.mail-api -->
<dependency>
<groupId>jakarta.mail</groupId>
@ -166,7 +188,7 @@
<artifactId>ehcache</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>org.gcube.dvos</groupId>
<artifactId>usermanagement-core</artifactId>
@ -186,13 +208,18 @@
<artifactId>jakarta.servlet-api</artifactId>
<version>4.0.4</version>
</dependency>
<dependency>
<groupId>org.gcube.idm</groupId>
<artifactId>idm-common-library</artifactId>
<version>0.0.2-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-cdi2-se</artifactId>
</dependency>
</dependencies>
<build>
@ -249,6 +276,34 @@
</configuration>
</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>
</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;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.smartgears.ApplicationManager;
import org.gcube.smartgears.ContextProvider;
import org.gcube.smartgears.configuration.Mode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
* @author Ahmed Ibrahim
*/
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}
*/
@Override
public synchronized void onInit() {
logger.info("Starting social service");
try{
String context = SecretManagerProvider.get().getContext();
logger.info(
"\n-------------------------------------------------------\n"
+ "Social Service is Starting on context {}\n"
+ "-------------------------------------------------------",
context);
}catch (Throwable e) {
logger.error("unexpected error initiliazing storagehub",e);
public void onInit() {
if (ContextProvider.get().container().configuration().mode() == Mode.offline) {
logger.debug("init called in offline mode");
} else {
Secret secret = SecretManagerProvider.get();
if (secret != null) {
logger.debug("init called in context {}", secret.getContext());
} else {
logger.debug("init called in null context");
}
}
// ApplicationContext applicationContext = ContextProvider.get();
// String helloWorldEServiceID = applicationContext.id();
}
/**
* {@inheritDoc}
/**
* {@inheritDoc}
*/
@Override
public synchronized void onShutdown(){
String context = SecretManagerProvider.get().getContext();
logger.trace(
"\n-------------------------------------------------------\n"
+ "Hello World Service is Stopping on context {}\n"
+ "-------------------------------------------------------",
context);
logger.trace(
"\n-------------------------------------------------------\n"
+ "Hello World Service Stopped Successfully on context {}\n"
+ "-------------------------------------------------------",
context);
public void onShutdown() {
if (ContextProvider.get().container().configuration().mode() == Mode.offline) {
logger.debug("shutDown called in offline mode");
} else {
Secret secret = SecretManagerProvider.get();
if (secret != null) {
logger.debug("shutDown called in context {}", secret.getContext());
} else {
logger.debug("shutDown called in null 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.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.RequestHeaders;
import com.webcohesion.enunciate.metadata.rs.ResourceGroup;
import com.webcohesion.enunciate.metadata.rs.ResourceLabel;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Path("/test")
@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>")
@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 TestRest {
@GET
@Path("/test")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"})
public String test(){
return "{\"result\":\"funziona!!!\"}";
@Produces({ MediaType.APPLICATION_JSON })
public Response test() {
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")
@ResourceLabel("Attachments 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>")
@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 {
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<>();
Response.Status status;
logger.info("Unable to "+action+" attachment {}.", id);
logger.info("Unable to " + action + " attachment {}.", id);
logger.info(e.getMessage());
responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false);
@ -36,15 +36,15 @@ public class Attachments extends Collection {
}
@POST
@Path("/")
@Path("")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createAttachment(Attachment attachment) {
try{
try {
logger.info("Creating attachment with id {}.", attachment.getId());
return super.create(attachment);
}catch(Exception e){
return ErrorHandler(e, "create",attachment.getId());
} catch (Exception e) {
return ErrorHandler(e, "create", attachment.getId());
}
}
@ -52,11 +52,11 @@ public class Attachments extends Collection {
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response readAttachment(@NotNull @PathParam("id") String id) {
try{
try {
logger.info("Reading attachment with id {}.", id);
return super.read(id, ResourceNames.Attachment);
}catch(Exception e){
return ErrorHandler(e, "fetch",id);
} catch (Exception e) {
return ErrorHandler(e, "fetch", id);
}
}
@ -64,11 +64,11 @@ public class Attachments extends Collection {
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteAttachment(@NotNull @PathParam("id") String id) {
try{
try {
logger.info("Deleting attachment with id {}.", id);
return super.delete(id,ResourceNames.Attachment);
}catch(Exception e){
return ErrorHandler(e, "delete",id);
return super.delete(id, ResourceNames.Attachment);
} catch (Exception e) {
return ErrorHandler(e, "delete", id);
}
}
@ -77,11 +77,11 @@ public class Attachments extends Collection {
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updateAttachment(@NotNull @PathParam("id") String id, @NotNull Attachment attachment) {
try{
try {
logger.info("Updating attachment with id {}", id);
return super.update(id, attachment);
}catch(Exception e){
return ErrorHandler(e, "update",id);
} catch (Exception e) {
return ErrorHandler(e, "update", id);
}
}
}

View File

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

View File

@ -17,20 +17,20 @@ import jakarta.ws.rs.core.GenericType;
import jakarta.ws.rs.core.Response;
import java.util.*;
@Path("vres")
@ResourceGroup("Vres APIs")
@ResourceLabel("Vres 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>")
@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 {
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<>();
Response.Status status;
logger.info("Unable to "+action+" vre {}.", id);
logger.info("Unable to " + action + " vre {}.", id);
logger.info(e.getMessage());
responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false);
@ -38,193 +38,219 @@ public class Vres extends Collection {
return Response.status(status).entity(responseBean).build();
}
@GET
@Path("/{id}/posts")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"})
public Response getAllPostsByVre(@NotNull @PathParam("id") String id){
try{
logger.info("Getting all posts of VRE: " + id);
return super.readChildOf(id, ResourceNames.VRE, ResourceNames.POST);
}catch(Exception e){
return ErrorHandler(e, "fetch posts of",id);
}
}
// @GET
// @Path("/{id}/posts")
// @Produces({ "application/json;charset=UTF-8", "application/vnd.api+json" })
// public Response getAllPostsByVre(@NotNull @PathParam("id") String id) {
// try {
// logger.info("Getting all posts of VRE: " + id);
// return super.readChildOf(id, ResourceNames.VRE, ResourceNames.POST);
// } catch (Exception e) {
// return ErrorHandler(e, "fetch posts of", id);
// }
// }
@GET
@Path("/")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"})
public Response getAllVreIds(){
try{
@Produces({ "application/json;charset=UTF-8", "application/vnd.api+json" })
public Response getAllVreIds() {
try {
logger.info("Getting all VRE IDs");
List<String> ids = new ArrayList<>();
List<Vre> vres = super.readAll(ResourceNames.VRE).readEntity(new GenericType<ResponseBean<List<Vre>>>(){}).getResult();
for(Vre vre: vres){
List<Vre> vres = super.readAll(ResourceNames.VRE).readEntity(new GenericType<ResponseBean<List<Vre>>>() {
}).getResult();
for (Vre vre : vres) {
ids.add(vre.getId());
}
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.setSuccess(true);
responseBean.setResult(ids);
return Response.status(status).entity(responseBean).build();
}catch(Exception e){
return ErrorHandler(e, "fetch ids of","");
} catch (Exception e) {
return ErrorHandler(e, "fetch ids of", "");
}
}
// TODO: verificare limit null
@GET
@Path("/{id}/posts")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"})
public Response getRecentPostsByVre(@NotNull @PathParam("id") String id, @QueryParam("limit") @DefaultValue("10") int limit){
try{
logger.info("Getting most recent {} posts of VRE {} " , limit, id);
return super.readChildOfWithParameter(id, ParameterNames.RECENT_LIMIT, String.valueOf(limit), ResourceNames.VRE, ResourceNames.POST);
}catch(Exception e){
return ErrorHandler(e, "fetch recent posts of",id);
@Produces({ "application/json;charset=UTF-8", "application/vnd.api+json" })
public Response getRecentPostsByVre(@NotNull @PathParam("id") String id,
@QueryParam("limit") Integer limit) {
try {
logger.info("Getting most recent {} posts of VRE {} ", limit, id);
if (limit != null)
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
@Path("/{id}/posts")
@Produces({"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){
try{
logger.info("saving post {} to VRE {} " , post.getKey(), id);
@Produces({ "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) {
try {
logger.info("saving post {} to VRE {} ", post.getKey(), id);
return super.createChildOf(id, post, ResourceNames.VRE);
}catch(Exception e){
return ErrorHandler(e, "save post to",id);
} catch (Exception e) {
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
@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);
}
}
@GET
@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);
@Produces({ "application/json;charset=UTF-8", "application/vnd.api+json" })
public Response getVREHashtagsWithOccurrenceFilteredByTime(@NotNull @PathParam("id") String id,
@QueryParam("time") Long timestamp) {
try {
logger.info("getting hashtags of VRE {} starting {} ", id, timestamp);
if (timestamp == null) {
return super.readChildOf(id, ResourceNames.VRE, ResourceNames.HASHTAG);
}
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
@Path("/{id}/hashtags/{hashtag}/posts")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"})
public Response getVREPostsByHashtag(@NotNull @PathParam("id") String id, @NotNull @PathParam("hashtag") String hashtag){
try{
logger.info("getting posts containing hashtags in VRE {}" , id);
return super.readChildOfWithParameter(id, ParameterNames.HASHTAG, hashtag, ResourceNames.VRE, ResourceNames.POST);
}catch(Exception e){
return ErrorHandler(e, "get posts containing hashtag in",id);
@Produces({ "application/json;charset=UTF-8", "application/vnd.api+json" })
public Response getVREPostsByHashtag(@NotNull @PathParam("id") String id,
@NotNull @PathParam("hashtag") String hashtag) {
try {
logger.info("getting posts containing hashtags in VRE {}", id);
return super.readChildOfWithParameter(id, ParameterNames.HASHTAG, hashtag, ResourceNames.VRE,
ResourceNames.POST);
} catch (Exception e) {
return ErrorHandler(e, "get posts containing hashtag in", id);
}
}
@GET
@Path("/{id}/invites/")
@Produces({"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){
try{
logger.info("getting invites in VRE {}" , id);
return super.readChildOfWithParameter(id, ParameterNames.STATUS, Arrays.toString(status), ResourceNames.VRE, ResourceNames.INVITE);
}catch(Exception e){
return ErrorHandler(e, "get invites in",id);
@Produces({ "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) {
try {
logger.info("getting invites in VRE {}", id);
return super.readChildOfWithParameter(id, ParameterNames.STATUS, Arrays.toString(status), ResourceNames.VRE,
ResourceNames.INVITE);
} catch (Exception e) {
return ErrorHandler(e, "get invites in", id);
}
}
@GET
@Path("/{id}/invites/{email}")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"})
public Response isExistingInvite(@NotNull @PathParam("id") String id, @NotNull @PathParam("email")String email){
try{
logger.info("checking if invite {} exists in VRE {}" , email, id);
return super.readChildOfWithParameter(id, ParameterNames.EMAIL, email, ResourceNames.VRE, ResourceNames.INVITE);
}catch(Exception e){
return ErrorHandler(e, "check invite in",id);
@Produces({ "application/json;charset=UTF-8", "application/vnd.api+json" })
public Response isExistingInvite(@NotNull @PathParam("id") String id, @NotNull @PathParam("email") String email) {
try {
logger.info("checking if invite {} exists in VRE {}", email, id);
return super.readChildOfWithParameter(id, ParameterNames.EMAIL, email, ResourceNames.VRE,
ResourceNames.INVITE);
} catch (Exception e) {
return ErrorHandler(e, "check invite in", id);
}
}
@PUT
@Path("/{id}/invites/{email}")
@Produces({"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){
try{
logger.info("setting invite {} status in VRE {}" , email, id);
@Produces({ "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) {
try {
logger.info("setting invite {} status in VRE {}", email, id);
Invite invite = new Invite();
invite.setStatus(inviteStatus);
return super.updateChildOfWithParameter(id, ParameterNames.EMAIL, email, invite, ResourceNames.VRE);
}catch(Exception e){
return ErrorHandler(e, "set invite status in",id);
} catch (Exception e) {
return ErrorHandler(e, "set invite status in", id);
}
}
@POST
@Path("/{id}/posts/{postid}/hashtags")
@Produces({"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){
try{
@Produces({ "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) {
try {
logger.info("saving post hashtags to VRE {} ", id);
return super.BatchCreateChildOfWithParameter(id, ResourceNames.POST, postid, new ArrayList<>(hashtags), ResourceNames.VRE, ResourceNames.HASHTAG);
}catch(Exception e){
return ErrorHandler(e, "save post hashtags to",id);
return super.BatchCreateChildOfWithParameter(id, ResourceNames.POST, postid, new ArrayList<>(hashtags),
ResourceNames.VRE, ResourceNames.HASHTAG);
} catch (Exception e) {
return ErrorHandler(e, "save post hashtags to", id);
}
}
@DELETE
@Path("/{id}/posts/{postid}/hashtags")
@Produces({"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){
try{
logger.info("deleting post hashtags from VRE {} " , id);
return super.BatchDeleteChildOfWithParameter(id, ResourceNames.POST, postid, new ArrayList<>(hashtags), ResourceNames.VRE, ResourceNames.HASHTAG);
}catch(Exception e){
return ErrorHandler(e, "delete post hashtags from",id);
@Produces({ "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) {
try {
logger.info("deleting post hashtags from VRE {} ", id);
return super.BatchDeleteChildOfWithParameter(id, ResourceNames.POST, postid, new ArrayList<>(hashtags),
ResourceNames.VRE, ResourceNames.HASHTAG);
} catch (Exception e) {
return ErrorHandler(e, "delete post hashtags from", id);
}
}
@POST
@Path("/{id}/comments/{commentid}/hashtags")
@Produces({"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){
try{
@Produces({ "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) {
try {
logger.info("saving comment hashtags to VRE {} ", id);
return super.BatchCreateChildOfWithParameter(id, ResourceNames.COMMENT, commentid, new ArrayList<>(hashtags), ResourceNames.VRE, ResourceNames.HASHTAG);
}catch(Exception e){
return ErrorHandler(e, "save comment hashtags to",id);
return super.BatchCreateChildOfWithParameter(id, ResourceNames.COMMENT, commentid,
new ArrayList<>(hashtags), ResourceNames.VRE, ResourceNames.HASHTAG);
} catch (Exception e) {
return ErrorHandler(e, "save comment hashtags to", id);
}
}
@DELETE
@Path("/{id}/comments/{commentid}/hashtags")
@Produces({"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){
try{
logger.info("deleting comment hashtags from VRE {} " , id);
return super.BatchDeleteChildOfWithParameter(id, ResourceNames.COMMENT, commentid, new ArrayList<>(hashtags), ResourceNames.VRE, ResourceNames.HASHTAG);
}catch(Exception e){
return ErrorHandler(e, "delete comment hashtags from",id);
@Produces({ "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) {
try {
logger.info("deleting comment hashtags from VRE {} ", id);
return super.BatchDeleteChildOfWithParameter(id, ResourceNames.COMMENT, commentid,
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();
}
}