source: ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/ComponentRegistryRestService.java @ 1604

Last change on this file since 1604 was 1604, checked in by twagoo, 13 years ago

Added parameter 'mdEditor' to REST call /registry/profiles which causes only selected profiles are shown. Implemented programmatic filtering on this, could be done on database which would be more efficient.

File size: 26.5 KB
Line 
1package clarin.cmdi.componentregistry.rest;
2
3import java.io.IOException;
4import java.io.InputStream;
5import java.io.OutputStream;
6import java.net.URI;
7import java.security.Principal;
8import java.util.ArrayList;
9import java.util.Arrays;
10import java.util.List;
11
12import javax.servlet.http.HttpServletRequest;
13import javax.ws.rs.Consumes;
14import javax.ws.rs.DELETE;
15import javax.ws.rs.DefaultValue;
16import javax.ws.rs.FormParam;
17import javax.ws.rs.GET;
18import javax.ws.rs.POST;
19import javax.ws.rs.Path;
20import javax.ws.rs.PathParam;
21import javax.ws.rs.Produces;
22import javax.ws.rs.QueryParam;
23import javax.ws.rs.WebApplicationException;
24import javax.ws.rs.core.Context;
25import javax.ws.rs.core.MediaType;
26import javax.ws.rs.core.Response;
27import javax.ws.rs.core.SecurityContext;
28import javax.ws.rs.core.StreamingOutput;
29import javax.ws.rs.core.UriInfo;
30import javax.ws.rs.core.Response.Status;
31
32import org.slf4j.Logger;
33import org.slf4j.LoggerFactory;
34
35import clarin.cmdi.componentregistry.ComponentRegistry;
36import clarin.cmdi.componentregistry.ComponentRegistryException;
37import clarin.cmdi.componentregistry.ComponentRegistryFactory;
38import clarin.cmdi.componentregistry.DeleteFailedException;
39import clarin.cmdi.componentregistry.UserCredentials;
40import clarin.cmdi.componentregistry.UserUnauthorizedException;
41import clarin.cmdi.componentregistry.components.CMDComponentSpec;
42import clarin.cmdi.componentregistry.model.AbstractDescription;
43import clarin.cmdi.componentregistry.model.ComponentDescription;
44import clarin.cmdi.componentregistry.model.ProfileDescription;
45import clarin.cmdi.componentregistry.model.RegisterResponse;
46
47import com.sun.jersey.multipart.FormDataParam;
48import com.sun.jersey.spi.inject.Inject;
49
50@Path("/registry")
51public class ComponentRegistryRestService {
52
53    @Context
54    private UriInfo uriInfo;
55    @Context
56    private SecurityContext security;
57    @Context
58    private HttpServletRequest request;
59    private final static Logger LOG = LoggerFactory.getLogger(ComponentRegistryRestService.class);
60    public static final String DATA_FORM_FIELD = "data";
61    public static final String NAME_FORM_FIELD = "name";
62    public static final String DESCRIPTION_FORM_FIELD = "description";
63    public static final String GROUP_FORM_FIELD = "group";
64    public static final String DOMAIN_FORM_FIELD = "domainName";
65    public static final String USERSPACE_PARAM = "userspace";
66    public static final String METADATA_EDITOR_PARAM = "mdEditor";
67    @Inject(value = "componentRegistryFactory")
68    private ComponentRegistryFactory componentRegistryFactory;
69
70    private ComponentRegistry getRegistry(boolean userspace) {
71        Principal userPrincipal = security.getUserPrincipal();
72        UserCredentials userCredentials = getUserCredentials(userPrincipal);
73        return getRegistry(userspace, userCredentials);
74    }
75
76    private ComponentRegistry getRegistry(boolean userspace, UserCredentials userCredentials) {
77        return componentRegistryFactory.getComponentRegistry(userspace, userCredentials);
78    }
79
80    private Principal checkAndGetUserPrincipal() {
81        Principal principal = security.getUserPrincipal();
82        if (principal == null) {
83            throw new IllegalArgumentException("no user principal found.");
84        }
85        return principal;
86    }
87
88    private UserCredentials getUserCredentials(Principal userPrincipal) {
89        UserCredentials userCredentials = null;
90        if (userPrincipal != null) {
91            userCredentials = new UserCredentials(userPrincipal);
92        }
93        return userCredentials;
94    }
95
96    @GET
97    @Path("/components")
98    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
99    public List<ComponentDescription> getRegisteredComponents(@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
100        long start = System.currentTimeMillis();
101        List<ComponentDescription> components = getRegistry(userspace).getComponentDescriptions();
102        LOG.info("Releasing " + components.size() + " registered components into the world (" + (System.currentTimeMillis() - start)
103                + " millisecs)");
104        return components;
105    }
106
107    @GET
108    @Path("/profiles")
109    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
110    public List<ProfileDescription> getRegisteredProfiles(@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace,
111            @QueryParam(METADATA_EDITOR_PARAM) @DefaultValue("false") boolean metadataEditor) throws ComponentRegistryException {
112        long start = System.currentTimeMillis();
113       
114        List<ProfileDescription> profiles;
115        if (metadataEditor) {
116            profiles = getRegistry(userspace).getProfileDescriptionsForMetadaEditor();
117        } else {
118            profiles = getRegistry(userspace).getProfileDescriptions();
119        }
120       
121        LOG.info("Releasing " + profiles.size() + " registered profiles into the world (" + (System.currentTimeMillis() - start)
122                + " millisecs)");
123        return profiles;
124    }
125
126    @GET
127    @Path("/components/{componentId}")
128    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
129    public CMDComponentSpec getRegisteredComponent(@PathParam("componentId") String componentId,
130            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
131        LOG.info("Component with id: " + componentId + " is requested.");
132        return getRegistry(userspace).getMDComponent(componentId);
133    }
134
135    @GET
136    @Path("/components/{componentId}/{rawType}")
137    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML})
138    public Response getRegisteredComponentRawType(@PathParam("componentId") final String componentId, @PathParam("rawType") String rawType) {
139        LOG.info("Component with id: " + componentId + " and rawType:" + rawType + " is requested.");
140        StreamingOutput result = null;
141        try {
142            final ComponentRegistry registry = findRegistry(componentId, new ComponentClosure());
143            if (registry == null) {
144                return Response.status(Status.NOT_FOUND).entity("Id: " + componentId + " is not registered, cannot create data.").build();
145            }
146            ComponentDescription desc = registry.getComponentDescription(componentId);
147            checkAndThrowDescription(desc, componentId);
148            String fileName = desc.getName() + "." + rawType;
149            if ("xml".equalsIgnoreCase(rawType)) {
150                result = new StreamingOutput() {
151
152                    @Override
153                    public void write(OutputStream output) throws IOException, WebApplicationException {
154                        try {
155                            registry.getMDComponentAsXml(componentId, output);
156                        } catch (ComponentRegistryException e) {
157                            LOG.info("Could not retrieve component", e);
158                            throw new WebApplicationException(e, Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
159                        }
160                    }
161                };
162            } else if ("xsd".equalsIgnoreCase(rawType)) {
163                result = new StreamingOutput() {
164
165                    @Override
166                    public void write(OutputStream output) throws IOException, WebApplicationException {
167                        try {
168                            registry.getMDComponentAsXsd(componentId, output);
169                        } catch (ComponentRegistryException e) {
170                            LOG.info("Could not retrieve component", e);
171                            throw new WebApplicationException(e, Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
172                        }
173
174                    }
175                };
176            } else {
177                throw new WebApplicationException(Response.serverError().entity(
178                        "unsupported rawType: " + rawType + " (only xml or xsd are supported)").build());
179            }
180            return createDownloadResponse(result, fileName);
181        } catch (ComponentRegistryException e) {
182            LOG.info("Could not retrieve component", e);
183            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
184        }
185    }
186
187    public ComponentRegistry findRegistry(String id, RegistryClosure<? extends AbstractDescription> clos) throws ComponentRegistryException {
188        AbstractDescription desc = null;
189        ComponentRegistry result = getRegistry(false);
190        desc = clos.getDescription(result, id);
191        if (desc == null) {
192            List<ComponentRegistry> userRegs = componentRegistryFactory.getAllUserRegistries();
193            for (ComponentRegistry reg : userRegs) {
194                desc = clos.getDescription(reg, id);
195                if (desc != null) {
196                    result = reg;
197                    break;
198                }
199            }
200        }
201        return result;
202    }
203
204    @GET
205    @Path("/profiles/{profileId}")
206    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
207    public CMDComponentSpec getRegisteredProfile(@PathParam("profileId") String profileId,
208            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
209        LOG.info("Profile with id: " + profileId + " is requested.");
210        return getRegistry(userspace).getMDProfile(profileId);
211    }
212
213    @GET
214    @Path("/components/usage/{componentId}")
215    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
216    public List<AbstractDescription> getComponentUsage(@PathParam("componentId") String componentId, @QueryParam(USERSPACE_PARAM) @DefaultValue("true") boolean userspace) throws ComponentRegistryException {
217        try {
218            final long start = System.currentTimeMillis();
219            ComponentRegistry registry = getRegistry(userspace);
220            List<ComponentDescription> components = registry.getUsageInComponents(componentId);
221            List<ProfileDescription> profiles = registry.getUsageInProfiles(componentId);
222
223            LOG.info("Found " + components.size() + " components and " + profiles.size() + " profiles that use component " + componentId
224                    + " (" + (System.currentTimeMillis() - start) + " millisecs)");
225
226            List<AbstractDescription> usages = new ArrayList<AbstractDescription>(components.size() + profiles.size());
227            usages.addAll(components);
228            usages.addAll(profiles);
229
230            return usages;
231        } catch (ComponentRegistryException e) {
232            LOG.info("Could not retrieve profile usage", e);
233            throw e;
234        }
235    }
236
237    /**
238     *
239     * Purely helper method for my front-end (FLEX) which only does post/get requests. The query param is checked and the "proper" method is
240     * called.
241     * @param profileId
242     * @param method
243     * @return
244     */
245    @POST
246    @Path("/profiles/{profileId}")
247    public Response manipulateRegisteredProfile(@PathParam("profileId") String profileId, @FormParam("method") String method,
248            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
249        if ("delete".equalsIgnoreCase(method)) {
250            return deleteRegisteredProfile(profileId, userspace);
251        } else {
252            return Response.ok().build();
253        }
254    }
255
256    @POST
257    @Path("/profiles/{profileId}/publish")
258    @Consumes("multipart/form-data")
259    public Response publishRegisteredProfile(@PathParam("profileId") String profileId, @FormDataParam(DATA_FORM_FIELD) InputStream input,
260            @FormDataParam(NAME_FORM_FIELD) String name, @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
261            @FormDataParam(GROUP_FORM_FIELD) String group, @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
262        Principal principal = checkAndGetUserPrincipal();
263        try {
264            ProfileDescription desc = getRegistry(true).getProfileDescription(profileId);
265            if (desc != null) {
266                updateDescription(desc, name, description, domainName, group);
267                return register(input, desc, getUserCredentials(principal), true, new PublishAction(principal));
268            } else {
269                LOG.error("Update of nonexistent id (" + profileId + ") failed.");
270                return Response.serverError().entity("Invalid id, cannot update nonexistent profile").build();
271            }
272        } catch (ComponentRegistryException e) {
273            LOG.info("Could not retrieve component", e);
274            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
275        }
276    }
277
278    @POST
279    @Path("/profiles/{profileId}/update")
280    @Consumes("multipart/form-data")
281    public Response updateRegisteredProfile(@PathParam("profileId") String profileId,
282            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace, @FormDataParam(DATA_FORM_FIELD) InputStream input,
283            @FormDataParam(NAME_FORM_FIELD) String name, @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
284            @FormDataParam(GROUP_FORM_FIELD) String group, @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
285        Principal principal = checkAndGetUserPrincipal();
286        UserCredentials userCredentials = getUserCredentials(principal);
287        try {
288            ProfileDescription desc = getRegistry(userspace).getProfileDescription(profileId);
289            if (desc != null) {
290                updateDescription(desc, name, description, domainName, group);
291                return register(input, desc, userCredentials, userspace, new UpdateAction(principal));
292            } else {
293                LOG.error("Update of nonexistent id (" + profileId + ") failed.");
294                return Response.serverError().entity("Invalid id, cannot update nonexistent profile").build();
295            }
296        } catch (ComponentRegistryException e) {
297            LOG.info("Could not retrieve component", e);
298            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
299        }
300    }
301
302    /**
303     *
304     * Purely helper method for my front-end (FLEX) which van only do post/get requests. The query param is checked and the "proper" method
305     * is called.
306     * @param componentId
307     * @param method
308     * @return
309     */
310    @POST
311    @Path("/components/{componentId}")
312    public Response manipulateRegisteredComponent(@PathParam("componentId") String componentId, @FormParam("method") String method,
313            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
314        if ("delete".equalsIgnoreCase(method)) {
315            return deleteRegisteredComponent(componentId, userspace);
316        } else {
317            return Response.ok().build();
318        }
319    }
320
321    @POST
322    @Path("/components/{componentId}/publish")
323    @Consumes("multipart/form-data")
324    public Response publishRegisteredComponent(@PathParam("componentId") String componentId,
325            @FormDataParam(DATA_FORM_FIELD) InputStream input, @FormDataParam(NAME_FORM_FIELD) String name,
326            @FormDataParam(DESCRIPTION_FORM_FIELD) String description, @FormDataParam(GROUP_FORM_FIELD) String group,
327            @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
328        Principal principal = checkAndGetUserPrincipal();
329        try {
330            ComponentDescription desc = getRegistry(true).getComponentDescription(componentId);
331            if (desc != null) {
332                updateDescription(desc, name, description, domainName, group);
333                return register(input, desc, getUserCredentials(principal), true, new PublishAction(principal));
334            } else {
335                LOG.error("Update of nonexistent id (" + componentId + ") failed.");
336                return Response.serverError().entity("Invalid id, cannot update nonexistent profile").build();
337            }
338        } catch (ComponentRegistryException e) {
339            LOG.info("Could not retrieve component", e);
340            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
341        }
342    }
343
344    @POST
345    @Path("/components/{componentId}/update")
346    @Consumes("multipart/form-data")
347    public Response updateRegisteredComponent(@PathParam("componentId") String componentId,
348            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace, @FormDataParam(DATA_FORM_FIELD) InputStream input,
349            @FormDataParam(NAME_FORM_FIELD) String name, @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
350            @FormDataParam(GROUP_FORM_FIELD) String group, @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
351        Principal principal = checkAndGetUserPrincipal();
352        try {
353            ComponentDescription desc = getRegistry(userspace).getComponentDescription(componentId);
354            if (desc != null) {
355                updateDescription(desc, name, description, domainName, group);
356                return register(input, desc, getUserCredentials(principal), userspace, new UpdateAction(principal));
357            } else {
358                LOG.error("Update of nonexistent id (" + componentId + ") failed.");
359                return Response.serverError().entity("Invalid id, cannot update nonexistent component").build();
360            }
361        } catch (ComponentRegistryException e) {
362            LOG.info("Could not retrieve component", e);
363            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
364        }
365    }
366
367    private void updateDescription(AbstractDescription desc, String name, String description, String domainName, String group) {
368        desc.setName(name);
369        desc.setDescription(description);
370        desc.setDomainName(domainName);
371        desc.setGroupName(group);
372        desc.setRegistrationDate(AbstractDescription.createNewDate());
373    }
374
375    @DELETE
376    @Path("/components/{componentId}")
377    public Response deleteRegisteredComponent(@PathParam("componentId") String componentId,
378            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
379        Principal principal = checkAndGetUserPrincipal();
380        ComponentRegistry registry = getRegistry(userspace);
381        LOG.info("Component with id: " + componentId + " set for deletion.");
382        try {
383            registry.deleteMDComponent(componentId, principal, false);
384        } catch (DeleteFailedException e) {
385            LOG.info("Component with id: " + componentId + " deletion failed.", e);
386            return Response.status(Status.FORBIDDEN).entity("" + e.getMessage()).build();
387        } catch (ComponentRegistryException e) {
388            LOG.info("Component with id: " + componentId + " deletion failed.", e);
389            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
390        } catch (IOException e) {
391            LOG.info("Component with id: " + componentId + " deletion failed.", e);
392            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
393        } catch (UserUnauthorizedException e) {
394            LOG.info("Component with id: " + componentId + " deletion failed: " + e.getMessage());
395            return Response.serverError().status(Status.UNAUTHORIZED).entity("" + e.getMessage()).build();
396        }
397        LOG.info("Component with id: " + componentId + " deleted.");
398        return Response.ok().build();
399    }
400
401    @DELETE
402    @Path("/profiles/{profileId}")
403    public Response deleteRegisteredProfile(@PathParam("profileId") String profileId,
404            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
405        Principal principal = checkAndGetUserPrincipal();
406        LOG.info("Profile with id: " + profileId + " set for deletion.");
407        try {
408            getRegistry(userspace).deleteMDProfile(profileId, principal);
409        } catch (DeleteFailedException e) {
410            LOG.info("Profile with id: " + profileId + " deletion failed: " + e.getMessage());
411            return Response.serverError().status(Status.FORBIDDEN).entity("" + e.getMessage()).build();
412        } catch (ComponentRegistryException e) {
413            LOG.info("Could not retrieve component", e);
414            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
415        } catch (IOException e) {
416            LOG.info("Profile with id: " + profileId + " deletion failed.", e);
417            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
418        } catch (UserUnauthorizedException e) {
419            LOG.info("Profile with id: " + profileId + " deletion failed: " + e.getMessage());
420            return Response.serverError().status(Status.UNAUTHORIZED).entity("" + e.getMessage()).build();
421        }
422        LOG.info("Profile with id: " + profileId + " deleted.");
423        return Response.ok().build();
424    }
425
426    @GET
427    @Path("/profiles/{profileId}/{rawType}")
428    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML})
429    public Response getRegisteredProfileRawType(@PathParam("profileId") final String profileId, @PathParam("rawType") String rawType) {
430        LOG.info("Profile with id: " + profileId + " and rawType:" + rawType + " is requested.");
431        StreamingOutput result = null;
432        try {
433            final ComponentRegistry registry = findRegistry(profileId, new ProfileClosure());
434            if (registry == null) {
435                return Response.status(Status.NOT_FOUND).entity("Id: " + profileId + " is not registered, cannot create data.").build();
436            }
437            ProfileDescription desc = registry.getProfileDescription(profileId);
438            checkAndThrowDescription(desc, profileId);
439            String fileName = desc.getName() + "." + rawType;
440
441            if ("xml".equalsIgnoreCase(rawType)) {
442                result = new StreamingOutput() {
443
444                    @Override
445                    public void write(OutputStream output) throws IOException, WebApplicationException {
446                        try {
447                            registry.getMDProfileAsXml(profileId, output);
448                        } catch (ComponentRegistryException e) {
449                            LOG.warn("Could not retrieve component", e);
450                            throw new WebApplicationException(e, Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
451                        }
452                    }
453                };
454            } else if ("xsd".equalsIgnoreCase(rawType)) {
455                result = new StreamingOutput() {
456
457                    @Override
458                    public void write(OutputStream output) throws IOException, WebApplicationException {
459                        try {
460                            registry.getMDProfileAsXsd(profileId, output);
461                        } catch (ComponentRegistryException e) {
462                            LOG.warn("Could not retrieve component", e);
463                            throw new WebApplicationException(e, Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
464                        }
465                    }
466                };
467            } else {
468                throw new WebApplicationException(Response.serverError().entity(
469                        "unsupported rawType: " + rawType + " (only xml or xsd are supported)").build());
470            }
471            return createDownloadResponse(result, fileName);
472        } catch (ComponentRegistryException e) {
473            LOG.info("Could not retrieve component", e);
474            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
475        }
476    }
477
478    private void checkAndThrowDescription(AbstractDescription desc, String id) {
479        if (desc == null) {
480            throw new WebApplicationException(Response.serverError().entity("Incorrect id:" + id + "cannot handle request").build());
481        }
482    }
483
484    private Response createDownloadResponse(StreamingOutput result, String fileName) {
485        //Making response so it triggers browsers native save as dialog.
486        Response response = Response.ok().type("application/x-download").header("Content-Disposition",
487                "attachment; filename=\"" + fileName + "\"").entity(result).build();
488        return response;
489
490    }
491
492    @POST
493    @Path("/profiles")
494    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
495    @Consumes("multipart/form-data")
496    public Response registerProfile(@FormDataParam(DATA_FORM_FIELD) InputStream input, @FormDataParam(NAME_FORM_FIELD) String name,
497            @FormDataParam(DESCRIPTION_FORM_FIELD) String description, @FormDataParam(GROUP_FORM_FIELD) String group, @FormDataParam(DOMAIN_FORM_FIELD) String domainName,
498            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
499        Principal principal = checkAndGetUserPrincipal();
500        UserCredentials userCredentials = getUserCredentials(principal);
501        ProfileDescription desc = createNewProfileDescription();
502        desc.setCreatorName(userCredentials.getDisplayName());
503        desc.setUserId(userCredentials.getPrincipalName()); // Hash used to be created here, now Id is constructed by impl
504        desc.setName(name);
505        desc.setDescription(description);
506        desc.setGroupName(group);
507        desc.setDomainName(domainName);
508        LOG.info("Trying to register Profile: " + desc);
509        return register(input, desc, userCredentials, userspace, new NewAction());
510    }
511
512    @POST
513    @Path("/components")
514    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
515    @Consumes("multipart/form-data")
516    public Response registerComponent(@FormDataParam(DATA_FORM_FIELD) InputStream input, @FormDataParam(NAME_FORM_FIELD) String name,
517            @FormDataParam(DESCRIPTION_FORM_FIELD) String description, @FormDataParam(GROUP_FORM_FIELD) String group,
518            @FormDataParam(DOMAIN_FORM_FIELD) String domainName, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
519        Principal principal = checkAndGetUserPrincipal();
520        UserCredentials userCredentials = getUserCredentials(principal);
521        ComponentDescription desc = createNewComponentDescription();
522        desc.setCreatorName(userCredentials.getDisplayName());
523        desc.setUserId(userCredentials.getPrincipalName()); // Hash used to be created here, now Id is constructed by impl
524        desc.setName(name);
525        desc.setDescription(description);
526        desc.setGroupName(group);
527        desc.setDomainName(domainName);
528        LOG.info("Trying to register Component: " + desc);
529        return register(input, desc, userCredentials, userspace, new NewAction());
530    }
531
532    @GET
533    @Path("/pingSession")
534    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
535    public Response pingSession() {
536        boolean stillActive = false;
537        Principal userPrincipal = security.getUserPrincipal();
538        LOG.info("ping by user: " + (userPrincipal == null ? "null" : userPrincipal.getName()));
539        if (request != null) {
540            if (userPrincipal != null && !ComponentRegistryFactory.ANONYMOUS_USER.equals(userPrincipal.getName())) {
541                stillActive = !((HttpServletRequest) request).getSession().isNew();
542            }
543        }
544        return Response.ok().entity("<session stillActive=\"" + stillActive + "\"/>").build();
545    }
546
547    private Response register(InputStream input, AbstractDescription desc, UserCredentials userCredentials, boolean userspace,
548            RegisterAction action) {
549        try {
550            ComponentRegistry registry = getRegistry(userspace, userCredentials);
551            DescriptionValidator descriptionValidator = new DescriptionValidator(desc);
552            MDValidator validator = new MDValidator(input, desc, registry, getRegistry(true), componentRegistryFactory.getPublicRegistry());
553            RegisterResponse response = new RegisterResponse();
554            response.setIsInUserSpace(userspace);
555            validate(response, descriptionValidator, validator);
556            if (response.getErrors().isEmpty()) {
557                CMDComponentSpec spec = validator.getCMDComponentSpec();
558                int returnCode = action.execute(desc, spec, response, registry);
559                if (returnCode == 0) {
560                    response.setRegistered(true);
561                    response.setDescription(desc);
562                } else {
563                    response.setRegistered(false);
564                    response.addError("Unable to register at this moment. Internal server error.");
565                }
566            } else {
567                LOG.info("Registration failed with validation errors:" + Arrays.toString(response.getErrors().toArray()));
568                response.setRegistered(false);
569            }
570            response.setIsProfile(desc.isProfile());
571            return Response.ok(response).build();
572        } finally {
573            try {
574                input.close();//either we read the input or there was an exception, we need to close it.
575            } catch (IOException e) {
576                LOG.error("Error when closing inputstream: ", e);
577            }
578        }
579    }
580
581    private ComponentDescription createNewComponentDescription() {
582        ComponentDescription desc = ComponentDescription.createNewDescription();
583        desc.setHref(createXlink(desc.getId()));
584        return desc;
585    }
586
587    private ProfileDescription createNewProfileDescription() {
588        ProfileDescription desc = ProfileDescription.createNewDescription();
589        desc.setHref(createXlink(desc.getId()));
590        return desc;
591    }
592
593    private String createXlink(String id) {
594        URI uri = uriInfo.getRequestUriBuilder().path(id).build();
595        return uri.toString();
596    }
597
598    private void validate(RegisterResponse response, Validator... validators) {
599        for (Validator validator : validators) {
600            if (!validator.validate()) {
601                for (String error : validator.getErrorMessages()) {
602                    response.addError(error);
603                }
604            }
605        }
606    }
607
608    /**
609     * @param componentRegistryFactory the componentRegistryFactory to set
610     */
611    public void setComponentRegistryFactory(ComponentRegistryFactory componentRegistryFactory) {
612        this.componentRegistryFactory = componentRegistryFactory;
613    }
614}
Note: See TracBrowser for help on using the repository browser.