Commit 68e920d5 authored by Christos Tranoris's avatar Christos Tranoris
Browse files

scm633 hubApi with repo implementation

parent d40ca564
Loading
Loading
Loading
Loading
Loading
+13 −0
Original line number Diff line number Diff line
@@ -27,6 +27,7 @@ package org.etsi.osl.tmf.scm633.api;
import org.etsi.osl.tmf.scm633.model.EventSubscription;
import org.etsi.osl.tmf.scm633.model.EventSubscriptionInput;
import org.springframework.http.ResponseEntity;
import java.util.List;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -74,4 +75,16 @@ public interface HubApi {
        method = RequestMethod.DELETE)
    ResponseEntity<Void> unregisterListener(@Parameter(description = "The id of the registered listener",required=true) @PathVariable("id") String id);

    @Operation(summary = "Get all registered listeners", operationId = "getListeners", description = "Retrieves all registered event subscriptions", tags={ "events subscription", })
    @ApiResponses(value = { 
        @ApiResponse(responseCode = "200", description = "Success" ),
        @ApiResponse(responseCode = "400", description = "Bad Request" ),
        @ApiResponse(responseCode = "401", description = "Unauthorized" ),
        @ApiResponse(responseCode = "403", description = "Forbidden" ),
        @ApiResponse(responseCode = "500", description = "Internal Server Error" ) })
    @RequestMapping(value = "/hub",
        produces = { "application/json;charset=utf-8" },
        method = RequestMethod.GET)
    ResponseEntity<List<EventSubscription>> getListeners();

}
+48 −12
Original line number Diff line number Diff line
@@ -20,18 +20,24 @@
package org.etsi.osl.tmf.scm633.api;

import java.io.IOException;
import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.etsi.osl.tmf.scm633.model.EventSubscription;
import org.etsi.osl.tmf.scm633.model.EventSubscriptionInput;
import org.etsi.osl.tmf.scm633.reposervices.EventSubscriptionRepoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
@@ -47,29 +53,59 @@ public class HubApiController implements HubApi {

    private final HttpServletRequest request;
    
    @Autowired
    @Qualifier("scm633EventSubscriptionRepoService")
    EventSubscriptionRepoService eventSubscriptionRepoService;

    @org.springframework.beans.factory.annotation.Autowired
    public HubApiController(ObjectMapper objectMapper, HttpServletRequest request) {
        this.objectMapper = objectMapper;
        this.request = request;
    }

    @Override
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_USER')")
    public ResponseEntity<EventSubscription> registerListener(@Parameter(description = "Data containing the callback endpoint to deliver the information" ,required=true )  @Valid @RequestBody EventSubscriptionInput data) {
        String accept = request.getHeader("Accept");
        if (accept != null && accept.contains("application/json")) {
        try {
                return new ResponseEntity<EventSubscription>(objectMapper.readValue("{  \"query\" : \"query\",  \"callback\" : \"callback\",  \"id\" : \"id\"}", EventSubscription.class), HttpStatus.NOT_IMPLEMENTED);
            } catch (IOException e) {
                log.error("Couldn't serialize response for content type application/json", e);
                return new ResponseEntity<EventSubscription>(HttpStatus.INTERNAL_SERVER_ERROR);
            EventSubscription eventSubscription = eventSubscriptionRepoService.addEventSubscription(data);
            return new ResponseEntity<>(eventSubscription, HttpStatus.CREATED);
        } catch (IllegalArgumentException e) {
            log.error("Invalid input for listener registration: {}", e.getMessage());
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        } catch (Exception e) {
            log.error("Error registering listener", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

        return new ResponseEntity<EventSubscription>(HttpStatus.NOT_IMPLEMENTED);
    @Override
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_USER')")
    @RequestMapping(value = "/hub/{id}", method = RequestMethod.DELETE, produces = { "application/json;charset=utf-8" })
    public ResponseEntity<Void> unregisterListener(@Parameter(description = "The id of the registered listener",required=true) @PathVariable("id") String id) {
        try {
            EventSubscription existing = eventSubscriptionRepoService.findById(id);
            if (existing == null) {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }
            
    public ResponseEntity<Void> unregisterListener(@Parameter(description = "The id of the registered listener",required=true) @PathVariable("id") String id) {
        String accept = request.getHeader("Accept");
        return new ResponseEntity<Void>(HttpStatus.NOT_IMPLEMENTED);
            eventSubscriptionRepoService.deleteById(id);
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } catch (Exception e) {
            log.error("Error unregistering listener with id: " + id, e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @Override
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_USER')")
    public ResponseEntity<List<EventSubscription>> getListeners() {
        try {
            List<EventSubscription> eventSubscriptions = eventSubscriptionRepoService.findAll();
            return new ResponseEntity<>(eventSubscriptions, HttpStatus.OK);
        } catch (Exception e) {
            log.error("Error retrieving listeners", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}
+37 −0
Original line number Diff line number Diff line
/*-
 * ========================LICENSE_START=================================
 * org.etsi.osl.tmf.api
 * %%
 * Copyright (C) 2019 openslice.io
 * %%
 * 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.etsi.osl.tmf.scm633.repo;

import java.util.List;
import java.util.Optional;
import org.etsi.osl.tmf.scm633.model.EventSubscription;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

@Repository("scm633EventSubscriptionRepository")
public interface EventSubscriptionRepository extends CrudRepository<EventSubscription, Long>, PagingAndSortingRepository<EventSubscription, Long> {

    Optional<EventSubscription> findById(String id);
    
    void deleteById(String id);
    
    List<EventSubscription> findAll();
}
 No newline at end of file
+72 −0
Original line number Diff line number Diff line
/*-
 * ========================LICENSE_START=================================
 * org.etsi.osl.tmf.api
 * %%
 * Copyright (C) 2019 - 2021 openslice.io
 * %%
 * 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.etsi.osl.tmf.scm633.reposervices;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

import org.etsi.osl.tmf.scm633.model.EventSubscription;
import org.etsi.osl.tmf.scm633.model.EventSubscriptionInput;
import org.etsi.osl.tmf.scm633.repo.EventSubscriptionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.validation.Valid;

@Service("scm633EventSubscriptionRepoService")
@Transactional
public class EventSubscriptionRepoService {

    @Autowired
    @Qualifier("scm633EventSubscriptionRepository")
    EventSubscriptionRepository eventSubscriptionRepo;

    public EventSubscription addEventSubscription(@Valid EventSubscriptionInput eventSubscriptionInput) {
        if (eventSubscriptionInput.getCallback() == null || eventSubscriptionInput.getCallback().trim().isEmpty()) {
            throw new IllegalArgumentException("Callback URL is required and cannot be empty");
        }
        
        EventSubscription eventSubscription = new EventSubscription();
        eventSubscription.setId(UUID.randomUUID().toString());
        eventSubscription.setCallback(eventSubscriptionInput.getCallback());
        eventSubscription.setQuery(eventSubscriptionInput.getQuery());
        
        return this.eventSubscriptionRepo.save(eventSubscription);
    }

    public EventSubscription findById(String id) {
        Optional<EventSubscription> optionalEventSubscription = this.eventSubscriptionRepo.findById(id);
        return optionalEventSubscription.orElse(null);
    }

    public void deleteById(String id) {
        Optional<EventSubscription> optionalEventSubscription = this.eventSubscriptionRepo.findById(id);
        if (optionalEventSubscription.isPresent()) {
            this.eventSubscriptionRepo.delete(optionalEventSubscription.get());
        }
    }

    public List<EventSubscription> findAll() {
        return (List<EventSubscription>) this.eventSubscriptionRepo.findAll();
    }
}
 No newline at end of file
+3 −3
Original line number Diff line number Diff line
@@ -70,14 +70,14 @@ public class HubApiControllerTest {
                        .contentType(MediaType.APPLICATION_JSON)
                        .accept(MediaType.APPLICATION_JSON)
                .content( JsonUtils.toJson( eventSubscriptionInput ) ))
                .andExpect(status().is(501));
                .andExpect(status().isCreated());

        // Test when not providing an "Accept" request header
        mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/hub")
                        .with(SecurityMockMvcRequestPostProcessors.csrf())
                        .contentType(MediaType.APPLICATION_JSON)
                        .content( JsonUtils.toJson( eventSubscriptionInput ) ))
                .andExpect(status().is(501));
                .andExpect(status().isCreated());
    }


@@ -89,6 +89,6 @@ public class HubApiControllerTest {
                        .with(SecurityMockMvcRequestPostProcessors.csrf())
                        .contentType(MediaType.APPLICATION_JSON)
                        .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().is(501));
                .andExpect(status().isNotFound());
    }
}
 No newline at end of file