dc6411009ba80ae51ce89a8f40bb1497edccd2e9
[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  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License.
15  *
16  *  SPDX-License-Identifier: Apache-2.0
17  *  ============LICENSE_END=========================================================
18  */
19
20 package org.onap.cps.rest.controller;
21
22 import java.io.File;
23 import java.io.IOException;
24 import javax.ws.rs.Consumes;
25 import javax.ws.rs.POST;
26 import javax.ws.rs.Path;
27 import javax.ws.rs.Produces;
28 import javax.ws.rs.core.MediaType;
29 import javax.ws.rs.core.Response;
30 import javax.ws.rs.core.Response.Status;
31 import org.glassfish.jersey.media.multipart.FormDataParam;
32 import org.onap.cps.api.CpService;
33 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
34 import org.opendaylight.yangtools.yang.model.parser.api.YangParserException;
35 import org.springframework.beans.factory.annotation.Autowired;
36
37
38 @Path("cps")
39 public class RestController {
40
41     @Autowired
42     private CpService cpService;
43
44     @POST
45     @Path("uploadYangFile")
46     @Produces(MediaType.APPLICATION_JSON)
47     @Consumes(MediaType.MULTIPART_FORM_DATA)
48     public Response uploadFile(@FormDataParam("file") File uploadedFile) throws IOException {
49         try {
50             File fileToParse = renameFileIfNeeded(uploadedFile);
51             SchemaContext schemaContext = cpService.parseAndValidateModel(fileToParse);
52             cpService.storeSchemaContext(schemaContext);
53             return Response.status(Status.OK).entity("Yang File Parsed").build();
54         } catch (YangParserException e) {
55             return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
56         }
57     }
58
59     private static File renameFileIfNeeded(File originalFile) {
60         if (originalFile.getName().endsWith(".yang")) {
61             return originalFile;
62         }
63         File renamedFile = new File(originalFile.getName() + ".yang");
64         originalFile.renameTo(renamedFile);
65         return renamedFile;
66     }
67 }
68
69
70
71