diff options
Diffstat (limited to 'adapters')
11 files changed, 1515 insertions, 0 deletions
diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/exceptions/ApplicationException.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/exceptions/ApplicationException.java new file mode 100644 index 0000000000..f63ba356a1 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/exceptions/ApplicationException.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.nssmf.exceptions; + +import org.onap.so.adapters.nssmf.model.ErrorResponse; +import org.springframework.http.ResponseEntity; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.marshal; + +public class ApplicationException extends Exception { + + private static final long serialVersionUID = 1L; + + private int errorCode; + + private String errorMsg; + + public ApplicationException(int errorCode, String errorMsg) { + this.errorCode = errorCode; + this.errorMsg = errorMsg; + } + + public int getErrorCode() { + return errorCode; + } + + public void setErrorCode(int errorCode) { + this.errorCode = errorCode; + } + + public String getErrorMsg() { + return errorMsg; + } + + public void setErrorMsg(String errorMsg) { + this.errorMsg = errorMsg; + } + + public ResponseEntity buildErrorResponse() { + String message; + try { + ErrorResponse err = new ErrorResponse(errorCode, errorMsg); + message = marshal(err); + } catch (ApplicationException e) { + return ResponseEntity.status(500).body("Internal Server Error"); + } + return ResponseEntity.status(errorCode).body(message); + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/HttpMethod.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/HttpMethod.java new file mode 100644 index 0000000000..f6abd98794 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/HttpMethod.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.nssmf.rest; + +public enum HttpMethod { + GET, POST, PUT, DELETE, PATCH; + + public static HttpMethod fromString(String s) { + if (s == null) + return null; + if (("get").equalsIgnoreCase(s)) + return GET; + if (("post").equalsIgnoreCase(s)) + return POST; + if (("put").equalsIgnoreCase(s)) + return PUT; + if (("delete").equalsIgnoreCase(s)) + return DELETE; + if (("patch").equalsIgnoreCase(s)) + return PATCH; + throw new IllegalArgumentException("Invalid value for HTTP Method: " + s); + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/JobStatus.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/JobStatus.java new file mode 100644 index 0000000000..f2e651fd6e --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/JobStatus.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.nssmf.rest; + +import org.onap.so.adapters.nssmf.exceptions.ApplicationException; + + +public enum JobStatus { + STARTED, PROCESSING, FINISHED, ERROR; + + public static JobStatus fromString(String s) throws ApplicationException { + if (s == null) + return null; + if (("started").equalsIgnoreCase(s)) + return STARTED; + if (("processing").equalsIgnoreCase(s)) + return PROCESSING; + if (("finished").equalsIgnoreCase(s)) + return FINISHED; + if (("error").equalsIgnoreCase(s)) + return ERROR; + throw new ApplicationException(500, "Invalid value for Job " + "Status: " + s); + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfAdapterRest.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfAdapterRest.java new file mode 100644 index 0000000000..d8e1e36058 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfAdapterRest.java @@ -0,0 +1,205 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.nssmf.rest; + +import org.onap.so.adapters.nssmf.exceptions.ApplicationException; +import org.onap.so.beans.nsmf.JobStatusRequest; +import org.onap.so.beans.nsmf.NssiActDeActRequest; +import org.onap.so.beans.nsmf.NssiAllocateRequest; +import org.onap.so.beans.nsmf.NssiCreateRequest; +import org.onap.so.beans.nsmf.NssiDeAllocateRequest; +import org.onap.so.beans.nsmf.NssiTerminateRequest; +import org.onap.so.beans.nsmf.NssiUpdateRequest; +import org.onap.so.beans.nsmf.NssiUpdateRequestById; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.assertObjectNotNull; + +@Controller +@RequestMapping(value = "/api/rest/provMns/v1", produces = {APPLICATION_JSON}, consumes = {APPLICATION_JSON}) +public class NssmfAdapterRest { + + private static final Logger logger = LoggerFactory.getLogger(NssmfAdapterRest.class); + + @Autowired + private NssmfManager nssmfMgr; + + @PostMapping(value = "/NSS/SliceProfiles") + public ResponseEntity allocateNssi(@RequestBody NssiAllocateRequest allocate) { + try { + logger.info("Nssmi allocate request is invoked"); + assertObjectNotNull(allocate); + RestResponse rsp = getNssmfMgr().allocateNssi(allocate); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @PostMapping(value = "/NSS/nssi") + public ResponseEntity createNssi(@RequestBody NssiCreateRequest create) { + try { + logger.info("Nssmf create request is invoked"); + assertObjectNotNull(create); + RestResponse rsp = getNssmfMgr().createNssi(create); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @PostMapping(value = "/NSS/SliceProfiles/{sliceProfileId}") + public ResponseEntity deAllocateNssi(@RequestBody NssiDeAllocateRequest deAllocate, + @PathVariable("sliceProfileId") final String sliceId) { + try { + logger.info("Nssmf deallocate request is invoked"); + assertObjectNotNull(deAllocate); + RestResponse rsp = getNssmfMgr().deAllocateNssi(deAllocate, sliceId); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @PostMapping(value = "/NSS/nssi/{nssiId}") + public ResponseEntity terminateNssi(@RequestBody NssiTerminateRequest terminate, + @PathVariable("nssiId") String nssiId) { + try { + logger.info("Nssmf terminate request is invoked"); + assertObjectNotNull(terminate); + RestResponse rsp = getNssmfMgr().terminateNssi(terminate, nssiId); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @PutMapping(value = "/NSS/SliceProfiles/{sliceProfileId}") + public ResponseEntity modifyNssi(@RequestBody NssiUpdateRequest update, + @PathVariable("sliceProfileId") String sliceId) { + try { + logger.info("Nssmf modify request is invoked"); + assertObjectNotNull(update); + RestResponse rsp = getNssmfMgr().updateNssi(update, sliceId); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @PutMapping(value = "/NSS/nssi/{nssiId}") + public ResponseEntity modifyNssiById(@RequestBody NssiUpdateRequestById updateById, + @PathVariable("nssiId") String nssiId) { + try { + logger.info("Nssmf modify by ID request is invoked"); + assertObjectNotNull(updateById); + RestResponse rsp = getNssmfMgr().updateNssiById(updateById, nssiId); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @PostMapping(value = "/NSS/{snssai}/activation") + public ResponseEntity activateNssi(@RequestBody NssiActDeActRequest activate, + @PathVariable("snssai") String snssai) { + try { + logger.info("Nssmf activate request is invoked"); + assertObjectNotNull(activate); + RestResponse rsp = getNssmfMgr().activateNssi(activate, snssai); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @PostMapping(value = "/NSS/{snssai}/deactivation") + public ResponseEntity deactivateNssi(@RequestBody NssiActDeActRequest deActivate, + @PathVariable("snssai") String snssai) { + try { + logger.info("Nssmf activate request is invoked"); + assertObjectNotNull(deActivate); + RestResponse rsp = getNssmfMgr().deActivateNssi(deActivate, snssai); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @PostMapping(value = "/NSS/jobs/{jobId}") + public ResponseEntity queryJobStatus(@RequestBody JobStatusRequest jobStatusReq, + @PathVariable("jobId") String jobId) { + try { + logger.info("Nssmf query job status request is invoked"); + assertObjectNotNull(jobStatusReq); + RestResponse rsp = getNssmfMgr().queryJobStatus(jobStatusReq, jobId); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @GetMapping(value = "/vendor/{vendorName}/type/{networkType}/NSS" + "/SliceProfiles/{sliceProfileId}") + public ResponseEntity queryNssi(@PathVariable("vendorName") String vendorName, + @PathVariable("networktype") String networkType, @PathVariable("sliceProfileId") String sliceId) { + try { + logger.info("Nssmf query nssi request is invoked"); + RestResponse rsp = getNssmfMgr().queryNssi(vendorName, networkType, sliceId); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @GetMapping(value = "/vendor/{vendorName}/type/{networkType}/NSS/nssi" + "/{nssiId}") + public ResponseEntity queryNssiById(@PathVariable("vendorName") String vendorName, + @PathVariable("networkTtype") String networkType, @PathVariable("nssiId") String nssiId) { + try { + logger.info("Nssmf query nssi by ID request is invoked"); + RestResponse rsp = getNssmfMgr().queryNssiById(vendorName, networkType, nssiId); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + public void setNssmfMgr(NssmfManager nssmfMgr) { + this.nssmfMgr = nssmfMgr; + } + + public NssmfManager getNssmfMgr() { + return nssmfMgr; + } + + private ResponseEntity buildResponse(RestResponse rsp) { + return ResponseEntity.status(rsp.getStatus()).body(rsp.getResponseContent()); + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfInfo.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfInfo.java new file mode 100644 index 0000000000..6306643a97 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfInfo.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.nssmf.rest; + +public class NssmfInfo { + + private String url; + + private String ipAddress; + + private String port; + + private String insecure; + + private String cacert; + + private String userName; + + private String password; + + public String getInsecure() { + return insecure; + } + + public void setInsecure(String insecure) { + this.insecure = insecure; + } + + public String getCacert() { + return cacert; + } + + public void setCacert(String cacert) { + this.cacert = cacert; + } + + public String getIpAddress() { + return ipAddress; + } + + public void setIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + } + + public String getPort() { + return port; + } + + public void setPort(String port) { + this.port = port; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfManager.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfManager.java new file mode 100644 index 0000000000..0e25729610 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfManager.java @@ -0,0 +1,541 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.nssmf.rest; + +import org.onap.so.adapters.nssmf.exceptions.ApplicationException; +import org.onap.so.beans.nsmf.ActDeActNssi; +import org.onap.so.beans.nsmf.AllocateAnNssi; +import org.onap.so.beans.nsmf.AllocateCnNssi; +import org.onap.so.beans.nsmf.AllocateTnNssi; +import org.onap.so.beans.nsmf.CreateCnNssi; +import org.onap.so.beans.nsmf.DeAllocateNssi; +import org.onap.so.beans.nsmf.EsrInfo; +import org.onap.so.beans.nsmf.JobStatusRequest; +import org.onap.so.beans.nsmf.JobStatusResponse; +import org.onap.so.beans.nsmf.NetworkType; +import org.onap.so.beans.nsmf.NssiActDeActRequest; +import org.onap.so.beans.nsmf.NssiAllocateRequest; +import org.onap.so.beans.nsmf.NssiCreateRequest; +import org.onap.so.beans.nsmf.NssiDeAllocateRequest; +import org.onap.so.beans.nsmf.NssiResponse; +import org.onap.so.beans.nsmf.NssiTerminateRequest; +import org.onap.so.beans.nsmf.NssiUpdateRequest; +import org.onap.so.beans.nsmf.NssiUpdateRequestById; +import org.onap.so.beans.nsmf.ResponseDescriptor; +import org.onap.so.beans.nsmf.TerminateNssi; +import org.onap.so.beans.nsmf.UpdateCnNssi; +import org.onap.so.beans.nsmf.UpdateCnNssiById; +import org.onap.so.db.request.beans.ResourceOperationStatus; +import org.onap.so.db.request.data.repository.ResourceOperationStatusRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Primary; +import org.springframework.data.domain.Example; +import org.springframework.stereotype.Component; +import static java.lang.String.valueOf; +import static org.onap.so.adapters.nssmf.rest.HttpMethod.DELETE; +import static org.onap.so.adapters.nssmf.rest.HttpMethod.GET; +import static org.onap.so.adapters.nssmf.rest.HttpMethod.POST; +import static org.onap.so.adapters.nssmf.rest.HttpMethod.PUT; +import static org.onap.so.adapters.nssmf.rest.JobStatus.ERROR; +import static org.onap.so.adapters.nssmf.rest.JobStatus.FINISHED; +import static org.onap.so.adapters.nssmf.rest.JobStatus.PROCESSING; +import static org.onap.so.adapters.nssmf.rest.JobStatus.STARTED; +import static org.onap.so.adapters.nssmf.rest.JobStatus.fromString; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.StatusDesc.ACTIVATE_NSS_SUCCESS; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.StatusDesc.ALLOCATE_NSS_SUCCESS; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.StatusDesc.CREATE_NSS_SUCCESS; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.StatusDesc.DEACTIVATE_NSS_SUCCESS; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.StatusDesc.DEALLOCATE_NSS_SUCCESS; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.StatusDesc.QUERY_JOB_STATUS_FAILED; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.StatusDesc.QUERY_JOB_STATUS_SUCCESS; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.assertObjectNotNull; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.marshal; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.unMarshal; +import static org.onap.so.beans.nsmf.ActDeActNssi.ACT_URL; +import static org.onap.so.beans.nsmf.ActDeActNssi.DE_ACT_URL; + +@Component +@Primary +public class NssmfManager { + + private static final Logger logger = LoggerFactory.getLogger(NssmfManager.class); + + public final static String QUERY = "/api/rest/provMns/v1/NSS" + "/SliceProfiles/{sliceProfileId}"; + + public final static String QUERY_BY_ID = "/api/rest/provMns/v1/NSS/nssi" + "/{nssiId}"; + + @Autowired + private ResourceOperationStatusRepository rscOperStatusRepo; + + @Autowired + private RestUtil restUtil; + + + public RestResponse allocateNssi(NssiAllocateRequest nssmiAllocate) throws ApplicationException { + + assertObjectNotNull(nssmiAllocate.getEsrInfo()); + assertObjectNotNull(nssmiAllocate.getEsrInfo().getNetworkType()); + assertObjectNotNull(nssmiAllocate.getEsrInfo().getVendor()); + + String nsiId = null; + String allocateReq = null; + String allocateUrl = null; + logger.info("Allocate Nssi for " + nssmiAllocate.getEsrInfo().getNetworkType() + " Network has begun"); + + switch (nssmiAllocate.getEsrInfo().getNetworkType()) { + + case CORE: + AllocateCnNssi cn = nssmiAllocate.getAllocateCnNssi(); + assertObjectNotNull(cn); + assertObjectNotNull(cn.getNsiInfo()); + assertObjectNotNull(cn.getNsiInfo().getNsiId()); + nsiId = cn.getNsiInfo().getNsiId(); + assertObjectNotNull(nsiId); + allocateReq = marshal(cn); + allocateUrl = AllocateCnNssi.URL; + break; + + case ACCESS: + AllocateAnNssi an = nssmiAllocate.getAllocateAnNssi(); + assertObjectNotNull(an); + assertObjectNotNull(an.getNsiInfo()); + assertObjectNotNull(an.getNsiInfo().getNsiId()); + nsiId = an.getNsiInfo().getNsiId(); + assertObjectNotNull(nsiId); + allocateReq = marshal(an); + allocateUrl = AllocateAnNssi.URL; + break; + + case TRANSPORT: + AllocateTnNssi tn = nssmiAllocate.getAllocateTnNssi(); + assertObjectNotNull(tn); + assertObjectNotNull(tn.getNsiInfo()); + assertObjectNotNull(tn.getNsiInfo().getNsiId()); + nsiId = tn.getNsiInfo().getNsiId(); + allocateReq = marshal(tn); + allocateUrl = AllocateTnNssi.URL; + break; + + } + RestResponse rsp = restUtil.sendRequest(allocateUrl, POST, allocateReq, nssmiAllocate.getEsrInfo()); + assertObjectNotNull(rsp); + + if (valueOf(rsp.getStatus()).startsWith("2")) { + NssiResponse allocateRes = unMarshal(rsp.getResponseContent(), NssiResponse.class); + + ResourceOperationStatus status = + new ResourceOperationStatus(allocateRes.getNssiId(), allocateRes.getJobId(), nsiId); + logger.info("save segment and operaton info -> begin"); + updateDbStatus(status, rsp.getStatus(), STARTED, ALLOCATE_NSS_SUCCESS); + logger.info("save segment and operation info -> end"); + } + return rsp; + } + + public RestResponse createNssi(NssiCreateRequest nssiCreate) throws ApplicationException { + + assertObjectNotNull(nssiCreate.getEsrInfo()); + assertObjectNotNull(nssiCreate.getEsrInfo().getNetworkType()); + assertObjectNotNull(nssiCreate.getEsrInfo().getVendor()); + + String nsiId = null; + String createReq = null; + String createUrl = null; + logger.info("Create Nssi for " + nssiCreate.getEsrInfo().getNetworkType() + " Network has begun"); + + switch (nssiCreate.getEsrInfo().getNetworkType()) { + case CORE: + CreateCnNssi cn = nssiCreate.getCreateCnNssi(); + nsiId = cn.getNsiInfo().getNsiId(); + assertObjectNotNull(nsiId); + createReq = marshal(cn); + createUrl = AllocateCnNssi.URL; + break; + + case ACCESS: + case TRANSPORT: + throw new ApplicationException(1, "Create Nssi doesn't " + "support the Network type:" + + nssiCreate.getEsrInfo().getNetworkType()); + } + RestResponse rsp = restUtil.sendRequest(createUrl, POST, createReq, nssiCreate.getEsrInfo()); + assertObjectNotNull(rsp); + + if (valueOf(rsp.getStatus()).startsWith("2")) { + NssiResponse allocateRes = unMarshal(rsp.getResponseContent(), NssiResponse.class); + + ResourceOperationStatus status = + new ResourceOperationStatus(allocateRes.getNssiId(), allocateRes.getJobId(), nsiId); + logger.info("save segment and operaton info -> begin"); + updateDbStatus(status, rsp.getStatus(), STARTED, CREATE_NSS_SUCCESS); + logger.info("save segment and operaton info -> end"); + } + return rsp; + } + + public RestResponse deAllocateNssi(NssiDeAllocateRequest nssiDeallocate, String sliceId) + throws ApplicationException { + + assertObjectNotNull(nssiDeallocate.getEsrInfo()); + assertObjectNotNull(nssiDeallocate.getEsrInfo().getNetworkType()); + assertObjectNotNull(nssiDeallocate.getEsrInfo().getVendor()); + + DeAllocateNssi deAllocate = nssiDeallocate.getDeAllocateNssi(); + + assertObjectNotNull(sliceId); + assertObjectNotNull(deAllocate.getNssiId()); + assertObjectNotNull(deAllocate.getNsiId()); + + String deallocateUrl = formTnAndAnUrl(nssiDeallocate.getEsrInfo(), DeAllocateNssi.URL, sliceId); + String deAllocateReq = marshal(deAllocate); + + logger.info("Deallocate Nssi has begun"); + + RestResponse rsp = restUtil.sendRequest(deallocateUrl, DELETE, deAllocateReq, nssiDeallocate.getEsrInfo()); + assertObjectNotNull(rsp); + + if (valueOf(rsp.getStatus()).startsWith("2")) { + NssiResponse res = unMarshal(rsp.getResponseContent(), NssiResponse.class); + + ResourceOperationStatus status = + new ResourceOperationStatus(deAllocate.getNssiId(), res.getJobId(), deAllocate.getNsiId()); + logger.info("save segment and operaton info -> begin"); + updateDbStatus(status, rsp.getStatus(), STARTED, DEALLOCATE_NSS_SUCCESS); + logger.info("save segment and operaton info -> end"); + } + return rsp; + } + + private String formTnAndAnUrl(EsrInfo esrInfo, String origUrl, String variable) { + + origUrl = formatUrl(origUrl, variable); + String[] val; + + switch (esrInfo.getNetworkType()) { + + case TRANSPORT: + val = origUrl.split("v1"); + return val[0] + "v1/tn" + val[1]; + + case ACCESS: + val = origUrl.split("v1"); + return val[0] + "v1/an" + val[1]; + + case CORE: + return origUrl; + } + return origUrl; + } + + private String formatUrl(String origUrl, String variable) { + + if (variable != null) { + origUrl = String.format(origUrl, variable); + } + return origUrl; + } + + + public RestResponse terminateNssi(NssiTerminateRequest nssiTerminate, String nssiId) throws ApplicationException { + + assertObjectNotNull(nssiTerminate.getEsrInfo()); + assertObjectNotNull(nssiTerminate.getEsrInfo().getNetworkType()); + assertObjectNotNull(nssiTerminate.getEsrInfo().getVendor()); + + TerminateNssi terminate = nssiTerminate.getTerminateNssi(); + + assertObjectNotNull(nssiId); + assertObjectNotNull(terminate.getNsiId()); + + logger.info("Terminate Nssi has begun"); + + String terminateUrl = formTnAndAnUrl(nssiTerminate.getEsrInfo(), TerminateNssi.URL, nssiId); + String terminateReq = marshal(terminate); + + RestResponse rsp = restUtil.sendRequest(terminateUrl, DELETE, terminateReq, nssiTerminate.getEsrInfo()); + assertObjectNotNull(rsp); + + if (valueOf(rsp.getStatus()).startsWith("2")) { + NssiResponse res = unMarshal(rsp.getResponseContent(), NssiResponse.class); + + ResourceOperationStatus status = new ResourceOperationStatus(nssiId, res.getJobId(), terminate.getNsiId()); + logger.info("save segment and operaton info -> begin"); + updateDbStatus(status, rsp.getStatus(), STARTED, DEALLOCATE_NSS_SUCCESS); + logger.info("save segment and operaton info -> end"); + } + return rsp; + } + + public RestResponse activateNssi(NssiActDeActRequest nssiActivate, String snssai) throws ApplicationException { + + assertObjectNotNull(nssiActivate.getEsrInfo()); + assertObjectNotNull(nssiActivate.getEsrInfo().getNetworkType()); + assertObjectNotNull(nssiActivate.getEsrInfo().getVendor()); + + ActDeActNssi activate = nssiActivate.getActDeActNssi(); + + assertObjectNotNull(snssai); + assertObjectNotNull(activate.getNssiId()); + assertObjectNotNull(activate.getNsiId()); + + logger.info("Activate Nssi has begun"); + + String activateUrl = formTnAndAnUrl(nssiActivate.getEsrInfo(), ACT_URL, snssai); + String activateReq = marshal(activate); + + RestResponse rsp = restUtil.sendRequest(activateUrl, PUT, activateReq, nssiActivate.getEsrInfo()); + assertObjectNotNull(rsp); + + if (valueOf(rsp.getStatus()).startsWith("2")) { + NssiResponse activateRes = unMarshal(rsp.getResponseContent(), NssiResponse.class); + + ResourceOperationStatus status = + new ResourceOperationStatus(activate.getNssiId(), activateRes.getJobId(), activate.getNsiId()); + logger.info("save segment and operaton info -> begin"); + updateDbStatus(status, rsp.getStatus(), STARTED, ACTIVATE_NSS_SUCCESS); + logger.info("save segment and operaton info -> end"); + } + return rsp; + } + + public RestResponse deActivateNssi(NssiActDeActRequest nssiDeActivate, String snssai) throws ApplicationException { + + assertObjectNotNull(nssiDeActivate.getEsrInfo()); + assertObjectNotNull(nssiDeActivate.getEsrInfo().getNetworkType()); + assertObjectNotNull(nssiDeActivate.getEsrInfo().getVendor()); + + logger.info("Deactivate Nssi has begun"); + + ActDeActNssi deActivate = nssiDeActivate.getActDeActNssi(); + + assertObjectNotNull(snssai); + assertObjectNotNull(deActivate.getNssiId()); + assertObjectNotNull(deActivate.getNsiId()); + + String deActivateUrl = formTnAndAnUrl(nssiDeActivate.getEsrInfo(), DE_ACT_URL, snssai); + String deActivateReq = marshal(deActivate); + + RestResponse rsp = restUtil.sendRequest(deActivateUrl, PUT, deActivateReq, nssiDeActivate.getEsrInfo()); + assertObjectNotNull(rsp); + + if (valueOf(rsp.getStatus()).startsWith("2")) { + NssiResponse deActivateRes = unMarshal(rsp.getResponseContent(), NssiResponse.class); + + ResourceOperationStatus status = new ResourceOperationStatus(deActivate.getNssiId(), + deActivateRes.getJobId(), deActivate.getNsiId()); + logger.info("save segment and operaton info -> begin"); + updateDbStatus(status, rsp.getStatus(), STARTED, DEACTIVATE_NSS_SUCCESS); + logger.info("save segment and operaton info -> end"); + } + return rsp; + } + + public RestResponse queryJobStatus(JobStatusRequest jobReq, String jobId) throws ApplicationException { + + assertObjectNotNull(jobReq.getEsrInfo()); + assertObjectNotNull(jobReq.getEsrInfo().getNetworkType()); + assertObjectNotNull(jobReq.getEsrInfo().getVendor()); + assertObjectNotNull(jobId); + assertObjectNotNull(jobReq.getNssiId()); + assertObjectNotNull(jobReq.getNsiId()); + + logger.info("Query job status has begun"); + + ResourceOperationStatus status = new ResourceOperationStatus(jobReq.getNssiId(), jobId, jobReq.getNsiId()); + status = rscOperStatusRepo.findOne(Example.of(status)) + .orElseThrow(() -> new ApplicationException(404, "Cannot Find Operation Status")); + + String statusUrl = formatUrl(JobStatusRequest.URL, jobId); + if (jobReq.getResponseId() != null) { + statusUrl = statusUrl + "?responseId=" + jobReq.getResponseId(); + } + + RestResponse rsp = restUtil.sendRequest(statusUrl, GET, "", jobReq.getEsrInfo()); + assertObjectNotNull(rsp); + + if (!valueOf(rsp.getStatus()).startsWith("2")) { + updateDbStatus(status, rsp.getStatus(), ERROR, QUERY_JOB_STATUS_FAILED); + throw new ApplicationException(500, QUERY_JOB_STATUS_FAILED); + } + + ResponseDescriptor rspDesc = + unMarshal(rsp.getResponseContent(), JobStatusResponse.class).getResponseDescriptor(); + logger.info("save segment and operaton info -> begin"); + updateRequestDbJobStatus(rspDesc, status, rsp); + logger.info("save segment and operaton info -> end"); + return rsp; + } + + + public RestResponse updateNssi(NssiUpdateRequest nssiUpdate, String sliceId) throws ApplicationException { + + assertObjectNotNull(nssiUpdate.getEsrInfo()); + assertObjectNotNull(nssiUpdate.getEsrInfo().getNetworkType()); + assertObjectNotNull(nssiUpdate.getEsrInfo().getVendor()); + assertObjectNotNull(sliceId); + + String nsiId = null; + String nssiId = null; + String updateReq = null; + String updateUrl = null; + logger.info("Update Nssi for " + nssiUpdate.getEsrInfo().getNetworkType() + " Network has begun"); + + switch (nssiUpdate.getEsrInfo().getNetworkType()) { + case CORE: + UpdateCnNssi cn = nssiUpdate.getUpdateCnNssi(); + nsiId = cn.getNsiInfo().getNsiId(); + nssiId = cn.getNssiId(); + assertObjectNotNull(nsiId); + assertObjectNotNull(nssiId); + updateReq = marshal(cn); + updateUrl = formatUrl(UpdateCnNssi.URL, sliceId); + break; + + case ACCESS: + case TRANSPORT: + throw new ApplicationException(1, "Update Nssi doesn't " + "support the Network type:" + + nssiUpdate.getEsrInfo().getNetworkType()); + } + + RestResponse rsp = restUtil.sendRequest(updateUrl, PUT, updateReq, nssiUpdate.getEsrInfo()); + assertObjectNotNull(rsp); + + if (valueOf(rsp.getStatus()).startsWith("2")) { + NssiResponse allocateRes = unMarshal(rsp.getResponseContent(), NssiResponse.class); + + ResourceOperationStatus status = new ResourceOperationStatus(nssiId, allocateRes.getJobId(), nsiId); + logger.info("save segment and operaton info -> begin"); + updateDbStatus(status, rsp.getStatus(), STARTED, ALLOCATE_NSS_SUCCESS); + logger.info("save segment and operaton info -> end"); + } + return rsp; + } + + public RestResponse updateNssiById(NssiUpdateRequestById nssiUpdateById, String nssiId) + throws ApplicationException { + + assertObjectNotNull(nssiUpdateById.getEsrInfo()); + assertObjectNotNull(nssiUpdateById.getEsrInfo().getNetworkType()); + assertObjectNotNull(nssiUpdateById.getEsrInfo().getVendor()); + assertObjectNotNull(nssiId); + + String nsiId = null; + String updateReq = null; + String updateUrl = null; + logger.info("Update Nssi by ID for " + nssiUpdateById.getEsrInfo().getNetworkType() + " Network has begun"); + + switch (nssiUpdateById.getEsrInfo().getNetworkType()) { + case CORE: + UpdateCnNssiById cn = nssiUpdateById.getUpdateCnNssiById(); + nsiId = cn.getNsiInfo().getNsiId(); + assertObjectNotNull(nsiId); + updateReq = marshal(cn); + updateUrl = formatUrl(UpdateCnNssiById.URL, nssiId); + break; + + case ACCESS: + case TRANSPORT: + throw new ApplicationException(1, "Update Nssi doesn't " + "support the Network type:" + + nssiUpdateById.getEsrInfo().getNetworkType()); + } + + RestResponse rsp = restUtil.sendRequest(updateUrl, PUT, updateReq, nssiUpdateById.getEsrInfo()); + assertObjectNotNull(rsp); + + if (valueOf(rsp.getStatus()).startsWith("2")) { + NssiResponse allocateRes = unMarshal(rsp.getResponseContent(), NssiResponse.class); + + ResourceOperationStatus status = new ResourceOperationStatus(nssiId, allocateRes.getJobId(), nsiId); + logger.info("save segment and operaton info -> begin"); + updateDbStatus(status, rsp.getStatus(), STARTED, ALLOCATE_NSS_SUCCESS); + logger.info("save segment and operaton info -> end"); + } + return rsp; + } + + public RestResponse queryNssi(String vendor, String type, String sliceId) throws ApplicationException { + + logger.info("Query Nssi has begun"); + String getUrl = formatUrl(QUERY, sliceId); + EsrInfo esr = new EsrInfo(); + esr.setVendor(vendor); + esr.setNetworkType(NetworkType.valueOf(type)); + RestResponse rsp = restUtil.sendRequest(getUrl, GET, "", esr); + assertObjectNotNull(rsp); + return rsp; + } + + public RestResponse queryNssiById(String vendor, String type, String nssiId) throws ApplicationException { + + logger.info("Query Nssi by ID has begun"); + String getUrl = formatUrl(QUERY_BY_ID, nssiId); + EsrInfo esr = new EsrInfo(); + esr.setVendor(vendor); + esr.setNetworkType(NetworkType.valueOf(type)); + RestResponse rsp = restUtil.sendRequest(getUrl, GET, "", esr); + assertObjectNotNull(rsp); + return rsp; + } + + private void updateRequestDbJobStatus(ResponseDescriptor rspDesc, ResourceOperationStatus status, RestResponse rsp) + throws ApplicationException { + + switch (fromString(rspDesc.getStatus())) { + + case STARTED: + updateDbStatus(status, rsp.getStatus(), STARTED, QUERY_JOB_STATUS_SUCCESS); + break; + + case ERROR: + updateDbStatus(status, rsp.getStatus(), ERROR, QUERY_JOB_STATUS_FAILED); + throw new ApplicationException(500, QUERY_JOB_STATUS_FAILED); + + case FINISHED: + if (rspDesc.getProgress() == 100) { + updateDbStatus(status, rsp.getStatus(), FINISHED, QUERY_JOB_STATUS_SUCCESS); + } + break; + + case PROCESSING: + updateDbStatus(status, rsp.getStatus(), PROCESSING, QUERY_JOB_STATUS_SUCCESS); + break; + } + } + + private void updateDbStatus(ResourceOperationStatus status, int rspStatus, JobStatus jobStatus, + String description) { + status.setErrorCode(valueOf(rspStatus)); + status.setStatus(jobStatus.toString()); + status.setStatusDescription(description); + logger.info("Updating DB status"); + rscOperStatusRepo.save(status); + logger.info("Updating successful"); + } + + public void setRscOperStatusRepo(ResourceOperationStatusRepository rscOperStatusRepo) { + this.rscOperStatusRepo = rscOperStatusRepo; + } + + public void setRestUtil(RestUtil restUtil) { + this.restUtil = restUtil; + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/RestResponse.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/RestResponse.java new file mode 100644 index 0000000000..cc047e45c7 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/RestResponse.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.nssmf.rest; + +import java.util.Map; + +public class RestResponse { + + // the response content + private String responseContent; + + // the response status + private int status; + + // the response header + private Map<String, String> respHeaderMap; + + public RestResponse() { + this.status = -1; + + this.respHeaderMap = null; + } + + public int getStatus() { + return this.status; + } + + public void setStatus(int status) { + this.status = status; + } + + public Map<String, String> getRespHeaderMap() { + return this.respHeaderMap; + } + + public void setRespHeaderMap(Map<String, String> header) { + this.respHeaderMap = header; + } + + public int getRespHeaderInt(String key) { + if (this.respHeaderMap != null) { + String result = this.respHeaderMap.get(key); + if (result != null) { + return Integer.parseInt(result); + } + } + return -1; + } + + public long getRespHeaderLong(String key) { + if (this.respHeaderMap != null) { + String result = this.respHeaderMap.get(key); + if (result != null) { + return Long.parseLong(result); + } + } + return -1L; + } + + public String getRespHeaderStr(String key) { + if (this.respHeaderMap != null) { + return this.respHeaderMap.get(key); + } + return null; + } + + public String getResponseContent() { + return this.responseContent; + } + + public void setResponseContent(String responseString) { + this.responseContent = responseString; + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/RestUtil.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/RestUtil.java new file mode 100644 index 0000000000..3592d4f6a3 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/RestUtil.java @@ -0,0 +1,307 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.nssmf.rest; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import javax.ws.rs.core.UriBuilder; +import java.net.SocketTimeoutException; +import java.net.URI; +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.conn.ConnectTimeoutException; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicHeader; +import org.apache.http.util.EntityUtils; +import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.aai.domain.yang.EsrSystemInfoList; +import org.onap.aai.domain.yang.EsrThirdpartySdnc; +import org.onap.aai.domain.yang.EsrThirdpartySdncList; +import org.onap.so.adapters.nssmf.exceptions.ApplicationException; +import org.onap.so.adapters.nssmf.extclients.aai.AaiServiceProvider; +import org.onap.so.adapters.nssmf.model.TokenRequest; +import org.onap.so.adapters.nssmf.model.TokenResponse; +import org.onap.so.beans.nsmf.EsrInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import static org.apache.http.entity.ContentType.APPLICATION_JSON; +import static org.onap.so.adapters.nssmf.rest.HttpMethod.POST; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.BAD_REQUEST; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.marshal; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.unMarshal; +import static org.onap.so.logger.ErrorCode.AvailabilityError; +import static org.onap.so.logger.LoggingAnchor.FOUR; +import static org.onap.so.logger.MessageEnum.RA_NS_EXC; + +@Component +public class RestUtil { + + private static final Logger logger = LoggerFactory.getLogger(RestUtil.class); + + private static final int DEFAULT_TIME_OUT = 60000; + + private static final String NSSMI_ADAPTER = "NSSMI Adapter"; + + private static final String TOKEN_URL = "/api/rest/securityManagement/v1" + "/oauth/token"; + + @Autowired + private AaiServiceProvider aaiSvcProv; + + + public NssmfInfo getNssmfHost(EsrInfo esrInfo) throws ApplicationException { + EsrThirdpartySdncList sdncList = aaiSvcProv.invokeGetThirdPartySdncList(); + if (sdncList != null && sdncList.getEsrThirdpartySdnc() != null) { + for (EsrThirdpartySdnc sdncEsr : sdncList.getEsrThirdpartySdnc()) { + + EsrSystemInfoList sysInfoList = + aaiSvcProv.invokeGetThirdPartySdncEsrSystemInfo(sdncEsr.getThirdpartySdncId()); + + if (sysInfoList != null && sysInfoList.getEsrSystemInfo() != null) { + for (EsrSystemInfo esr : sysInfoList.getEsrSystemInfo()) { + if (esr != null && esr.getType().equals(esrInfo.getNetworkType().getNetworkType()) + && esr.getVendor().equals(esrInfo.getVendor())) { + logger.info("Found an entry with vendor name " + esrInfo.getVendor() + " and network type " + + esrInfo.getNetworkType() + " in ESR."); + NssmfInfo nssmfInfo = new NssmfInfo(); + nssmfInfo.setIpAddress(esr.getIpAddress()); + nssmfInfo.setPort(esr.getPort()); + nssmfInfo.setCacert(esr.getSslCacert()); + nssmfInfo.setUserName(esr.getUserName()); + nssmfInfo.setPassword(esr.getPassword()); + String endPoint = UriBuilder.fromPath("").host(esr.getIpAddress()) + .port(Integer.valueOf(esr.getPort())).scheme("https").build().toString(); + nssmfInfo.setUrl(endPoint); + return nssmfInfo; + } + } + } + + } + } + + throw new ApplicationException(BAD_REQUEST, "ESR information is improper"); + } + + public RestResponse sendRequest(String url, HttpMethod methodType, String content, EsrInfo esrInfo) + throws ApplicationException { + + NssmfInfo nssmfInfo = getNssmfHost(esrInfo); + + TokenRequest req = new TokenRequest(); + req.setGrantType("password"); + req.setUserName(nssmfInfo.getUserName()); + req.setValue(nssmfInfo.getPassword()); + + String tokenReq = marshal(req); + + logger.info("Sending token request to NSSMF: " + tokenReq); + RestResponse tokenRes = send(nssmfInfo.getUrl() + TOKEN_URL, POST, tokenReq, null); + + TokenResponse res = unMarshal(tokenRes.getResponseContent(), TokenResponse.class); + String token = res.getAccessToken(); + Header header = new BasicHeader("X-Auth-Token", token); + String nssmfUrl = nssmfInfo.getUrl() + url; + return send(nssmfUrl, methodType, content, header); + } + + private RestResponse send(String url, HttpMethod methodType, String content, Header header) { + + HttpRequestBase req = null; + HttpResponse res = null; + + logger.debug("Beginning to send message {}: {}", methodType, url); + + try { + int timeout = DEFAULT_TIME_OUT; + + RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout) + .setConnectionRequestTimeout(timeout).build(); + logger.debug("Sending request to NSSMF: " + content); + req = getHttpReq(url, methodType, header, config, content); + res = getHttpsClient().execute(req); + + String resContent = null; + if (res.getEntity() != null) { + resContent = EntityUtils.toString(res.getEntity(), "UTF-8"); + } + + int statusCode = res.getStatusLine().getStatusCode(); + String statusMessage = res.getStatusLine().getReasonPhrase(); + logger.info("NSSMF Response: {} {}", statusCode, + statusMessage + (resContent == null ? "" : System.lineSeparator() + resContent)); + + if (res.getStatusLine().getStatusCode() >= 300) { + String errMsg = "{\n \"errorCode\": " + res.getStatusLine().getStatusCode() + + "\n \"errorDescription\": " + statusMessage + "\n}"; + logError(errMsg); + return createResponse(statusCode, errMsg); + } + if (null != req) { + req.reset(); + } else { + logger.debug("method is NULL:"); + } + req = null; + + return createResponse(statusCode, resContent); + + } catch (SocketTimeoutException | ConnectTimeoutException e) { + String errMsg = "Request to NSSMF timed out"; + logError(errMsg, e); + return createResponse(408, errMsg); + } catch (Exception e) { + String errMsg = "Error processing request to NSSMF"; + logError(errMsg, e); + return createResponse(500, errMsg); + } finally { + if (res != null) { + try { + EntityUtils.consume(res.getEntity()); + } catch (Exception e) { + logger.debug("Exception :", e); + } + } + if (req != null) { + try { + req.reset(); + } catch (Exception e) { + logger.debug("Exception :", e); + } + } + } + } + + private RestResponse createResponse(int statusCode, String errMsg) { + RestResponse restResponse = new RestResponse(); + restResponse.setStatus(statusCode); + restResponse.setResponseContent(errMsg); + return restResponse; + } + + private HttpRequestBase getHttpReq(String url, HttpMethod method, Header header, RequestConfig config, + String content) throws ApplicationException { + HttpRequestBase base = null; + switch (method) { + case POST: + HttpPost post = new HttpPost(url); + post.setEntity(new StringEntity(content, APPLICATION_JSON)); + base = post; + break; + + case GET: + base = new HttpGet(url); + break; + + case PUT: + HttpPut put = new HttpPut(url); + put.setEntity(new StringEntity(content, APPLICATION_JSON)); + base = put; + break; + + case PATCH: + break; + + case DELETE: + HttpDeleteWithBody delete = new HttpDeleteWithBody(url); + if (content != null) { + delete.setEntity(new StringEntity(content, APPLICATION_JSON)); + } + base = delete; + break; + + } + base.setConfig(config); + if (header != null) { + base.setHeader(header); + } + return base; + } + + class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase { + public static final String METHOD_NAME = "DELETE"; + + public String getMethod() { + return METHOD_NAME; + } + + public HttpDeleteWithBody(final String uri) { + super(); + setURI(URI.create(uri)); + } + + public HttpDeleteWithBody(final URI uri) { + super(); + setURI(uri); + } + + public HttpDeleteWithBody() { + super(); + } + } + + + public HttpClient getHttpsClient() { + + TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } + + public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {} + + public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {} + }}; + + // Install the all-trusting trust manager + try { + SSLContext sc = SSLContext.getInstance("SSL"); + sc.init(null, trustAllCerts, new java.security.SecureRandom()); + // HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + + SSLConnectionSocketFactory sslsf = + new SSLConnectionSocketFactory(sc, new String[] {"TLSv1"}, null, new TrustAllHostNameVerifier()); + return HttpClients.custom().setSSLSocketFactory(sslsf).build(); + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + } + + private static void logError(String errMsg, Throwable t) { + logger.error(FOUR, RA_NS_EXC.toString(), NSSMI_ADAPTER, AvailabilityError.getValue(), errMsg, t); + } + + private static void logError(String errMsg) { + logger.error(FOUR, RA_NS_EXC.toString(), NSSMI_ADAPTER, AvailabilityError.toString(), errMsg); + } +} + diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/TrustAllHostNameVerifier.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/TrustAllHostNameVerifier.java new file mode 100644 index 0000000000..254186bda8 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/TrustAllHostNameVerifier.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.nssmf.rest; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLSession; + +public class TrustAllHostNameVerifier implements HostnameVerifier { + + public boolean verify(String hostname, SSLSession session) { + return true; + } + +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/util/NssmfAdapterUtil.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/util/NssmfAdapterUtil.java new file mode 100644 index 0000000000..b0b84d822b --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/util/NssmfAdapterUtil.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.nssmf.util; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import org.onap.so.adapters.nssmf.exceptions.ApplicationException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.onap.so.logger.ErrorCode; +import static org.onap.so.logger.LoggingAnchor.THREE; +import static org.onap.so.logger.MessageEnum.RA_NS_EXC; + +public class NssmfAdapterUtil { + + private static final Logger LOGGER = LoggerFactory.getLogger(NssmfAdapterUtil.class); + + public static final int BAD_REQUEST = 400; + + private static final String UNMARSHAL_FAIL_MSG = "Failed to unmarshal json"; + + private static final String MARSHAL_FAIL_MSG = "Failed to marshal object"; + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static class StatusDesc { + + public static final String ALLOCATE_NSS_SUCCESS = "Allocating nss is " + "successful"; + + public static final String CREATE_NSS_SUCCESS = "Creating nss is " + "successful"; + + public static final String DEALLOCATE_NSS_SUCCESS = "Deallocate nss " + "is successful"; + + public static final String ACTIVATE_NSS_SUCCESS = "Activate nss " + "is successful"; + + public static final String DEACTIVATE_NSS_SUCCESS = "Deactivate nss " + "is successful"; + + public static final String QUERY_JOB_STATUS_FAILED = "Query job " + "status failed"; + + public static final String QUERY_JOB_STATUS_SUCCESS = "Query job " + "status is successful"; + + private StatusDesc() { + + } + } + + private NssmfAdapterUtil() { + + } + + public static void assertObjectNotNull(Object object) throws ApplicationException { + if (null == object) { + LOGGER.error("Object is null."); + throw new ApplicationException(BAD_REQUEST, "An object is null."); + } + } + + public static <T> T unMarshal(String jsonstr, Class<T> type) throws ApplicationException { + try { + return MAPPER.readValue(jsonstr, type); + } catch (IOException e) { + LOGGER.error(THREE, RA_NS_EXC.toString(), ErrorCode.BusinessProcessError.getValue(), UNMARSHAL_FAIL_MSG, e); + throw new ApplicationException(BAD_REQUEST, UNMARSHAL_FAIL_MSG); + } + } + + public static String marshal(Object srcObj) throws ApplicationException { + try { + return MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(srcObj); + } catch (IOException e) { + LOGGER.error(THREE, RA_NS_EXC.toString(), ErrorCode.BusinessProcessError.getValue(), MARSHAL_FAIL_MSG, e); + throw new ApplicationException(BAD_REQUEST, MARSHAL_FAIL_MSG); + } + } + +} diff --git a/adapters/pom.xml b/adapters/pom.xml index 8acc7012ba..5d382fd4dd 100644 --- a/adapters/pom.xml +++ b/adapters/pom.xml @@ -23,6 +23,7 @@ <module>mso-openstack-adapters</module> <module>mso-vnfm-adapter</module> <module>mso-ve-vnfm-adapter</module> + <module>mso-nssmf-adapter</module> <module>so-appc-orchestrator</module> </modules> |