Java Code Examples for javax.ws.rs.core.Response

The following are top voted examples for showing how to use javax.ws.rs.core.Response. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: hadoop-oss   File: KMS.java   Source Code and License 13 votes vote down vote up
@GET
@Path(KMSRESTConstants.KEYS_METADATA_RESOURCE)
@Produces(MediaType.APPLICATION_JSON)
public Response getKeysMetadata(@QueryParam(KMSRESTConstants.KEY)
    List<String> keyNamesList) throws Exception {
  KMSWebApp.getAdminCallsMeter().mark();
  UserGroupInformation user = HttpUserGroupInformation.get();
  final String[] keyNames = keyNamesList.toArray(
      new String[keyNamesList.size()]);
  assertAccess(KMSACLs.Type.GET_METADATA, user, KMSOp.GET_KEYS_METADATA);

  KeyProvider.Metadata[] keysMeta = user.doAs(
      new PrivilegedExceptionAction<KeyProvider.Metadata[]>() {
        @Override
        public KeyProvider.Metadata[] run() throws Exception {
          return provider.getKeysMetadata(keyNames);
        }
      }
  );

  Object json = KMSServerJSONUtils.toJSON(keyNames, keysMeta);
  kmsAudit.ok(user, KMSOp.GET_KEYS_METADATA, "");
  return Response.ok().type(MediaType.APPLICATION_JSON).entity(json).build();
}
 
Example 2
Project: message-broker   File: QueuesApiDelegate.java   Source Code and License 10 votes vote down vote up
public Response deleteQueue(String queueName, Boolean ifUnused, Boolean ifEmpty) {
    if (Objects.isNull(ifUnused)) {
        ifUnused = true;
    }

    if (Objects.isNull(ifEmpty)) {
        ifEmpty = true;
    }

    try {
        if (broker.deleteQueue(queueName, ifUnused, ifEmpty)) {
            return Response.ok().build();
        } else {
            throw new NotFoundException("Queue " + queueName + " doesn't exist.");
        }
    } catch (BrokerException e) {
        throw new BadRequestException(e.getMessage(), e);
    }
}
 
Example 3
Project: Celebino   File: UserController.java   Source Code and License 8 votes vote down vote up
/**
 * Cadastra usuario
 * 
 * @param User
 * @return Response
 */
@PermitAll
@POST
@Path("/")
@Consumes("application/json")
@Produces("application/json")
public Response insert(User user) {

	ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
	builder.expires(new Date());

	try {

		Long idUser = (long) UserDao.getInstance().insertU(user);
		user.setId(idUser);
		builder.status(Response.Status.OK).entity(user);

	} catch (SQLException e) {

		builder.status(Response.Status.INTERNAL_SERVER_ERROR);
	}

	return builder.build();
}
 
Example 4
Project: trellis   File: PutHandlerTest.java   Source Code and License 7 votes vote down vote up
@Test
public void testPutLdpResourceContainer() {
    when(mockLdpRequest.getLink()).thenReturn(fromUri(LDP.Container.getIRIString()).rel("type").build());
    when(mockLdpRequest.getContentType()).thenReturn(TEXT_TURTLE);

    final File entity = new File(getClass().getResource("/simpleTriple.ttl").getFile());
    final PutHandler putHandler = new PutHandler(mockLdpRequest, entity, mockResourceService,
            mockIoService, mockBinaryService, null);

    final Response res = putHandler.setResource(mockResource).build();
    assertEquals(NO_CONTENT, res.getStatusInfo());
    assertTrue(res.getLinks().stream().anyMatch(hasType(LDP.Resource)));
    assertTrue(res.getLinks().stream().anyMatch(hasType(LDP.RDFSource)));
    assertTrue(res.getLinks().stream().anyMatch(hasType(LDP.Container)));
    assertFalse(res.getLinks().stream().anyMatch(hasType(LDP.NonRDFSource)));

    verify(mockBinaryService, never()).setContent(any(IRI.class), any(InputStream.class));
    verify(mockIoService).read(any(InputStream.class), eq(baseUrl + "resource"), eq(TURTLE));
}
 
Example 5
Project: osc-core   File: ManagerConnectorApis.java   Source Code and License 7 votes vote down vote up
@ApiOperation(
        value = "Updates an Manager Connector.  If we are unable to connect to the endpoint(IP) using the credentials provided, this call will fail.",
        notes = "Creates an Manager Connector and sync's it immediately. "
                + "If we are unable to connect to the manager using the credentials provided, this call will fail."
                + "To skip validation of IP and credentials 'skipRemoteValidation' flag can be used.",
        response = BaseJobResponse.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successful operation"), @ApiResponse(code = 400,
        message = "In case of any error validating the information",
        response = ErrorCodeDto.class) })
@Path("/{applianceManagerConnectorId}")
@PUT
public Response updateApplianceManagerConnector(@Context HttpHeaders headers,
                                                @ApiParam(value = "Id of the Appliance Manager Connector",
                                                        required = true) @PathParam("applianceManagerConnectorId") Long amcId,
                                                @ApiParam(required = true) ApplianceManagerConnectorRequest amcRequest) {

    logger.info("Updating Appliance Manager Connector " + amcId);
    this.userContext.setUser(OscAuthFilter.getUsername(headers));

    this.apiUtil.setIdOrThrow(amcRequest, amcId, "Appliance Manager Connector");

    Response responseForBaseRequest = this.apiUtil.getResponseForBaseRequest(this.updateService,
                new DryRunRequest<>(amcRequest, amcRequest.isSkipRemoteValidation()));
    return responseForBaseRequest;
}
 
Example 6
Project: Equella   File: ItemResourceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public Response headFile(HttpHeaders headers, String uuid, int version, String path)
{
	ItemId itemId = new ItemId(uuid, version);
	checkViewItem(itemId);

	ItemFile itemFile = itemFileService.getItemFile(itemId, null);
	ResponseBuilder builder = makeBlobHeaders(itemFile, path);

	String contentType = mimeService.getMimeTypeForFilename(path);
	builder.type(contentType);

	if( !fileSystemService.fileExists(itemFile, path) )
	{
		return Response.status(Status.NOT_FOUND).build();
	}
	return builder.build();
}
 
Example 7
Project: osc-core   File: ServerMgmtApis.java   Source Code and License 6 votes vote down vote up
/**
 * Add a SSL certificate entry
 */
@ApiOperation(value = "Add SSL certificate",
        notes = "Adds a SSL certificate entry with custom alias provided by the user. Caution: As JSON string certificate needs to have all break lines converted to \\n.")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Successful operation"),
        @ApiResponse(code = 400, message = "In case of any error", response = ErrorCodeDto.class)})
@Path("/sslcertificate")
@OscAuth
@POST
public Response addSslCertificate(@Context HttpHeaders headers, @ApiParam(required = true) SslCertificateDto sslEntry) {
    logger.info("Adding new SSL certificate to truststore");
    this.userContext.setUser(OscAuthFilter.getUsername(headers));
    AddSslEntryRequest addSslEntryRequest = new AddSslEntryRequest(sslEntry.getAlias(), sslEntry.getCertificate());
    return this.apiUtil.getResponse(this.addSSlCertificateService, addSslEntryRequest);
}
 
Example 8
Project: lyre   File: EndpointService.java   Source Code and License 6 votes vote down vote up
@POST
public Response post(Endpoint endpoint) {

    if (validator.check(endpoint)) {

        if (bundle.exists(endpoint))
            bundle.update(endpoint);
        else
            throw new NotFoundException("Endpoint does not exist");

        apixController.bootAttempt(this.getClass().getSimpleName() +
            " POST {Endpoint method:[" + endpoint.getMethod().name() + "] path:[" + endpoint.getPath() + "]}");

    } else
        throw new BadRequestException("Malformed endpoint entity");

    return Response.ok().entity(endpoint).build();
}
 
Example 9
Project: keycloak-jaxrs-client-authfilter   File: BearerAuthFilter.java   Source Code and License 6 votes vote down vote up
@Override
public void filter( final ClientRequestContext requestContext, final ClientResponseContext responseContext )
  throws IOException
{
  if ( Response.Status.UNAUTHORIZED.getStatusCode() == responseContext.getStatus() )
  {
    final List<Object> headers = requestContext.getHeaders().get( HttpHeaders.AUTHORIZATION );
    if ( null == headers )
    {
      return;
    }
    for ( final Object header : headers )
    {
      if ( header instanceof String )
      {
        final String headerValue = (String) header;
        if ( headerValue.startsWith( AUTH_HEADER_PREFIX ) )
        {
          final String token = headerValue.substring( AUTH_HEADER_PREFIX.length() );
          _keycloak.invalidate( token );
        }
      }
    }
  }
}
 
Example 10
Project: lra-service   File: LRAService.java   Source Code and License 6 votes vote down vote up
public int leave(URL lraId, String compensatorUrl) {
    lraTrace(lraId, "leave LRA");

    Transaction transaction = getTransaction(lraId);

    if (!transaction.isActive())
        return Response.Status.PRECONDITION_FAILED.getStatusCode();

    try {
        if (!transaction.forgetParticipant(compensatorUrl))
            if (LRALogger.logger.isInfoEnabled())
                LRALogger.logger.infof("LRAServicve.forget %s failed%n", lraId);

        return Response.Status.OK.getStatusCode();
    } catch (Exception e) {
        return Response.Status.BAD_REQUEST.getStatusCode();
    }
}
 
Example 11
Project: incubator-freemarker-online-tester   File: ExecuteApiResourceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testMultipleErrorsDataModel() throws Exception {
    ExecuteRequest req = new ExecuteRequest(create30KString(), create30KString());
    req.setOutputFormat("wrongOutputFormat");
    req.setLocale("wrongLocale");
    req.setTimeZone("wrongTimeZone");

    Response resp = postJSON(req);
    
    assertEquals(200, resp.getStatus());
    ExecuteResponse response = resp.readEntity(ExecuteResponse.class);
    assertNotNull(response.getProblems());
    assertThat(getProblemMessage(response, ExecuteResourceField.TEMPLATE), containsString("limit"));
    assertThat(getProblemMessage(response, ExecuteResourceField.DATA_MODEL), containsString("limit"));
    assertThat(getProblemMessage(response, ExecuteResourceField.OUTPUT_FORMAT), containsString("wrongOutputFormat"));
    assertThat(getProblemMessage(response, ExecuteResourceField.LOCALE), containsString("wrongLocale"));
    assertThat(getProblemMessage(response, ExecuteResourceField.TIME_ZONE), containsString("wrongTimeZone"));
}
 
Example 12
Project: jobson   File: TestJobsAPI.java   Source Code and License 6 votes vote down vote up
@Test
public void testCanGETJobSummaries() throws IOException {
    final Invocation.Builder builder =
            generateAuthenticatedRequest(RULE, HTTP_JOBS_PATH);

    for (int i = 0; i < 10; i++) {
        builder.post(json(REQUEST_AGAINST_SECOND_SPEC), APIJobCreatedResponse.class);
    }

    final Response jobSummariesResponse =
            generateAuthenticatedRequest(RULE, HTTP_JOBS_PATH).get();

    assertThat(jobSummariesResponse.getStatus()).isEqualTo(OK);

    final APIJobDetailsCollection jobSummaries =
            readJSON(jobSummariesResponse.readEntity(String.class), APIJobDetailsCollection.class);

    assertThat(jobSummaries.getEntries().isEmpty()).isFalse();
}
 
Example 13
Project: dubbo2   File: RestClient.java   Source Code and License 6 votes vote down vote up
private static void registerUser(String url, MediaType mediaType) {
    System.out.println("Registering user via " + url);
    User user = new User(1L, "larrypage");
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(url);
    Response response = target.request().post(Entity.entity(user, mediaType));

    try {
        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed with HTTP error code : " + response.getStatus());
        }
        System.out.println("Successfully got result: " + response.readEntity(String.class));
    } finally {
        response.close();
        client.close();
    }
}
 
Example 14
Project: plugin-redirect   File: RedirectResourceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void handleRedirectAnonymousCookieNotMatch() throws URISyntaxException {
	SecurityContextHolder.clearContext();

	final SystemUserSetting setting = new SystemUserSetting();
	setting.setLogin(DEFAULT_USER);
	setting.setName(RedirectResource.PREFERRED_HASH);
	setting.setValue("-");
	userSettingRepository.save(setting);
	em.flush();
	em.clear();

	final Response response = resource.handleRedirect(DEFAULT_USER + "|hash");
	Assert.assertNull(response.getCookies().get(RedirectResource.PREFERRED_COOKIE_HASH));
	Assert.assertEquals("http://localhost:8081/external", response.getHeaderString("location"));
}
 
Example 15
Project: swaggy-jenkins   File: BlueApi.java   Source Code and License 6 votes vote down vote up
@PUT
    @Path("/rest/organizations/{organization}/pipelines/{pipeline}/favorite")
    
    @Produces({ "application/json" })
    @io.swagger.annotations.ApiOperation(value = "", notes = "Favorite/unfavorite a pipeline", response = FavoriteImpl.class, authorizations = {
        @io.swagger.annotations.Authorization(value = "jenkins_auth")
    }, tags={ "blueOcean", })
    @io.swagger.annotations.ApiResponses(value = { 
        @io.swagger.annotations.ApiResponse(code = 200, message = "Successfully favorited/unfavorited a pipeline", response = FavoriteImpl.class),
        
        @io.swagger.annotations.ApiResponse(code = 401, message = "Authentication failed - incorrect username and/or password", response = FavoriteImpl.class),
        
        @io.swagger.annotations.ApiResponse(code = 403, message = "Jenkins requires authentication - please set username and password", response = FavoriteImpl.class) })
    public Response putPipelineFavorite(@ApiParam(value = "Name of the organization",required=true) @PathParam("organization") String organization
,@ApiParam(value = "Name of the pipeline",required=true) @PathParam("pipeline") String pipeline
,@ApiParam(value = "Set JSON string body to {\"favorite\": true} to favorite, set value to false to unfavorite" ,required=true) String body
,@Context SecurityContext securityContext)
    throws NotFoundException {
        return delegate.putPipelineFavorite(organization,pipeline,body,securityContext);
    }
 
Example 16
Project: verify-hub   File: EidasCycle3DataResourceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldGetCycle3AttributeRequestDataFromConfiguration() throws JsonProcessingException {
    final SessionId sessionId = SessionIdBuilder.aSessionId().build();
    final String rpEntityId = new EidasCycle3DTO(sessionId).getRequestIssuerEntityId();
    final Response sessionCreatedResponse = createSessionInEidasAwaitingCycle3DataState(sessionId);
    assertThat(sessionCreatedResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());

    final MatchingProcessDto cycle3Attribute = new MatchingProcessDto(Optional.of("TUFTY_CLUB_CARD"));
    configStub.setUpStubForEnteringAwaitingCycle3DataState(rpEntityId, cycle3Attribute);
    samlSoapProxyProxyStub.setUpStubForSendHubMatchingServiceRequest(sessionId);

    final Cycle3AttributeRequestData actualResponse = getCycle3Data(sessionId);

    final Cycle3AttributeRequestData expectedResponse = aCycle3AttributeRequestData()
        .withAttributeName(cycle3Attribute.getAttributeName().get())
        .withRequestIssuerId(rpEntityId)
        .build();
    assertThat(actualResponse).isEqualToComparingFieldByField(expectedResponse);
}
 
Example 17
Project: javaee8-jaxrs-sample   File: PostResourceIT.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetPostsShouldBeOk() throws MalformedURLException {

    LOG.log(Level.INFO, "base url @{0}", base);

    //get all posts
    final WebTarget targetGetAll = client.target(URI.create(new URL(base, "api/posts").toExternalForm()));
    try (Response resGetAll = targetGetAll.request().accept(MediaType.APPLICATION_JSON_TYPE).get()) {
        assertEquals(200, resGetAll.getStatus());
        List<Post> results = resGetAll.readEntity(new GenericType<List<Post>>() {
        });
        assertTrue(results != null);
        LOG.log(Level.INFO, "results.size()::{0}", results.size());
        assertTrue(results.size() == 3);
    }

}
 
Example 18
Project: personium-core   File: PersoniumCoreContainerFilter.java   Source Code and License 6 votes vote down vote up
/**
 * 認証なしOPTIONメソッドのレスポンスを返却する.
 * @param request フィルタ前リクエスト
 */
private void responseOptionsMethod(ContainerRequest request) {
    String authValue = request.getHeaderValue(org.apache.http.HttpHeaders.AUTHORIZATION);
    String methodName = request.getMethod();
    if (authValue == null && HttpMethod.OPTIONS.equals(methodName)) {
        Response res = PersoniumCoreUtils.responseBuilderForOptions(
                HttpMethod.GET,
                HttpMethod.POST,
                HttpMethod.PUT,
                HttpMethod.DELETE,
                HttpMethod.HEAD,
                io.personium.common.utils.PersoniumCoreUtils.HttpMethod.MERGE,
                io.personium.common.utils.PersoniumCoreUtils.HttpMethod.MKCOL,
                io.personium.common.utils.PersoniumCoreUtils.HttpMethod.MOVE,
                io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND,
                io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPPATCH,
                io.personium.common.utils.PersoniumCoreUtils.HttpMethod.ACL
                ).build();

        // 例外を発行することでServletへ制御を渡さない
        throw new WebApplicationException(res);
    }
}
 
Example 19
Project: athena   File: StatisticsWebResource.java   Source Code and License 6 votes vote down vote up
/**
 * Gets port statistics of a specified devices.
 * @onos.rsModel StatisticsPorts
 * @param deviceId device ID
 * @return 200 OK with JSON encoded array of port statistics
 */
@GET
@Path("ports/{deviceId}")
@Produces(MediaType.APPLICATION_JSON)
public Response getPortStatisticsByDeviceId(@PathParam("deviceId") String deviceId) {
    final DeviceService service = get(DeviceService.class);
    final Iterable<PortStatistics> portStatsEntries =
            service.getPortStatistics(DeviceId.deviceId(deviceId));
    final ObjectNode root = mapper().createObjectNode();
    final ArrayNode rootArrayNode = root.putArray("statistics");
    final ObjectNode deviceStatsNode = mapper().createObjectNode();
    deviceStatsNode.put("device", deviceId);
    final ArrayNode statisticsNode = deviceStatsNode.putArray("ports");
    if (portStatsEntries != null) {
        for (final PortStatistics entry : portStatsEntries) {
            statisticsNode.add(codec(PortStatistics.class).encode(entry, this));
        }
    }
    rootArrayNode.add(deviceStatsNode);

    return ok(root).build();
}
 
Example 20
Project: redpipe   File: ApiResource.java   Source Code and License 6 votes vote down vote up
@RequiresPermissions("update")
@PUT
@Path("pages/{id}")
public Single<Response> apiUpdatePage(@PathParam("id") String id, 
		@ApiUpdateValid("markdown") JsonObject page,
		@Context HttpServerRequest req,
		@Context Vertx vertx){
	PagesDao dao = (PagesDao) AppGlobals.get().getGlobal("dao");
	return dao.updateExecAsync(new Pages().setId(Integer.valueOf(id)).setContent(page.getString("markdown")))
			.map(res -> {
			    JsonObject event = new JsonObject()
			    	      .put("id", id)
			    	      .put("client", page.getString("client"));
			    vertx.eventBus().publish("page.saved", event);
				return Response.ok(new JsonObject().put("success", true)).build();
			});
}
 
Example 21
Project: SistemaAlmoxarifado   File: UsuarioResource.java   Source Code and License 6 votes vote down vote up
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/updatepassword")
public Response updatePassword(@HeaderParam("token") String token, String body) 
        throws SQLException, Exception{
    
    Gson gson = new Gson();
    Usuario u = gson.fromJson(body, Usuario.class);  
    
    try {
        if(!Verify(token, "admin") && !Verify(token, "user"))
            return Response.status(Response.Status.UNAUTHORIZED)
                    .entity("Usuário ou senha incorretos").build();
    } catch (Exception ex) {
        return Resposta.retornar(400, ex.toString(), token);
    }
    
    int id = getSubject(token);    
    u.setId(id);
    UsuarioDAO.updatePassword(u);

    return Response.ok().build();
}
 
Example 22
Project: sample-acmegifts   File: AuthResourceTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests the JWT we get back from the auth service is valid. We test the JWT to make sure it was
 * signed correctly.
 *
 * <p>We do not validate other things, like the issued at time, expired time, etc.
 *
 * <p>The test case has access to the keystore that the server should have used to sign the JWT.
 */
@Test
public void testLoginJwtValidity() throws Exception {
  // Get the JWT from the auth service.
  Response response = processRequest(authServiceURL, "GET", null, null);
  assertEquals(
      "HTTP response code should have been " + Status.OK.getStatusCode() + ".",
      Status.OK.getStatusCode(),
      response.getStatus());
  String authHeader = response.getHeaderString("Authorization");

  // Open the keystore that the server should have used to sign the JWT.
  KeyStore ks = KeyStore.getInstance("JCEKS");
  InputStream ksStream = this.getClass().getResourceAsStream("/keystore.jceks");
  char[] password = new String("secret").toCharArray();
  ks.load(ksStream, password);
  java.security.cert.Certificate cert = ks.getCertificate("default");
  PublicKey publicKey = cert.getPublicKey();

  // Make sure it's valid.  Use the server's public key to check.
  new JWTVerifier().validateJWT(authHeader, publicKey);
}
 
Example 23
Project: swaggy-jenkins   File: BlueApi.java   Source Code and License 6 votes vote down vote up
@GET
    @Path("/rest/organizations/{organization}/pipelines/{pipeline}/queue")
    
    @Produces({ "application/json" })
    @io.swagger.annotations.ApiOperation(value = "", notes = "Retrieve queue details for an organization pipeline", response = PipelineQueue.class, authorizations = {
        @io.swagger.annotations.Authorization(value = "jenkins_auth")
    }, tags={ "blueOcean", })
    @io.swagger.annotations.ApiResponses(value = { 
        @io.swagger.annotations.ApiResponse(code = 200, message = "Successfully retrieved queue details", response = PipelineQueue.class),
        
        @io.swagger.annotations.ApiResponse(code = 401, message = "Authentication failed - incorrect username and/or password", response = PipelineQueue.class),
        
        @io.swagger.annotations.ApiResponse(code = 403, message = "Jenkins requires authentication - please set username and password", response = PipelineQueue.class) })
    public Response getPipelineQueue(@ApiParam(value = "Name of the organization",required=true) @PathParam("organization") String organization
,@ApiParam(value = "Name of the pipeline",required=true) @PathParam("pipeline") String pipeline
)
    throws NotFoundException {
        return delegate.getPipelineQueue(organization,pipeline);
    }
 
Example 24
Project: comms-router   File: TaskResource.java   Source Code and License 5 votes vote down vote up
@GET
@Path("byTag")
@ApiOperation(value = "Get resource by Tag", notes = "Returns resource by the given Tag")
public Response getByTag(@QueryParam("tag") String tag)
    throws CommsRouterException {

  LOGGER.debug("Getting by Tag {}", tag);

  TaskDto taskDto = taskService.getByTag(routerRef, tag);

  return Response.ok(taskDto, MediaType.APPLICATION_JSON_TYPE)
      .build();
}
 
Example 25
Project: Equella   File: FileResource.java   Source Code and License 5 votes vote down vote up
@DELETE
@Path("/{uuid}/content/{filepath:(.*)}")
@ApiOperation(value = "Delete a file")
public Response deleteFile(// @formatter:off
	@PathParam("uuid") String stagingUuid,
	@PathParam("filepath") String filepath
	// @formatter:on
) throws IOException;
 
Example 26
Project: servicebuilder   File: ConstraintViolationExceptionMapper.java   Source Code and License 5 votes vote down vote up
@Override
public Response toResponse(ConstraintViolationException exception) {
    Set<ConstraintViolation<?>> errorSet = exception.getConstraintViolations();
    List<String> errors = errorSet.stream()
            .map(this::errorMessage)
            .collect(Collectors.toList());
    String msg = String.format("Validering av parametere feilet med: %s", errors.toString());

    return exceptionUtil.handle(exception, cfg -> cfg
            .status(BAD_REQUEST.getStatusCode())
            .logLevel(LogLevel.WARN)
            .detail(msg)
            .logger(log)
    );
}
 
Example 27
Project: holon-json   File: TestResteasyIntegrationContext.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("static-access")
@Test
public void testGsonConfig() {

	Client client = ResteasyClientBuilder.newClient() // Avoid conflict with Jersey in classpath
			// ClientBuilder.newClient()
			.register(GsonFeature.class);

	String pong = client.target(TestPortProvider.generateURL("/test/ping")).request().get(String.class);
	assertEquals("pong", pong);

	PropertyBox box = SET.execute(() -> client.target(TestPortProvider.generateURL("/test/data/{num}"))
			.resolveTemplate("num", 1).request().get(PropertyBox.class));
	assertNotNull(box);
	assertEquals(Integer.valueOf(1), box.getValue(NUM));
	assertEquals("Str_1", box.getValue(STR));

	box = SET.execute(
			() -> client.target(TestPortProvider.generateURL("/test/data/2")).request().get(PropertyBox.class));
	assertNotNull(box);
	assertEquals(Integer.valueOf(2), box.getValue(NUM));
	assertEquals("Str_2", box.getValue(STR));

	PropertyBox boxToSrlz = PropertyBox.builder(SET).set(NUM, 100).set(DBL, 77.7).build();

	Response response = client.target(TestPortProvider.generateURL("/test/srlz")).request()
			.put(Entity.entity(boxToSrlz, MediaType.APPLICATION_JSON));
	assertNotNull(response);
	assertEquals(Status.ACCEPTED.getStatusCode(), response.getStatus());

}
 
Example 28
Project: swaggy-jenkins   File: BlueApi.java   Source Code and License 5 votes vote down vote up
@GET
    @Path("/rest/organizations/{organization}/scm/{scm}/organizations")
    
    @Produces({ "application/json" })
    @io.swagger.annotations.ApiOperation(value = "", notes = "Retrieve SCM organizations details for an organization", response = ScmOrganisations.class, authorizations = {
        @io.swagger.annotations.Authorization(value = "jenkins_auth")
    }, tags={ "blueOcean", })
    @io.swagger.annotations.ApiResponses(value = { 
        @io.swagger.annotations.ApiResponse(code = 200, message = "Successfully retrieved SCM organizations details", response = ScmOrganisations.class),
        
        @io.swagger.annotations.ApiResponse(code = 401, message = "Authentication failed - incorrect username and/or password", response = ScmOrganisations.class),
        
        @io.swagger.annotations.ApiResponse(code = 403, message = "Jenkins requires authentication - please set username and password", response = ScmOrganisations.class) })
    public Response getSCMOrganisations(@ApiParam(value = "Name of the organization",required=true) @PathParam("organization") String organization
,@ApiParam(value = "Name of SCM",required=true) @PathParam("scm") String scm
,@ApiParam(value = "Credential ID") @QueryParam("credentialId") String credentialId
,@Context SecurityContext securityContext)
    throws NotFoundException {
        return delegate.getSCMOrganisations(organization,scm,credentialId,securityContext);
    }
 
Example 29
Project: trellis   File: DeleteHandlerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testDeleteError() {
    when(mockResourceService.put(any(IRI.class), any(IRI.class), any(Dataset.class)))
        .thenReturn(completedFuture(false));
    final DeleteHandler handler = new DeleteHandler(mockLdpRequest, mockResourceService, baseUrl);

    final Response res = handler.deleteResource(mockResource).build();
    assertEquals(INTERNAL_SERVER_ERROR, res.getStatusInfo());
}
 
Example 30
Project: microprofile-jwt-auth   File: ProviderInjectionTest.java   Source Code and License 5 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
    description = "Verify that the injected sub claim is as expected")
public void verifyInjectedOptionalSubject() throws Exception {
    Reporter.log("Begin verifyInjectedOptionalSubject\n");
    String uri = baseURL.toExternalForm() + "/endp/verifyInjectedOptionalSubject";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.sub.name(), "24400320")
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example 31
Project: opencps-v2   File: ServiceProcessManagement.java   Source Code and License 5 votes vote down vote up
@GET
@Path("/{id}/actions")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Get all ProcessActions of a ServiceProcess", response = ProcessActionResultsModel.class)
@ApiResponses(value = {
		@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list ProcessStepRoles of a ProcessStep", response = ProcessActionResultsModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })

public Response getProcessActions(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext, @PathParam("id") long id, @BeanParam ProcessActionSearchModel query);
 
Example 32
Project: act-platform   File: ExceptionMappingsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testFailedRequestValidationNestedReturns412() throws Exception {
  CreateFactRequest request = new CreateFactRequest()
          .setType("type")
          .setValue("value")
          .addBinding(new CreateFactRequest.FactObjectBinding());
  Response response = target("/v1/fact").request().post(Entity.json(request));
  assertEquals(412, response.getStatus());
  assertMessages(getMessages(response), "must not be null", "{javax.validation.constraints.NotNull.message}", "bindings[0].direction", "NULL");
}
 
Example 33
Project: act-platform   File: OperationTimeoutMapper.java   Source Code and License 5 votes vote down vote up
@Override
public Response toResponse(OperationTimeoutException ex) {
  return ResultStash.builder()
          .setStatus(Response.Status.REQUEST_TIMEOUT)
          .addActionError(ex.getMessage(), ex.getMessageTemplate())
          .buildResponse();
}
 
Example 34
Project: trellis   File: AbstractLdpResourceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testPostBinaryWithInvalidDigest() {
    when(mockResource.getInteractionModel()).thenReturn(LDP.Container);
    when(mockResourceService.get(eq(rdf.createIRI(TRELLIS_PREFIX + RESOURCE_PATH + "/newresource")),
                any(Instant.class))).thenReturn(empty());
    final Response res = target(RESOURCE_PATH).request().header("Slug", "newresource")
        .header("Digest", "md5=blahblah").post(entity("some data.", TEXT_PLAIN_TYPE));

    assertEquals(BAD_REQUEST, res.getStatusInfo());
}
 
Example 35
Project: agilion   File: SessionApi.java   Source Code and License 5 votes vote down vote up
@GET


@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "retrieve list of sessions", notes = "list sessions", response = Session.class, responseContainer = "List", tags={ "sessions",  })
@io.swagger.annotations.ApiResponses(value = { 
    @io.swagger.annotations.ApiResponse(code = 200, message = "session objects", response = Session.class, responseContainer = "List") })
public Response listSessions(
    @Context SecurityContext securityContext)
throws NotFoundException {
    return delegate.listSessions(securityContext);
}
 
Example 36
Project: Pet-Supply-Store   File: LoadBalancedRecommenderOperations.java   Source Code and License 5 votes vote down vote up
/**
 * Gets recommendations.
 * @param order list of order items
 * @throws NotFoundException If 404 was returned.
 * @throws LoadBalancerTimeoutException On receiving the 408 status code
    * and on repeated load balancer socket timeouts.
 * @return List of recommended order ids
 */
public static List<Long> getRecommendations(List<OrderItem> order)
		throws NotFoundException, LoadBalancerTimeoutException {
	Response r = ServiceLoadBalancer.loadBalanceRESTOperation(Service.RECOMMENDER,
			"recommend", Category.class, client -> client.getService().path(client.getApplicationURI())
			.path(client.getEndpointURI()).request(MediaType.APPLICATION_JSON)
			.accept(MediaType.APPLICATION_JSON).post(Entity.entity(order, MediaType.APPLICATION_JSON)));
	try {
		return r.readEntity(new GenericType<List<Long>>() { });
	} catch (NullPointerException e) {
		return new ArrayList<>();
	}
}
 
Example 37
Project: swaggy-jenkins   File: BlueApiServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
    public Response postPipelineRuns(String organization
, String pipeline
 ) throws NotFoundException {
        // do some magic!
        return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build();
    }
 
Example 38
Project: redirector   File: PendingChangesControllerOffline.java   Source Code and License 5 votes vote down vote up
@POST
@Path("{appName}/templateRule/{ruleId}/approve")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response approveTemplatePendingRule(@PathParam("appName") final String appName,
                                           @PathParam("ruleId") final String ruleId,
                                           final Snapshot snapshot) {
    operationContextHolder.buildContextFromOfflineSnapshot(appName, snapshot);
    OperationResult result = pendingTemplateFlavorRuleWriteService.approve(appName, ruleId, ApplicationStatusMode.OFFLINE);
    return Response.ok(result).build();
}
 
Example 39
Project: ats-framework   File: MonitoringServiceImpl.java   Source Code and License 5 votes vote down vote up
@POST
@Path( "scheduleMonitoring")
@Consumes( MediaType.APPLICATION_JSON)
@Produces( MediaType.APPLICATION_JSON)
public Response scheduleMonitoring(
                                    @Context HttpServletRequest request,
                                    ScheduleMonitoringPojo monitoringPojo ) {

    final String caller = getCaller(request, monitoringPojo, false);
    ThreadsPerCaller.registerThread(caller);

    try {

        SessionData sd = getSessionData(request, monitoringPojo);

        RestSystemMonitor restSystemMonitor = sd.getSystemMonitor();

        String agent = request.getLocalAddr() + ":" + request.getLocalPort();

        Set<ReadingBean> readings = restSystemMonitor.scheduleMonitoring(agent,
                                                                         monitoringPojo.getReading(),
                                                                         monitoringPojo.getReadingParametersAsMap());

        restSystemMonitor.setScheduledReadingTypes(readings);

        String readingParametersAsString = entrySetAsString(monitoringPojo.getReadingParametersAsMap());

        return Response.ok("{\"status\":\"scheduled monitoring for reading '"
                           + monitoringPojo.getReading() + "' and readingParameters '"
                           + readingParametersAsString + "'\"}")
                       .build();

    } catch (Exception e) {
        return Response.serverError().entity(new ErrorPojo(e)).build();
    } finally {
        ThreadsPerCaller.unregisterThread();
    }

}
 
Example 40
Project: karate   File: JerseyHttpClient.java   Source Code and License 5 votes vote down vote up
@Override
public HttpResponse makeHttpRequest(Entity entity, long startTime) {
    String method = request.getMethod();
    if ("PATCH".equals(method)) { // http://danofhisword.com/dev/2015/09/04/Jersey-Client-Http-Patch.html
        builder.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
    }
    Response resp;
    if (entity != null) {
        resp = builder.method(method, entity);
    } else {
        resp = builder.method(method);
    }
    byte[] bytes = resp.readEntity(byte[].class);
    long responseTime = getResponseTime(startTime);
    HttpResponse response = new HttpResponse(responseTime);
    response.setUri(getRequestUri());
    response.setBody(bytes);
    response.setStatus(resp.getStatus());
    for (NewCookie c : resp.getCookies().values()) {
        com.intuit.karate.http.Cookie cookie = new com.intuit.karate.http.Cookie(c.getName(), c.getValue());
        cookie.put(DOMAIN, c.getDomain());
        cookie.put(PATH, c.getPath());
        if (c.getExpiry() != null) {
            cookie.put(EXPIRES, c.getExpiry().getTime() + "");
        }
        cookie.put(SECURE, c.isSecure() + "");
        cookie.put(HTTP_ONLY, c.isHttpOnly() + "");
        cookie.put(MAX_AGE, c.getMaxAge() + "");
        response.addCookie(cookie);
    }
    for (Entry<String, List<Object>> entry : resp.getHeaders().entrySet()) {
        response.putHeader(entry.getKey(), entry.getValue());
    }
    return response;
}
 
Example 41
Project: javaee-calculator   File: OperationsResourceIT.java   Source Code and License 5 votes vote down vote up
@Test
public void addition() {
    JsonObject input = Json.createObjectBuilder().
            add("a", 2).
            add("b", 21).
            build();
    Response response = this.tut.path("addition").
            request(MediaType.APPLICATION_JSON).
            post(json(input));
    assertThat(response.getStatus(), is(200));
    JsonObject jsonResult = response.readEntity(JsonObject.class);
    int result = jsonResult.getJsonNumber("result").intValue();
    assertThat(result, is(23));
}
 
Example 42
Project: presto-manager   File: ResponseWrapper.java   Source Code and License 5 votes vote down vote up
public WrappedResponse wrapResponse(Response response)
{
    return new WrappedResponse(response.getStatus(),
            response.getStatusInfo().getReasonPhrase(),
            response.getHeaders(),
            parseEntity(response));
}
 
Example 43
Project: Equella   File: ActivationResource.java   Source Code and License 5 votes vote down vote up
@PUT
@Path("/{requestuuid}")
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation("Update/edit an activation")
Response edit(
	// @formatter:off
		@ApiParam(value = "Activation request uuid") @PathParam("requestuuid") String requestUuid,
		@ApiParam(value = "to disable or not", allowableValues = "true,false", defaultValue = "false", required = false)
		@QueryParam("disable")
			boolean disable,
		@ApiParam("Activation request in JSON format") ActivationBean bean
		// @formatter:on
);
 
Example 44
Project: mid-tier   File: CustomerServiceExposure.java   Source Code and License 5 votes vote down vote up
Response listServiceGeneration1Version1(UriInfo uriInfo, Request request) {
    List<Customer> customers = archivist.listCustomers();
    return new EntityResponseBuilder<>(customers, list -> new CustomersRepresentation(list, uriInfo))
            .name("customers")
            .version("1")
            .maxAge(10)
            .build(request);
}
 
Example 45
Project: verify-hub   File: StateProcessingValidationExceptionMapperTest.java   Source Code and License 5 votes vote down vote up
@Test
public void toResponse_shouldReturnUnauditedErrorStatus() throws Exception {
    HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
    when(httpServletRequest.getParameter(Urls.SharedUrls.SESSION_ID_PARAM)).thenReturn("42");
    StateProcessingValidationExceptionMapper mapper = new StateProcessingValidationExceptionMapper(serviceInfo, eventSinkProxy);
    mapper.setHttpServletRequest(httpServletRequest);
    StateProcessingValidationException exception = new StateProcessingValidationException("error message", Level.ERROR);

    final Response response = mapper.toResponse(exception);

    assertThat(response.getEntity()).isNotNull();
    ErrorStatusDto errorStatusDto = (ErrorStatusDto)response.getEntity();
    assertThat(errorStatusDto.isAudited()).isEqualTo(false);
    assertThat(errorStatusDto.getExceptionType()).isEqualTo(ExceptionType.STATE_PROCESSING_VALIDATION);
}
 
Example 46
Project: holon-examples   File: ProductEndpoint.java   Source Code and License 5 votes vote down vote up
@POST
@Path("/products")
@Consumes(MediaType.APPLICATION_JSON)
public Response addProduct(@PropertySetRef(MProduct.class) PropertyBox product) {
	if (product == null) {
		return Response.status(Status.BAD_REQUEST).entity("Missing product").build();
	}
	// set id
	long nextId = getProductStore().nextId();
	product.setValue(MProduct.ID, nextId);
	getProductStore().put(product);
	return Response.created(URI.create("/api/products/" + nextId)).build();
}
 
Example 47
Project: presto-manager   File: ControlAPI.java   Source Code and License 5 votes vote down vote up
@POST
@Path("/stop")
@ApiOperation(value = "Stop Presto")
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successfully stopped Presto"),
        @ApiResponse(code = 404, message = "Presto is not installed"),
        @ApiResponse(code = 409, message = "Coordinator can't be gracefully stopped")})
public synchronized Response stopPresto(@QueryParam("stopType") @ApiParam("StopType: TERMINATE, KILL or GRACEFUL")
@DefaultValue("GRACEFUL") StopType stopType)
{
    return controller.stop(stopType);
}
 
Example 48
Project: escommons   File: EsCommonsResourceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testRemoveIndexByName2() {
    // test data
    resetAll();
    final RemoveIndexByNameRequest request = new RemoveIndexByNameRequest(UUID.randomUUID().toString());
    // expectations
    indexingComponent.removeIndexByName(request.getIndexName());
    replayAll();
    // test scenario
    final Response result = esCommonsResource.removeIndexByName(request);
    assertThat(result.getEntity()).isNotNull();
    verifyAll();
}
 
Example 49
Project: Biliomi   File: Responses.java   Source Code and License 5 votes vote down vote up
/**
 * Returned when the request succeeded
 *
 * @param entity The involved entity
 * @return A Response object
 */
public static Response okOrEmpty(Object entity) {
  if (entity == null || (Collection.class.isAssignableFrom(entity.getClass()) && ((Collection) entity).isEmpty())) {
    return noContent();
  }

  return ok(entity);
}
 
Example 50
Project: redirector   File: NamespaceControllerOffline.java   Source Code and License 5 votes vote down vote up
@POST
@Path("search/{value}")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response searchNamespacedLists(@PathParam("value") final String value, final SnapshotList snapshotList) {
    NamespacedListSearchResult result = namespacedListsService.searchNamespacedLists(new NamespacedListValueForWS(value), snapshotList);
    return Response.ok(result).build();
}
 
Example 51
Project: opencps-v2   File: ServiceConfigManagement.java   Source Code and License 5 votes vote down vote up
@GET
@Path("/domains")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@ApiOperation(value = "Get all ServiceConfigs", response = ServiceConfigResultsModel.class)
@ApiResponses(value = {
		@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of ServiceConfig", response = ServiceConfigResultsModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response getServiceConfigsByDomain(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext, @BeanParam ServiceInfoSearchModel query);
 
Example 52
Project: app-ms   File: HelloResource.java   Source Code and License 5 votes vote down vote up
@ApiOperation(value = "throws an client exception")
@GET
@Path("/bad")
public Response badClient() {

    final JsonElement entity = jsonOps.toJsonElement("{\"error\":\"client bad\"}");
    throw new BadRequestException("who's bad", Response.status(Status.BAD_REQUEST).entity(entity).build());
}
 
Example 53
Project: Java-9-Programming-Blueprints   File: DeskDroidResource.java   Source Code and License 5 votes vote down vote up
@POST
@Path("conversations")
@Secure
public Response sendMessage(Message message) throws InterruptedException {
    final SmsManager sms = SmsManager.getDefault();
    final ArrayList<String> parts = sms.divideMessage(message.getBody());
    final CountDownLatch sentLatch = new CountDownLatch(parts.size());
    final AtomicInteger statusCode =
            new AtomicInteger(Response.Status.CREATED.getStatusCode());
    final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (getResultCode() != Activity.RESULT_OK) {
                statusCode.set(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
            }
            sentLatch.countDown();
        }
    };
    deskDroidService.registerReceiver(receiver, new IntentFilter("com.steeplesoft.deskdroid.SMS_SENT"));
    ArrayList<PendingIntent> sentPIs = new ArrayList<>();
    for (int i = 0; i < parts.size(); i++) {
        sentPIs.add(PendingIntent.getBroadcast(deskDroidService.getApplicationContext(), 0,
                new Intent("com.steeplesoft.deskdroid.SMS_SENT"), 0));
    }
    sms.sendMultipartTextMessage(message.getAddress(), null, parts, sentPIs, null);

    sentLatch.await(5, TimeUnit.SECONDS);
    deskDroidService.unregisterReceiver(receiver);
    return Response.status(statusCode.get()).build();

}
 
Example 54
Project: syndesis   File: JsonDBResource.java   Source Code and License 5 votes vote down vote up
@Produces({APPLICATION_JSON, APPLICATION_JAVASCRIPT})
@Path("/{path: .*}.json")
@GET
public Response get(
    @PathParam("path") String path,
    @QueryParam("print") String print,
    @QueryParam("shallow") Boolean shallow,
    @QueryParam("callback") String callback
) {
    GetOptions options = new GetOptions();
    if ("pretty".equals(print)) {
        options.prettyPrint(true);
    } else if ("silent".equals(print)) {
        if( jsondb.exists(path) ) {
            return Response.noContent().build();
        }

        return Response.status(Response.Status.NOT_FOUND).build();
    }
    if( shallow!=null ) {
        options.depth(1);
    }

    String contentType = APPLICATION_JSON;
    if( callback!=null ) {
        contentType = APPLICATION_JAVASCRIPT;
        options.callback(callback);
    }

    Consumer<OutputStream> stream = jsondb.getAsStreamingOutput(path, options);
    if( stream == null ) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }

    StreamingOutput streamingOutput = x-> stream.accept(x);
    return Response.ok(streamingOutput).header(CONTENT_TYPE, contentType).build();
}
 
Example 55
Project: redirector   File: UrlRulesControllerIntegrationTest.java   Source Code and License 5 votes vote down vote up
UrlRuleSteps exportUrlRuleForNonExistentUrlRuleAndVerifyResponseIsUrlRuleNotFound() {
    try {
        apiFacade.exportUrlRuleForServiceById(serviceName, NON_EXISTENT_URLRULE);
    } catch (WebApplicationException exception) {
        Assert.assertEquals(exception.getResponse().getStatus(), Response.Status.NOT_FOUND.getStatusCode());
    }
    return this;
}
 
Example 56
Project: swaggy-jenkins   File: BlueApi.java   Source Code and License 5 votes vote down vote up
@GET
@Path("/rest/organizations/{organization}/pipelines/{pipeline}/runs/{run}")

@Produces({ "application/json" })
@ApiOperation(value = "", notes = "Retrieve run details for an organization pipeline", response = PipelineRun.class, authorizations = {
    @Authorization(value = "jenkins_auth")
}, tags={ "blueOcean",  })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "Successfully retrieved run details", response = PipelineRun.class),
    @ApiResponse(code = 401, message = "Authentication failed - incorrect username and/or password", response = PipelineRun.class),
    @ApiResponse(code = 403, message = "Jenkins requires authentication - please set username and password", response = PipelineRun.class) })
public Response getPipelineRun(@ApiParam(value = "Name of the organization",required=true) @PathParam("organization") String organization, @ApiParam(value = "Name of the pipeline",required=true) @PathParam("pipeline") String pipeline, @ApiParam(value = "Name of the run",required=true) @PathParam("run") String run) {
    return delegate.getPipelineRun(organization, pipeline, run, securityContext);
}
 
Example 57
Project: jwala   File: MediaServiceRestImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Response createMedia(final List<Attachment> attachments) {
    LOGGER.info("createMedia {}", attachments);
    if (attachments == null || attachments.isEmpty()) {
        LOGGER.error("Expected non-empty attachments. Returning without creating Media.");
        return Response.status(Response.Status.BAD_REQUEST).build();
    }

    final Map<String, String> mediaDataMap = new HashMap<>();
    final Map<String, Object> mediaFileDataMap = new HashMap<>();
    attachments.forEach(attachment -> {
        try {
            // when using the REST API from Chef a null attachment gets added somewhere between the execute_rest and here
            if (attachment.getHeaders().size() < 2) {
                return;
            }
            if (attachment.getHeader("Content-Type") == null) {
                mediaDataMap.put(attachment.getDataHandler().getName(),
                        IOUtils.toString(attachment.getDataHandler().getInputStream(), Charset.defaultCharset()));
            } else {
                mediaFileDataMap.put("filename", attachment.getDataHandler().getName());
                mediaFileDataMap.put("content", new BufferedInputStream(attachment.getDataHandler().getInputStream()));
            }
        } catch (final IOException e) {
            LOGGER.error("Failed to retrieve attachments!", e);
            Response.status(Response.Status.BAD_REQUEST).build();
        }
    });

    return ResponseBuilder.created(mediaService.create(mediaDataMap, mediaFileDataMap));
}
 
Example 58
Project: abhot   File: MetricsResource.java   Source Code and License 5 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON + "; charset=UTF-8")
@Path("/aggregators")
public Response getAggregators()
{
    ImmutableList<AggregatorMetadata> aggregatorMetadata = aggregatorFactory.getAggregatorMetadata();
    ResponseBuilder responseBuilder = Response.status(Response.Status.OK).entity(gson.toJson(aggregatorMetadata));
    setHeaders(responseBuilder);
    return responseBuilder.build();
}
 
Example 59
Project: athena   File: VirtualNetworkWebResource.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the virtual networks with the specified tenant identifier.
 *
 * @param tenantId tenant identifier
 * @return 200 OK with a virtual network, 404 not found
 * @onos.rsModel VirtualNetworks
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{tenantId}")
public Response getVirtualNetworkById(@PathParam("tenantId") String tenantId) {
    final TenantId existingTid = TenantWebResource.getExistingTenantId(vnetAdminService,
                                                                       TenantId.tenantId(tenantId));
    Set<VirtualNetwork> vnets = vnetService.getVirtualNetworks(existingTid);
    return ok(encodeArray(VirtualNetwork.class, "vnets", vnets)).build();
}
 
Example 60
Project: openNaEF   File: ConfigurableMvoApiTest.java   Source Code and License 5 votes vote down vote up
public static Map<String, Object> assertLink(Response res, String name, String port1, String port2) {
    Map<String, Object> actual = JSON.decode(res.readEntity(String.class));

    assertEquals(name, actual.get("name"));

    List<Map<String, String>> memberPorts = (List<Map<String, String>>) actual.get("member_ports");
    long ports = memberPorts.stream().filter(p -> {
        String id = p.get("id");
        return id.equals(port1) || id.equals(port2);
    }).count();
    assertEquals(2, memberPorts.size());
    assertEquals(2, ports);
    return actual;
}