@Consumes(MediaType.APPLICATION_JSON) @Path("/{projectName}/statuses/{commit}") @POST public Response save(@PathParam("projectName") String projectName, @PathParam("commit") String commit, Map<String, String> commitStatus, @Context UriInfo uriInfo) { Project project = getProject(projectName); if (!SecurityUtils.canWrite(project)) throw new UnauthorizedException(); String state = commitStatus.get("state").toUpperCase(); if (state.equals("PENDING")) state = "RUNNING"; Verification verification = new Verification(Verification.Status.valueOf(state), new Date(), commitStatus.get("description"), commitStatus.get("target_url")); String context = commitStatus.get("context"); if (context == null) context = "default"; verificationManager.saveVerification(project, commit, context, verification); UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder(); uriBuilder.path(context); commitStatus.put("id", "1"); return Response.created(uriBuilder.build()).entity(commitStatus).type(RestConstants.JSON_UTF8).build(); }
@Test public void shouldCreateASessionFromInputs() { // Given SamlResponseWithAuthnRequestInformationDto samlResponse = aSamlResponseWithAuthnRequestInformationDto().build(); URI assertionConsumerServiceUri = UriBuilder.fromUri(UUID.randomUUID().toString()).build(); final SessionId sessionId = SessionIdBuilder.aSessionId().with("coffee-pasta").build(); givenSamlEngineTranslatesRequest(samlResponse); givenConfigReturnsAssertionConsumerServiceURLFor(samlResponse, assertionConsumerServiceUri); givenSessionIsCreated(samlResponse, assertionConsumerServiceUri, sessionId, false); // When SessionId result = service.create(requestDto); // Then assertThat(result, is(sessionId)); }
/** * Ensures that CDI event is relayed over the webSocket status endpoint. * * @throws Exception when the test has failed */ @Test public void webSocketsStatusTest() throws Exception { //given UUID uuid = UUID.randomUUID(); WebSocketContainer container = ContainerProvider.getWebSocketContainer(); URI uri = UriBuilder.fromUri(deploymentUrl).scheme("ws").path("status").path(uuid.toString()).build(); container.connectToServer(endpoint, uri); //when Thread.sleep(200); testEvent.fire(new StatusMessageEvent(uuid, StatusEventType.GITHUB_CREATE, singletonMap(EXTRA_DATA_KEY, "http://github.com/dummy-project-location"))); endpoint.getLatch().await(1, TimeUnit.SECONDS); //then assertNotNull("a status message should have been send", endpoint.getMessage()); assertTrue(endpoint.getMessage().contains(EXTRA_DATA_KEY)); }
@Test public void shouldGetACountryAuthnRequestWithOverriddenSsoUrl() throws Exception { // Given SessionId sessionId = createNewSessionId(); when(sessionRepository.sessionExists(sessionId)).thenReturn(true); when(sessionRepository.isSessionInState(sessionId, CountrySelectedState.class)).thenReturn(true); AuthnRequestFromHub authnRequestFromHub = anAuthnRequestFromHub().withSsoUrl(URI.create("/theSsoUri")).build(); when(authnRequestHandler.getIdaAuthnRequestFromHub(sessionId)).thenReturn(authnRequestFromHub); URI ssoUri = UriBuilder.fromUri(UUID.randomUUID().toString()).build(); SamlRequestDto samlRequest = new SamlRequestDto("samlRequest", ssoUri); when(samlEngineProxy.generateCountryAuthnRequestFromHub(any(IdaAuthnRequestFromHubDto.class))).thenReturn(samlRequest); // When AuthnRequestFromHubContainerDto countryAuthnRequest = service.getIdpAuthnRequest(sessionId); // Then AuthnRequestFromHubContainerDto expected = new AuthnRequestFromHubContainerDto(samlRequest.getSamlRequest(), ssoUri, authnRequestFromHub.getRegistering()); assertThat(countryAuthnRequest).isEqualToComparingFieldByField(expected); ArgumentCaptor<IdaAuthnRequestFromHubDto> requestFromHubDtoArgumentCaptor = ArgumentCaptor.forClass(IdaAuthnRequestFromHubDto.class); verify(samlEngineProxy).generateCountryAuthnRequestFromHub(requestFromHubDtoArgumentCaptor.capture()); assertThat(requestFromHubDtoArgumentCaptor.getValue().getOverriddenSsoUrl(), notNullValue()); }
/** * Creates a tenant with the given tenant identifier. * * @param stream TenantId JSON stream * @return status of the request - CREATED if the JSON is correct, * BAD_REQUEST if the JSON is invalid * @onos.rsModel TenantId */ @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response addTenantId(InputStream stream) { try { final TenantId tid = getTenantIdFromJsonStream(stream); vnetAdminService.registerTenantId(tid); final TenantId resultTid = getExistingTenantId(vnetAdminService, tid); UriBuilder locationBuilder = uriInfo.getBaseUriBuilder() .path("tenants") .path(resultTid.id()); return Response .created(locationBuilder.build()) .build(); } catch (IOException e) { throw new IllegalArgumentException(e); } }
@Test public void shouldReturnOkWhenGeneratingIdpAuthnRequestFromHubIsSuccessfulOnRegistration() throws Exception { // Given SessionId sessionId = aSessionIsCreated(); anIdpIsSelectedForRegistration(sessionId, idpEntityId); final SamlRequestDto samlRequestDto = new SamlRequestDto("coffee-pasta", idpSsoUri); final AuthnRequestFromHubContainerDto expectedResult = anAuthnRequestFromHubContainerDtoWithRegistering(samlRequestDto, true); samlEngineStub.setupStubForIdpAuthnRequestGenerate(samlRequestDto); // When AuthnRequestFromHubContainerDto result = getEntity(UriBuilder.fromPath(Urls.PolicyUrls .IDP_AUTHN_REQUEST_RESOURCE).build (sessionId), AuthnRequestFromHubContainerDto.class); //Then assertThat(result).isEqualToComparingFieldByField(expectedResult); }
/** * Provided the user has at least the basic CONNECTOR privilege, get a list * of all connectors, and from that list exclude any of those Connectors for * which the user lacks the PRIV_VIEWCONTENT_VIA_CONNECTOR privilege. * * @param uuid Item uuid, not relevant to the query per se, but used in * composing result set * @param version Item version, not relevant to the query per se, but used * in composing result set * @return */ @GET @Path("/{uuid}/{version}") @ApiOperation(value = "List of connectors and usage links") public List<ConnectorBean> getConnectorQueriesForItem(@ApiParam("Item UUID") @PathParam("uuid") String uuid, @ApiParam("Item version") @PathParam("version") int version) { List<ConnectorBean> connectorBeans = Lists.newArrayList(); Iterable<BaseEntityLabel> connectorDescriptors = connectorService.listForViewing(); UriBuilder uriBuilder = urlLinkService.getMethodUriBuilder(getClass(), "getUsagesOfItemForConnector"); for( BaseEntityLabel bent : connectorDescriptors ) { Connector connector = connectorService.get(bent.getId()); ConnectorBean bean = serializer.serialize(connector, null, true); Map<String, URI> links = Maps.newHashMap(); URI uri = uriBuilder.build(uuid, version, bent.getUuid()); links.put("usage", uri); bean.set("links", links); connectorBeans.add(bean); } return connectorBeans; }
@Before public void setUp() throws Exception { idpEntityId = "idpEntityId"; rpEntityId = "rpEntityId"; msaEntityId = "msaEntityId"; translatedAuthnRequest = SamlResponseWithAuthnRequestInformationDtoBuilder.aSamlResponseWithAuthnRequestInformationDto().withIssuer(rpEntityId).build(); rpSamlRequest = SamlAuthnRequestContainerDtoBuilder.aSamlAuthnRequestContainerDto().build(); idpSsoUri = UriBuilder.fromPath("idpSsoUri").build(); configStub.reset(); configStub.setupStubForEnabledIdps(asList(idpEntityId)); configStub.setUpStubForLevelsOfAssurance(rpEntityId); configStub.setUpStubForMatchingServiceEntityId(rpEntityId, msaEntityId); configStub.setupStubForEidasEnabledForTransaction(rpEntityId, false); eventSinkStub.setupStubForLogging(); }
@Test public void shouldReturnOkWhenAMatchingServiceFailureResponseIsReceived() throws Exception { SessionId sessionId = aSessionIsCreated(); anIdpIsSelectedForRegistration(sessionId, idpEntityId); anIdpAuthnRequestWasGenerated(sessionId); anAuthnResponseFromIdpWasReceivedAndMatchingRequestSent(sessionId); URI uri = UriBuilder.fromPath(Urls.PolicyUrls.MATCHING_SERVICE_REQUEST_FAILURE_RESOURCE).build(sessionId); Response response = postResponse(policy.uri(uri.toASCIIString()), null); assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); assertThat(getSessionStateName(sessionId)).isEqualTo(MatchingServiceRequestErrorState.class.getName()); // check that the state has been updated uri = UriBuilder.fromPath(Urls.PolicyUrls.RESPONSE_PROCESSING_DETAILS_RESOURCE).build(sessionId); response = getResponse(policy.uri(uri.toASCIIString())); assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); ResponseProcessingDetails responseProcessingDetails = response.readEntity(ResponseProcessingDetails.class); assertThat(responseProcessingDetails.getResponseProcessingStatus()).isEqualTo(ResponseProcessingStatus.SHOW_MATCHING_ERROR_PAGE); assertThat(responseProcessingDetails.getSessionId()).isEqualTo(sessionId); }
@Test public void filter_QueryParametersPassing_WhenRequestUrlContainsQueryParameters() throws Exception { // Arrange String queryPart = "test=123"; URI uri = URI.create("http://" + DBEERPEDIA.ORG_HOST + "/beer?" + queryPart); when(uriInfo.getRequestUriBuilder()).thenReturn(UriBuilder.fromUri(uri)); // Act hostPreMatchingRequestFilter.filter(containerRequestContext); // Assert ArgumentCaptor<URI> capture = ArgumentCaptor.forClass(URI.class); verify(containerRequestContext).setRequestUri(capture.capture()); assertEquals(queryPart, capture.getValue().getQuery()); }
@Test public void journeyWithFailedAccountCreation() throws Exception { final SessionId sessionId = aSessionIsCreated(); anIdpIsSelectedForRegistration(sessionId, idpEntityId); anIdpAuthnRequestWasGenerated(sessionId); anAuthnResponseFromIdpWasReceivedAndMatchingRequestSent(sessionId); aNoMatchResponseWasReceivedFromTheMSAForCycle01_withCycle3Enabled(sessionId); configStub.setUpStubForEnteringAwaitingCycle3DataState(rpEntityId); aCycle3AttributeHasBeenSentToPolicyFromTheUser(sessionId, "#1"); aNoMatchResponseHasBeenReceivedAndUserAccountCreationIsEnabled(sessionId); aUserAccountCreationResponseIsReceived(sessionId, MatchingServiceIdaStatus.UserAccountCreationFailed); URI uri = UriBuilder.fromPath(Urls.PolicyUrls.RESPONSE_PROCESSING_DETAILS_RESOURCE).build(sessionId); Response response = getResponse(policy.uri(uri.toASCIIString())); assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); ResponseProcessingDetails responseProcessingDetails = response.readEntity(ResponseProcessingDetails.class); assertThat(responseProcessingDetails.getResponseProcessingStatus()).isEqualTo(ResponseProcessingStatus.USER_ACCOUNT_CREATION_FAILED); assertThat(responseProcessingDetails.getSessionId()).isEqualTo(sessionId); assertThat(getSessionStateName(sessionId)).isEqualTo(UserAccountCreationFailedState.class.getName()); }
@Test public void isResponseFromHubReady_shouldReturnFailedStatusWhenAProblemHasOccurredWhilstMatchingCycle1() throws Exception { final SessionId sessionId = aSessionIsCreated(); anIdpIsSelectedForRegistration(sessionId, idpEntityId); anIdpAuthnRequestWasGenerated(sessionId); anAuthnResponseFromIdpWasReceivedAndMatchingRequestSent(sessionId); aMatchingServiceFailureResponseHasBeenReceived(sessionId); URI uri = UriBuilder.fromPath(Urls.PolicyUrls.RESPONSE_PROCESSING_DETAILS_RESOURCE).build(sessionId); Response response = getResponse(policy.uri(uri.toASCIIString())); assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); ResponseProcessingDetails responseProcessingDetails = response.readEntity(ResponseProcessingDetails.class); assertThat(responseProcessingDetails.getResponseProcessingStatus()).isEqualTo(ResponseProcessingStatus.SHOW_MATCHING_ERROR_PAGE); assertThat(responseProcessingDetails.getSessionId()).isEqualTo(sessionId); assertThat(getSessionStateName(sessionId)).isEqualTo(MatchingServiceRequestErrorState.class.getName()); }
@Test public void getCycle3AttributeRequestData_shouldReturnExpectedAttributeData() throws Exception { final SessionId sessionId = aSessionIsCreated(); anIdpIsSelectedForRegistration(sessionId, idpEntityId); anIdpAuthnRequestWasGenerated(sessionId); anAuthnResponseFromIdpWasReceivedAndMatchingRequestSent(sessionId); final String cycle3Attribute = aNoMatchResponseWasReceivedFromTheMSAForCycle01_withCycle3Enabled(sessionId); URI uri = UriBuilder.fromPath(Urls.PolicyUrls.CYCLE_3_REQUEST_RESOURCE).build(sessionId); Response response = getResponse(policy.uri(uri.toASCIIString())); assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); final Cycle3AttributeRequestData attributeData = response.readEntity(Cycle3AttributeRequestData.class); assertThat(attributeData.getAttributeName()).isEqualTo(cycle3Attribute); assertThat(attributeData.getRequestIssuerId()).isEqualTo(rpEntityId); assertThat(getSessionStateName(sessionId)).isEqualTo(AwaitingCycle3DataState.class.getName()); }
private void doRoleCommand(String serviceName, String roleName, RoleCommand roleCommand) { URI uri = UriBuilder.fromUri(serverHostname) .path("api") .path(API_VERSION) .path("clusters") .path(clusterName) .path("services") .path(serviceName) .path("roleCommands") .path(roleCommand.toString()) .build(); String body = "{ \"items\": [ \"" + roleName + "\" ] }"; LOG.info("Executing POST against " + uri + " with body " + body + "..."); ClientResponse response = client.resource(uri) .type(MediaType.APPLICATION_JSON) .post(ClientResponse.class, body); int statusCode = response.getStatus(); if (statusCode != Response.Status.OK.getStatusCode()) { throw new HTTPException(statusCode); } }
@Test public void generateSamlRequestWithOverriddenSsoUri() { // Given String theCountryEntityId = "theCountryEntityId"; URI overriddenSsoURI = URI.create("http://overridden.foo.bar"); IdaAuthnRequestFromHubDto dto = new IdaAuthnRequestFromHubDto("1", null, Optional.of(false), null, theCountryEntityId, false, overriddenSsoURI); URI ssoUri = UriBuilder.fromPath("/the-sso-uri").build(); String samlRequest = "samlRequest"; when(eidasAuthnRequestFromHubStringTransformer.apply(any())).thenReturn(samlRequest); when(eidasAuthnRequestTranslator.getEidasAuthnRequestFromHub(dto, ssoUri, HUB_ENTITY_ID)).thenReturn(null); // When final SamlRequestDto output = service.generateSaml(dto); // Then assertThat(output.getSamlRequest()).isEqualTo(samlRequest); assertThat(output.getSsoUri()).isEqualTo(overriddenSsoURI); verifyNoMoreInteractions(countrySingleSignOnServiceHelper); }
private void aNoMatchResponseWasReceivedFromTheMSAForCycle01_withCycle3Disabled(SessionId sessionId) throws JsonProcessingException { SamlResponseDto msaSamlResponseDto = new SamlResponseDto("a-saml-response"); InboundResponseFromMatchingServiceDto inboundResponseFromMatchingServiceDto = new InboundResponseFromMatchingServiceDto(MatchingServiceIdaStatus.NoMatchingServiceMatchFromMatchingService, translatedAuthnRequest.getId(), msaEntityId, Optional.<String>absent(), Optional.<LevelOfAssurance>absent()); samlEngineStub.setupStubForAttributeResponseTranslate(inboundResponseFromMatchingServiceDto); configStub.setUpStubForCycle01NoMatchCycle3Disabled(rpEntityId); List<UserAccountCreationAttribute> userAccountCreationAttributes = ImmutableList.of(UserAccountCreationAttribute.CURRENT_ADDRESS); configStub.setUpStubForUserAccountCreation(rpEntityId, userAccountCreationAttributes); URI uri = UriBuilder.fromPath(Urls.PolicyUrls.ATTRIBUTE_QUERY_RESPONSE_RESOURCE).build(sessionId); postResponse(policy.uri(uri.toASCIIString()), msaSamlResponseDto); }
@Test public void shouldCreateSessionIfProvidedAssertionConsumerServiceUrlMatches() throws Exception { URI assertionConsumerServiceUri = UriBuilder.fromUri(UUID.randomUUID().toString()).build(); SamlResponseWithAuthnRequestInformationDto samlResponse = aSamlResponseWithAuthnRequestInformationDto() .withAssertionConsumerServiceUrl(assertionConsumerServiceUri) .build(); final SessionId sessionId = SessionIdBuilder.aSessionId().with("coffee-pasta").build(); givenSamlEngineTranslatesRequest(samlResponse); givenConfigReturnsAssertionConsumerServiceURLFor(samlResponse, assertionConsumerServiceUri); givenSessionIsCreated(samlResponse, assertionConsumerServiceUri, sessionId, false); SessionId result = service.create(requestDto); assertThat(result, is(sessionId)); }
private String respondByTransitionToConfirmNumber(TaskDto task, String number) { LOGGER.debug("respondByTransitionToConfirmNumber"); String taskId = task.getRef(); String state = STATE_CONFIRM_NUMBER; AttributeGroupDto taskContext = new AttributeGroupDto(); taskContext.put(KEY_STATE, new StringAttributeValueDto(state)); taskContext.put(KEY_TEMP_NUMBER, new StringAttributeValueDto(number)); boolean taskUpdated = updateTaskContext(taskId, taskContext); if (false == taskUpdated) { return respondWithErrorTalkNcco(); } URI uri = UriBuilder.fromPath(getEventUrl()) .queryParam("taskId", taskId) .queryParam(KEY_STATE, state) .build(); String finalEventUrl = uri.toString(); String machineReadableNumber = PhoneConverter.machineReadable(number); String confirmationMessage = String.format(CONFIRM_NUMBER_MESSAGE, machineReadableNumber); List<Ncco> list = nccoFactory.nccoListWithConfirmNumber(confirmationMessage, finalEventUrl); // preparing a response NccoResponseBuilder builder = new NccoResponseBuilder(); list.forEach(ncco -> { builder.appendNcco(ncco); }); // respond NccoResponse nccoResponse = builder.getValue(); return nccoResponse.toJson(); }
private void initializeMissionControlServiceURI() { String host = System.getProperty(LAUNCHER_MISSIONCONTROL_SERVICE_HOST, System.getenv(LAUNCHER_MISSIONCONTROL_SERVICE_HOST)); if (host == null) { host = "launchpad-missioncontrol"; } UriBuilder uri = UriBuilder.fromPath("/api/missioncontrol/upload").host(host).scheme("http"); String port = System.getProperty(LAUNCHER_MISSIONCONTROL_SERVICE_PORT, System.getenv(LAUNCHER_MISSIONCONTROL_SERVICE_PORT)); uri.port(port != null ? Integer.parseInt(port) : 8080); missionControlURI = uri.build(); }
private static URI constructServiceProviderURI(final String serviceProviderId) { String basePath = OSLC4JUtils.getServletURI(); Map<String, Object> pathParameters = new HashMap<String, Object>(); pathParameters.put("serviceProviderId", serviceProviderId); String instanceURI = "serviceProviders/{serviceProviderId}"; final UriBuilder builder = UriBuilder.fromUri(basePath); return builder.path(instanceURI).buildFromMap(pathParameters); }
private Cycle3AttributeRequestData getCycle3Data(SessionId sessionId) { URI uri = UriBuilder.fromPath(Urls.PolicyUrls.CYCLE_3_REQUEST_RESOURCE).build(sessionId); Response response = client.target(policy.uri(uri.toASCIIString())) .request() .get(); return response.readEntity(Cycle3AttributeRequestData.class); }
@Test public void selectIdpShouldReturnErrorWhenSessionDoesNotExistInPolicy() throws Exception { SessionId sessionId = SessionId.createNewSessionId(); URI uri = UriBuilder .fromPath(Urls.PolicyUrls.AUTHN_REQUEST_SELECT_IDP_RESOURCE) .buildFromEncoded(sessionId); confirmError(policy.uri(uri.getPath()), new IdpSelected(STUB_IDP_ONE, "some-ip-address", REGISTERING), ExceptionType .SESSION_NOT_FOUND); }
@Override public CertificateChoiceResponse getCertificate(String documentNumber, CertificateRequest request) { logger.debug("Getting certificate for document " + documentNumber); URI uri = UriBuilder .fromUri(endpointUrl) .path(CERTIFICATE_CHOICE_BY_DOCUMENT_NUMBER_PATH) .build(documentNumber); return postCertificateRequest(uri, request); }
@Override public List<URI> getSupportedClaimTypes() { return WSFederationClaims.ALL_CLAIMS .stream() .map(c -> UriBuilder.fromUri(c.getUri()).build()) .collect(Collectors.toList()); }
/** * Creates new meter rule. Creates and installs a new meter rule for the * specified device. * * @param deviceId device identifier * @param stream meter rule JSON * @return status of the request - CREATED if the JSON is correct, * BAD_REQUEST if the JSON is invalid * @onos.rsModel MeterPost */ @POST @Path("{deviceId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createMeter(@PathParam("deviceId") String deviceId, InputStream stream) { try { ObjectNode jsonTree = (ObjectNode) mapper().readTree(stream); JsonNode specifiedDeviceId = jsonTree.get("deviceId"); if (specifiedDeviceId != null && !specifiedDeviceId.asText().equals(deviceId)) { throw new IllegalArgumentException(DEVICE_INVALID); } jsonTree.put("deviceId", deviceId); final MeterRequest meterRequest = codec(MeterRequest.class).decode(jsonTree, this); final Meter meter = meterService.submit(meterRequest); UriBuilder locationBuilder = uriInfo.getBaseUriBuilder() .path("meters") .path(deviceId) .path(Long.toString(meter.id().id())); return Response .created(locationBuilder.build()) .build(); } catch (IOException ex) { throw new IllegalArgumentException(ex); } }
@Test public void filter_PrefixPathWithXForwaredHeader_Always() throws Exception { // Arrange when(containerRequestContext.getHeaderString(HttpHeaders.X_FORWARDED_HOST)).thenReturn( DBEERPEDIA.NL_HOST); // Act hostPreMatchingRequestFilter.filter(containerRequestContext); // Assert verify(containerRequestContext).setRequestUri(UriBuilder.fromUri( "http://" + DBEERPEDIA.ORG_HOST + "/" + DBEERPEDIA.NL_HOST + "/beer").build()); }
private void anIdpIsSelectedForSignIn(SessionId sessionId, String idpEntityId) { final URI policyUri = policy.uri(UriBuilder.fromPath(Urls.PolicyUrls.AUTHN_REQUEST_SELECT_IDP_RESOURCE).build(sessionId).getPath()); client.target(policyUri) .request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(new IdpSelected(idpEntityId, "this-is-an-ip-address", SIGNING_IN))); }
@Test public void shouldReturnErrorStatusCodeWhenCallToSamlEngineGoesAwry() throws Exception { final SessionId sessionId = aSessionIsCreated(); samlEngineStub.setUpStubForErrorResponseGenerateErrorOccurring(); URI uri = UriBuilder.fromPath(Urls.PolicyUrls.RP_ERROR_RESPONSE_RESOURCE).build(sessionId.getSessionId()); Response response = get(uri); assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode()); ErrorStatusDto errorStatusDto = response.readEntity(ErrorStatusDto.class); assertThat(errorStatusDto.getExceptionType()).isEqualTo(ExceptionType.INVALID_INPUT); }
/** * Returns the URL for a collection page. * * @param collectionURL the collection URL * @param page the page * @return the collection page URL */ public static String createCollectionPageURL( String collectionURL, Page page, PageType pageType) { return UriBuilder.fromUri( collectionURL ).queryParam( "page", pageType.getPageNumber(page) ).queryParam( "per_page", page.getItemsPerPage() ).build( ).toString(); }
@Timed public CertificateDto getEncryptionCertificate(String entityId) { URI uri = UriBuilder .fromUri(configUri) .path(Urls.ConfigUrls.ENCRYPTION_CERTIFICATES_RESOURCE) .buildFromEncoded(StringEncoding.urlEncode(entityId)); try { return encryptionCertificates.getUnchecked(uri); } catch (UncheckedExecutionException e){ Throwables.throwIfUnchecked(e.getCause()); throw new RuntimeException(e.getCause()); } }
private void registerStubForCertificates(String issuer, CertificateDto signingCertificate, CertificateDto encryptionCertificate) throws JsonProcessingException { String signingCertificateUri = UriBuilder.fromPath(Urls.ConfigUrls.SIGNATURE_VERIFICATION_CERTIFICATES_RESOURCE).buildFromEncoded(StringEncoding.urlEncode(issuer)).toASCIIString(); Collection<CertificateDto> signingCertificates = new ArrayList<>(); signingCertificates.add(signingCertificate); register(signingCertificateUri, OK.getStatusCode(), signingCertificates); String encryptionCertificateUri = UriBuilder.fromPath(Urls.ConfigUrls.ENCRYPTION_CERTIFICATES_RESOURCE).buildFromEncoded(StringEncoding.urlEncode(issuer)).toASCIIString(); register(encryptionCertificateUri, OK.getStatusCode(), encryptionCertificate); }
public static void main(String[] args) { URI baseUri = UriBuilder.fromUri("http://localhost/").port(9990).build(); ResourceConfig config = new ResourceConfig(OfsResource.class); config.register(JsonProcessingFeature.class); HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, config); }
/** * Creates a new host based on JSON input and adds it to the current * host inventory. * * @param stream input JSON * @return status of the request - CREATED if the JSON is correct, * BAD_REQUEST if the JSON is invalid * @onos.rsModel HostPut */ @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createAndAddHost(InputStream stream) { URI location; try { // Parse the input stream ObjectNode root = (ObjectNode) mapper().readTree(stream); HostProviderRegistry hostProviderRegistry = get(HostProviderRegistry.class); InternalHostProvider hostProvider = new InternalHostProvider(); HostProviderService hostProviderService = hostProviderRegistry.register(hostProvider); hostProvider.setHostProviderService(hostProviderService); HostId hostId = hostProvider.parseHost(root); UriBuilder locationBuilder = uriInfo.getBaseUriBuilder() .path("hosts") .path(hostId.mac().toString()) .path(hostId.vlanId().toString()); location = locationBuilder.build(); hostProviderRegistry.unregister(hostProvider); } catch (IOException ex) { throw new IllegalArgumentException(ex); } return Response .created(location) .build(); }
public static void main(String[] args) throws Exception { int port = Integer.parseInt(ConfUtils.appConf.getProperty("rest.server.port")); URI baseUri = UriBuilder.fromUri("http://localhost").port(port).build(); ResourceConfig config = new RestApplication(); Server server = JettyHttpContainerFactory.createServer(baseUri, config, false); server.start(); }
public static URI constructURIForWhObject(final String serviceProviderId, final String whObjectId) { String basePath = OSLC4JUtils.getServletURI(); Map<String, Object> pathParameters = new HashMap<String, Object>(); pathParameters.put("serviceProviderId", serviceProviderId); pathParameters.put("whObjectId", whObjectId); String instanceURI = "serviceProviders/{serviceProviderId}/resources/whObjects/{whObjectId}"; final UriBuilder builder = UriBuilder.fromUri(basePath); return builder.path(instanceURI).buildFromMap(pathParameters); }
@Test public void countriesResourceShouldReturnNotFound() { URI uri = policy.uri(UriBuilder.fromPath(Urls.PolicyUrls.COUNTRIES_RESOURCE).build().toASCIIString()); Response response = client.target(uri).request(MediaType.APPLICATION_JSON_TYPE).get(); assertThat(response.getStatus()).isEqualTo(NOT_FOUND.getStatusCode()); }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { User subject = ResteasyProviderFactory.getContextData(User.class); if(subject == null){ UriBuilder builder = requestContext.getUriInfo().getBaseUriBuilder(); Session session = ResteasyProviderFactory.getContextData(Session.class); session.put(BaseSecurityResource.REDIRECT_KEY, requestContext.getUriInfo().getPath(false)); URI loginUri = builder.path(BaseSecurityResource.class).path(BaseSecurityResource.class, "login").build(); requestContext.abortWith(Response.status(Status.TEMPORARY_REDIRECT).location(loginUri).build()); } }
public void setUpStubForAssertionConsumerServiceUri(String entityId, Optional<Integer> assertionConsumerServiceIndex) throws JsonProcessingException { UriBuilder uriBuilder = UriBuilder.fromPath(Urls.ConfigUrls.TRANSACTIONS_ASSERTION_CONSUMER_SERVICE_URI_RESOURCE); if (assertionConsumerServiceIndex.isPresent()) { uriBuilder.queryParam(Urls.ConfigUrls.ASSERTION_CONSUMER_SERVICE_INDEX_PARAM, assertionConsumerServiceIndex.get().toString()); } URI uri = uriBuilder.buildFromEncoded(StringEncoding.urlEncode(entityId).replace("+", "%20")); register(uri.toString(), OK, new ResourceLocation(URI.create("thisIsAnRpPostEndpointUri"))); }
public void setUpStubForSendHubMatchingServiceRequest(SessionId sessionId) throws JsonProcessingException { URI uri = UriBuilder .fromPath(Urls.SamlSoapProxyUrls.MATCHING_SERVICE_REQUEST_SENDER_RESOURCE) .queryParam(Urls.SharedUrls.SESSION_ID_PARAM, sessionId) .build(); Response response = Response.status(Response.Status.ACCEPTED).build(); register(uri.getPath(), Response.Status.ACCEPTED.getStatusCode(), response); }