Changing variable types for api
[cps.git] / cps / cps-rest / src / main / java / org / onap / cps / rest / controller / RestController.java
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2020 Nordix Foundation
4  *  Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
5  *  ================================================================================
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  *  SPDX-License-Identifier: Apache-2.0
18  *  ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.rest.controller;
22
23 import com.google.gson.Gson;
24 import com.google.gson.JsonSyntaxException;
25 import java.io.File;
26 import javax.persistence.PersistenceException;
27 import javax.validation.Valid;
28 import javax.ws.rs.Consumes;
29 import javax.ws.rs.DELETE;
30 import javax.ws.rs.GET;
31 import javax.ws.rs.POST;
32 import javax.ws.rs.Path;
33 import javax.ws.rs.PathParam;
34 import javax.ws.rs.Produces;
35 import javax.ws.rs.core.MediaType;
36 import javax.ws.rs.core.Response;
37 import javax.ws.rs.core.Response.Status;
38 import org.apache.cxf.jaxrs.ext.multipart.Attachment;
39 import org.glassfish.jersey.media.multipart.FormDataParam;
40 import org.hibernate.exception.ConstraintViolationException;
41 import org.onap.cps.api.CpService;
42 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
43 import org.opendaylight.yangtools.yang.model.parser.api.YangParserException;
44 import org.springframework.beans.factory.annotation.Autowired;
45 import org.springframework.dao.EmptyResultDataAccessException;
46
47 @Path("cps")
48 public class RestController implements CpsResourceApi {
49
50     @Autowired
51     private CpService cpService;
52
53     @Override
54     public Object createAnchor(final Attachment fileDetail, final String dataspaceName) {
55         return null;
56     }
57
58     @Override
59     public Object createModules(final Attachment fileDetail, final String dataspaceName) {
60         return null;
61     }
62
63     @Override
64     public Object createNode(final Attachment fileDetail, final String dataspaceName) {
65         return null;
66     }
67
68     @Override
69     public Object deleteAnchor(final String dataspaceName, final String anchorName) {
70         return null;
71     }
72
73     @Override
74     public Object deleteDataspace(final String dataspaceName) {
75         return null;
76     }
77
78     @Override
79     public Object getAnchor(final String dataspaceName, final String anchorName) {
80         return null;
81     }
82
83     @Override
84     public Object getAnchors(final String dataspaceName) {
85         return null;
86     }
87
88     @Override
89     public Object getModule(final String dataspaceName, final String namespaceName, final String revision) {
90         return null;
91     }
92
93     @Override
94     public Object getNode(@Valid final String body, final String dataspaceName) {
95         return null;
96     }
97
98     @Override
99     public Object getNodeByDataspaceAndAnchor(@Valid final String body, final String dataspaceName,
100         final String anchorName) {
101         return null;
102     }
103
104     /*
105     Old rest endpoints before contract first approach (Need to be removed).
106      */
107
108     /**
109      * Upload a yang model file.
110      *
111      * @param uploadedFile the yang model file.
112      * @param dataspaceName the dataspace name linked to the model.
113      * @return a http response code.
114      */
115     @POST
116     @Path("/dataspaces/{dataspace_name}/modules")
117     @Produces(MediaType.APPLICATION_JSON)
118     @Consumes(MediaType.MULTIPART_FORM_DATA)
119     public final Response uploadYangModelFile(@FormDataParam("file") File uploadedFile,
120         @PathParam("dataspace_name") String dataspaceName) {
121         try {
122             final File fileToParse = renameFileIfNeeded(uploadedFile);
123             final SchemaContext schemaContext = cpService.parseAndValidateModel(fileToParse);
124             cpService.storeSchemaContext(schemaContext, dataspaceName);
125             return Response.status(Status.CREATED).entity("Resource successfully created").build();
126         } catch (final YangParserException | ConstraintViolationException e) {
127             return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
128         } catch (final Exception e) {
129             return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
130         }
131     }
132
133     /**
134      * Upload a JSON file.
135      *
136      * @param uploadedFile the JSON file.
137      * @return a http response code.
138      */
139     @POST
140     @Path("/upload-yang-json-data-file")
141     @Produces(MediaType.APPLICATION_JSON)
142     @Consumes(MediaType.MULTIPART_FORM_DATA)
143     public final Response uploadYangJsonDataFile(@FormDataParam("file") final String uploadedFile) {
144         try {
145             validateJsonStructure(uploadedFile);
146             final int persistenceObjectId = cpService.storeJsonStructure(uploadedFile);
147             return Response.status(Status.OK).entity("Object stored in CPS with identity: " + persistenceObjectId)
148                 .build();
149         } catch (final JsonSyntaxException e) {
150             return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
151         } catch (final Exception e) {
152             return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
153         }
154     }
155
156     /**
157      * Read a JSON Object using the object identifier.
158      *
159      * @param jsonObjectId the JSON object identifier.
160      * @return a HTTP response.
161      */
162     @GET
163     @Path("/json-object/{id}")
164     public final Response getJsonObjectById(@PathParam("id") final int jsonObjectId) {
165         try {
166             return Response.status(Status.OK).entity(cpService.getJsonById(jsonObjectId)).build();
167         } catch (final PersistenceException e) {
168             return Response.status(Status.NOT_FOUND).entity(e.getMessage()).build();
169         } catch (final Exception e) {
170             return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
171         }
172     }
173
174     /**
175      * Delete a JSON Object using the object identifier.
176      *
177      * @param jsonObjectId the JSON object identifier.
178      * @return a HTTP response.
179      */
180     @DELETE
181     @Path("json-object/{id}")
182     public final Response deleteJsonObjectById(@PathParam("id") final int jsonObjectId) {
183         try {
184             cpService.deleteJsonById(jsonObjectId);
185             return Response.status(Status.OK).entity(Status.OK.toString()).build();
186         } catch (final EmptyResultDataAccessException e) {
187             return Response.status(Status.NOT_FOUND).entity(Status.NOT_FOUND.toString()).build();
188         } catch (final Exception e) {
189             return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
190         }
191     }
192
193     private static final void validateJsonStructure(final String jsonFile) {
194         final Gson gson = new Gson();
195         gson.fromJson(jsonFile, Object.class);
196     }
197
198     private static final File renameFileIfNeeded(final File originalFile) {
199         if (originalFile.getName().endsWith(".yang")) {
200             return originalFile;
201         }
202         final File renamedFile = new File(originalFile.getName() + ".yang");
203         originalFile.renameTo(renamedFile);
204         return renamedFile;
205     }
206 }