Java 类javax.ws.rs.core.Response 实例源码

项目:message-broker    文件:QueuesApiDelegate.java   
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);
    }
}
项目:swaggy-jenkins    文件:BlueApi.java   
@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);
    }
项目:microprofile-jwt-auth    文件:ProviderInjectionTest.java   
@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"));
}
项目:trellis    文件:PutHandlerTest.java   
@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));
}
项目:osc-core    文件:ManagerConnectorApis.java   
@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;
}
项目:Equella    文件:ItemResourceImpl.java   
@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();
}
项目:Celebino    文件:UserController.java   
/**
 * 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();
}
项目:lyre    文件:EndpointService.java   
@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();
}
项目:keycloak-jaxrs-client-authfilter    文件:BearerAuthFilter.java   
@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 );
        }
      }
    }
  }
}
项目:lra-service    文件:LRAService.java   
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();
    }
}
项目:incubator-freemarker-online-tester    文件:ExecuteApiResourceTest.java   
@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"));
}
项目:jobson    文件:TestJobsAPI.java   
@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();
}
项目:dubbo2    文件:RestClient.java   
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();
    }
}
项目:plugin-redirect    文件:RedirectResourceTest.java   
@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"));
}
项目:swaggy-jenkins    文件:BlueApi.java   
@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);
    }
项目:hadoop-oss    文件:KMS.java   
@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();
}
项目:verify-hub    文件:EidasCycle3DataResourceTest.java   
@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);
}
项目:javaee8-jaxrs-sample    文件:PostResourceIT.java   
@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);
    }

}
项目:personium-core    文件:PersoniumCoreContainerFilter.java   
/**
 * 認証なし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);
    }
}
项目:athena    文件:StatisticsWebResource.java   
/**
 * 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();
}
项目:redpipe    文件:ApiResource.java   
@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();
            });
}
项目:SistemaAlmoxarifado    文件:UsuarioResource.java   
@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();
}
项目:sample-acmegifts    文件:AuthResourceTest.java   
/**
 * 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);
}
项目:swaggy-jenkins    文件:BlueApi.java   
@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);
    }
项目:comms-router    文件:TaskResource.java   
@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();
}
项目:Equella    文件:FileResource.java   
@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;
项目:servicebuilder    文件:ConstraintViolationExceptionMapper.java   
@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)
    );
}
项目:holon-json    文件:TestResteasyIntegrationContext.java   
@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());

}
项目:trellis    文件:DeleteHandlerTest.java   
@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());
}
项目:opencps-v2    文件:ServiceProcessManagement.java   
@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);
项目:act-platform    文件:ExceptionMappingsTest.java   
@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");
}
项目:act-platform    文件:OperationTimeoutMapper.java   
@Override
public Response toResponse(OperationTimeoutException ex) {
  return ResultStash.builder()
          .setStatus(Response.Status.REQUEST_TIMEOUT)
          .addActionError(ex.getMessage(), ex.getMessageTemplate())
          .buildResponse();
}
项目:trellis    文件:AbstractLdpResourceTest.java   
@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());
}
项目:osc-core    文件:ServerMgmtApis.java   
/**
 * 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);
}
项目:agilion    文件:SessionApi.java   
@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);
}
项目:Pet-Supply-Store    文件:LoadBalancedRecommenderOperations.java   
/**
 * 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<>();
    }
}
项目:swaggy-jenkins    文件:BlueApiServiceImpl.java   
@Override
    public Response postPipelineRuns(String organization
, String pipeline
 ) throws NotFoundException {
        // do some magic!
        return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build();
    }
项目:redirector    文件:PendingChangesControllerOffline.java   
@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();
}
项目:ats-framework    文件:MonitoringServiceImpl.java   
@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();
    }

}
项目:karate    文件:JerseyHttpClient.java   
@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;
}