コード例 #1
0
 @GET
 @Produces(
     com.smartitengineering.util.opensearch.jaxrs.MediaType.APPLICATION_OPENSEARCHDESCRIPTION_XML)
 public Response getSpec() {
   OpenSearchDescriptorBuilder descBuilder = OpenSearchDescriptorBuilder.getBuilder();
   descBuilder.shortName("Content Search");
   descBuilder.description("Search the content repository for contents!");
   StringBuilder templateBuilder = getSearchUri(true);
   final String urlTemplate = templateBuilder.toString();
   if (logger.isDebugEnabled()) {
     logger.debug("Template URL: " + urlTemplate);
   }
   UrlBuilder xmlBuilder =
       UrlBuilder.getBuilder()
           .rel(RelEnum.RESULTS)
           .indexOffset(start)
           .template(urlTemplate)
           .type(MediaType.APPLICATION_ATOM_XML);
   UrlBuilder jsonBulder =
       UrlBuilder.getBuilder()
           .rel(RelEnum.RESULTS)
           .indexOffset(start)
           .template(urlTemplate)
           .type(MediaType.APPLICATION_JSON);
   descBuilder.urls(xmlBuilder.build(), jsonBulder.build());
   ResponseBuilder builder = Response.ok(descBuilder.build());
   return builder.build();
 }
コード例 #2
0
ファイル: UserService.java プロジェクト: LADOSS-IFPB/ForCode
  @RolesAllowed(value = {"Admin"})
  @POST
  @Path("/updateadmin")
  @Consumes("application/json")
  @Produces("application/json")
  public Response updateAdmin(Admin admin) {
    UserDAO userDAO = new UserDAO();
    ResponseBuilder builder;

    ForCodeError error = ForCodeValidator.validateUpdate(admin);
    try {
      if (error == null) {
        userDAO.update(admin);
        builder = Response.status(Response.Status.OK).entity(admin);
        logger.info("Admin updated.");
      } else {
        System.out.println(error.getMessage());
        builder = Response.status(Response.Status.CONFLICT).entity(error);
        logger.info("Conflict while trying to update Admin.");
      }
    } catch (ForCodeDataException fde) {
      logger.warn(fde.getMessage());
      builder = Response.status(Response.Status.BAD_REQUEST).entity(fde);
    }

    return builder.build();
  }
コード例 #3
0
ファイル: UserService.java プロジェクト: LADOSS-IFPB/ForCode
  @PermitAll
  @POST
  @Path("/searchinstitution")
  @Consumes("application/json")
  @Produces("application/json")
  public Response searchInstitution(String institutionName) {

    logger.info("Searching for institution " + institutionName);

    Institution institution = this.findInstitution(institutionName);

    ResponseBuilder builder;

    if (institution == null) {
      ForCodeError error = ErrorFactory.getErrorFromIndex(ErrorFactory.INSTITUTION_NOT_FOUND);
      builder = Response.status(Response.Status.NOT_FOUND).entity(error);

      logger.info("Unsuccessful attempt to find institution.");
    } else {
      builder = Response.status(Response.Status.FOUND).entity(institution);

      logger.info("Successful attempt to find institution.");
    }

    return builder.build();
  }
コード例 #4
0
ファイル: UserService.java プロジェクト: LADOSS-IFPB/ForCode
  @RolesAllowed(value = {"Admin"})
  @POST
  @Path("/createinstitute")
  @Consumes("application/json")
  @Produces("application/json")
  public Response createInstitution(Institution institution) {
    InstitutionDAO userDAO = new InstitutionDAO();
    ResponseBuilder builder;

    ForCodeError error = ForCodeValidator.validate(institution);

    try {
      if (error == null) {
        userDAO.insert(institution);
        builder = Response.status(Response.Status.OK).entity(institution);
        logger.info("New institution registered.");
      } else {
        System.out.println(error.getMessage());
        builder = Response.status(Response.Status.CONFLICT).entity(error);
        logger.info("Conflict while trying to register new institute.");
      }
    } catch (ForCodeDataException fde) {
      logger.warn(fde.getMessage());
      builder = Response.status(Response.Status.BAD_REQUEST).entity(fde);
    }

    return builder.build();
  }
コード例 #5
0
  @GET
  @Produces(MediaType.TEXT_HTML)
  public Response detailView(@Context HttpServletRequest request) {

    ModelAndView view;
    ModelMap model = new ModelMap();
    ResponseBuilder builder;

    try {
      model.addAttribute("title", "Account Settings - " + getContextName());
      model.addAttribute("user", getCurrentUser());
      model.addAttribute("currentView", "detail");

      addFlashMessage(request, model);

      view = new ModelAndView("user.detail", model);
      builder = Response.ok();
    } catch (UserNotFoundException e) {
      logger.warn("User not found", e);

      view = buildErrorView(Status.INTERNAL_SERVER_ERROR, e.getMessage());
      builder = Response.serverError();
    }

    return builder.entity(view).build();
  }
コード例 #6
0
ファイル: UserService.java プロジェクト: LADOSS-IFPB/ForCode
  @PermitAll
  @GET
  @Path("/searchuser")
  @Consumes("application/json")
  @Produces("application/json")
  public Response searchUser(@QueryParam("q") String username) {

    logger.info("Searching for user " + username);

    User user = this.findUser(username);

    ResponseBuilder builder;

    if (user == null) {
      ForCodeError error = ErrorFactory.getErrorFromIndex(ErrorFactory.USER_NOT_FOUND);
      builder = Response.status(Response.Status.NOT_FOUND).entity(error);

      logger.info("Unsuccessful attempt to find user.");
    } else {

      user.setPassword(null);
      user.setUserKey(null);

      builder = Response.status(Response.Status.FOUND).entity(user);

      logger.info("Successful attempt to find user.");
    }

    return builder.build();
  }
コード例 #7
0
  /**
   * Create Push Application
   *
   * @param pushApp new {@link PushApplication}
   * @return created {@link PushApplication}
   * @statuscode 201 The PushApplication Variant created successfully
   * @statuscode 400 The format of the client request was incorrect
   */
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  @ReturnType("org.jboss.aerogear.unifiedpush.api.PushApplication")
  public Response registerPushApplication(PushApplication pushApp) {

    // some validation
    try {
      validateModelClass(pushApp);
    } catch (ConstraintViolationException cve) {

      // Build and return the 400 (Bad Request) response
      ResponseBuilder builder = createBadRequestResponse(cve.getConstraintViolations());

      return builder.build();
    }

    pushAppService.addPushApplication(pushApp);

    return Response.created(
            UriBuilder.fromResource(PushApplicationEndpoint.class)
                .path(String.valueOf(pushApp.getPushApplicationID()))
                .build())
        .entity(pushApp)
        .build();
  }
コード例 #8
0
ファイル: ListService.java プロジェクト: GugaRibeiro/IFPB
  @PermitAll
  @GET
  @Path("/contestbyid")
  @Consumes("application/json")
  @Produces("application/json")
  public Response seachContestById(@QueryParam("q") Integer idContest) {
    ContestDAO contestDao = new ContestDAO();
    ResponseBuilder builder;

    logger.info("Searching for contest " + idContest);
    try {
      Contest contest = contestDao.getById(idContest);

      if (contest == null) {
        ForCodeError error = ErrorFactory.getErrorFromIndex(ErrorFactory.CONTEST_NOT_EXISTENT);
        builder = Response.status(Response.Status.NOT_FOUND).entity(error);
      } else {
        builder = Response.status(Response.Status.OK).entity(contest);
      }
    } catch (ForCodeDataException fde) {
      logger.warn(fde.getMessage());
      builder = Response.status(Response.Status.BAD_REQUEST).entity(fde);
    }

    return builder.build();
  }
コード例 #9
0
ファイル: UserService.java プロジェクト: LADOSS-IFPB/ForCode
  @RolesAllowed(value = {"Manager"})
  @POST
  @Path("/invalidatecontestant")
  @Consumes("application/json")
  @Produces("application/json")
  public Response invalidateContestant(UserContest contestant) {
    UserContestDAO userContestDao = new UserContestDAO();
    ResponseBuilder builder;

    try {
      contestant = userContestDao.getById(contestant.getIdUserContest());
      logger.info("Invalidating contestant");

      if (contestant == null) {
        logger.info("Contestant not found");
        ForCodeError error = ErrorFactory.getErrorFromIndex(ErrorFactory.USER_CONTEST_NOT_FOUND);
        builder = Response.status(Response.Status.NOT_FOUND).entity(error);

      } else {
        contestant.setValid(false);
        userContestDao.update(contestant);

        logger.info("Contestant invalidated " + contestant.getUser().getUsername());
        builder = Response.status(Response.Status.ACCEPTED).entity(contestant);
      }
    } catch (ForCodeDataException fde) {
      logger.warn(fde.getMessage());
      builder = Response.status(Response.Status.BAD_REQUEST).entity(fde);
    }
    return builder.build();
  }
コード例 #10
0
  /**
   * Update Push Application
   *
   * @param pushApplicationID id of {@link PushApplication}
   * @param updatedPushApp new info of {@link PushApplication}
   * @statuscode 204 The PushApplication updated successfully
   * @statuscode 400 The format of the client request was incorrect
   * @statuscode 404 The requested PushApplication resource does not exist
   */
  @PUT
  @Path("/{pushAppID}")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  @ReturnType("java.lang.Void")
  public Response updatePushApplication(
      @PathParam("pushAppID") String pushApplicationID, PushApplication updatedPushApp) {

    PushApplication pushApp = getSearch().findByPushApplicationIDForDeveloper(pushApplicationID);

    if (pushApp != null) {

      // some validation
      try {
        validateModelClass(updatedPushApp);
      } catch (ConstraintViolationException cve) {

        // Build and return the 400 (Bad Request) response
        ResponseBuilder builder = createBadRequestResponse(cve.getConstraintViolations());

        return builder.build();
      }

      // update name/desc:
      pushApp.setDescription(updatedPushApp.getDescription());
      pushApp.setName(updatedPushApp.getName());
      pushAppService.updatePushApplication(pushApp);

      return Response.noContent().build();
    }

    return Response.status(Status.NOT_FOUND)
        .entity("Could not find requested PushApplicationEntity")
        .build();
  }
コード例 #11
0
  /**
   * Get Push Application.
   *
   * @param pushApplicationID id of {@link PushApplication}
   * @param includeDeviceCount boolean param to put device count into response headers, default
   *     {@code false}
   * @param includeActivity boolean param to put activity into response headers, default {@code
   *     false}
   * @return requested {@link PushApplication}
   * @responseheader activity_app_{pushApplicationID} Count number of messages for Push Application
   * @responseheader activity_variant_{variantID} Count number of messages for Variant
   * @responseheader deviceCount_app_{pushApplicationID} Count number of devices for Push
   *     Application
   * @responseheader deviceCount_variant_{variantID} Count number of devices for Variant
   * @statuscode 404 The requested PushApplication resource does not exist
   */
  @GET
  @Path("/{pushAppID}")
  @Produces(MediaType.APPLICATION_JSON)
  @ReturnType("org.jboss.aerogear.unifiedpush.api.PushApplication")
  public Response findById(
      @PathParam("pushAppID") String pushApplicationID,
      @QueryParam("includeDeviceCount") @DefaultValue("false") boolean includeDeviceCount,
      @QueryParam("includeActivity") @DefaultValue("false") boolean includeActivity) {

    PushApplication pushApp = getSearch().findByPushApplicationIDForDeveloper(pushApplicationID);

    if (pushApp != null) {
      ResponseBuilder response = Response.ok(pushApp);
      if (includeActivity) {
        putActivityIntoResponseHeaders(pushApp, response);
      }
      if (includeDeviceCount) {
        putDeviceCountIntoResponseHeaders(pushApp, response);
      }
      return response.build();
    }

    return Response.status(Status.NOT_FOUND)
        .entity("Could not find requested PushApplicationEntity")
        .build();
  }
コード例 #12
0
ファイル: UserService.java プロジェクト: LADOSS-IFPB/ForCode
  @PermitAll
  @POST
  @Path("/createcontestant")
  @Consumes("application/json")
  @Produces("application/json")
  public Response createContestant(Contestant contestant) {
    UserDAO userDAO = new UserDAO();
    ResponseBuilder builder;

    ForCodeError error = ForCodeValidator.validateInsertion(contestant);
    try {
      if (error == null) {
        userDAO.insert(contestant);
        builder = Response.status(Response.Status.OK).entity(contestant);
        logger.info("New Contestant registered.");
      } else {
        System.out.println(error.getMessage());
        builder = Response.status(Response.Status.CONFLICT).entity(error);
        logger.info("Conflict while trying to register new contestant.");
      }
    } catch (ForCodeDataException fde) {
      logger.warn(fde.getMessage());
      builder = Response.status(Response.Status.BAD_REQUEST).entity(fde);
    }

    return builder.build();
  }
コード例 #13
0
  /**
   * List Push Applications
   *
   * @param page page number
   * @param pageSize number of items per page
   * @param includeDeviceCount put device count into response headers, default {@code false}
   * @param includeActivity put activity into response headers, default {@code false}
   * @return list of {@link PushApplication}s
   * @responseheader total Total count of items
   * @responseheader activity_app_{pushApplicationID} Count number of messages for Push Application
   * @responseheader activity_variant_{variantID} Count number of messages for Variant
   * @responseheader deviceCount_app_{pushApplicationID} Count number of devices for Push
   *     Application
   * @responseheader deviceCount_variant_{variantID} Count number of devices for Variant
   */
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  @ReturnType("java.util.List<org.jboss.aerogear.unifiedpush.api.PushApplication>")
  public Response listAllPushApplications(
      @QueryParam("page") Integer page,
      @QueryParam("per_page") Integer pageSize,
      @QueryParam("includeDeviceCount") @DefaultValue("false") boolean includeDeviceCount,
      @QueryParam("includeActivity") @DefaultValue("false") boolean includeActivity) {
    if (pageSize != null) {
      pageSize = Math.min(MAX_PAGE_SIZE, pageSize);
    } else {
      pageSize = DEFAULT_PAGE_SIZE;
    }

    if (page == null) {
      page = 0;
    }

    final PageResult<PushApplication, Count> pageResult =
        getSearch().findAllPushApplicationsForDeveloper(page, pageSize);
    ResponseBuilder response = Response.ok(pageResult.getResultList());
    response.header("total", pageResult.getAggregate().getCount());
    for (PushApplication app : pageResult.getResultList()) {
      if (includeActivity) {
        putActivityIntoResponseHeaders(app, response);
      }
      if (includeDeviceCount) {
        putDeviceCountIntoResponseHeaders(app, response);
      }
    }
    return response.build();
  }
コード例 #14
0
  private Response launch(String yaml, EntitySpec<? extends Application> spec) {
    try {
      Application app = EntityManagementUtils.createUnstarted(mgmt(), spec);
      CreationResult<Application, Void> result = EntityManagementUtils.start(app);

      boolean isEntitled =
          Entitlements.isEntitled(
              mgmt().getEntitlementManager(),
              Entitlements.INVOKE_EFFECTOR,
              EntityAndItem.of(app, StringAndArgument.of(Startable.START.getName(), null)));

      if (!isEntitled) {
        throw WebResourceUtils.unauthorized(
            "User '%s' is not authorized to start application %s",
            Entitlements.getEntitlementContext().user(), spec.getType());
      }

      log.info("Launched from YAML: " + yaml + " -> " + app + " (" + result.task() + ")");

      URI ref = URI.create(app.getApplicationId());
      ResponseBuilder response = created(ref);
      if (result.task() != null) response.entity(TaskTransformer.FROM_TASK.apply(result.task()));
      return response.build();
    } catch (ConstraintViolationException e) {
      throw new UserFacingException(e);
    } catch (Exception e) {
      throw Exceptions.propagate(e);
    }
  }
コード例 #15
0
  @RolesAllowed("user")
  @POST
  @Path("/create")
  @Consumes("application/json")
  @Produces("application/json")
  public Response createDebate(NewPolarizedRoom newDebate) {

    logger.info("Starting new room creating");

    OpiningError error = new PolarizedRoomValidation().validateInsertion(newDebate);
    ResponseBuilder builder;

    if (error == null) {

      UserDAO userDAO = new UserDAO();
      User user = userDAO.getByLogin(newDebate.getCreator().getLogin());
      newDebate.setCreator(user);

      PolarizedRoom polarizedRoom = newDebate.toPolarizedRoom();

      PolarizedRoomDAO polarizedRoomDAO = new PolarizedRoomDAO();
      polarizedRoomDAO.insert(polarizedRoom);

      builder = Response.status(Response.Status.OK).entity(polarizedRoom);

      logger.info("Room succefully created");

    } else {
      builder = Response.status(Response.Status.CONFLICT).entity(error);
      logger.warn("Room creation is failed with error code: " + error.getCode());
    }

    return builder.build();
  }
コード例 #16
0
ファイル: BasicRESTClient.java プロジェクト: inbloom/java-sdk
  /*
   * (non-Javadoc)
   *
   * @see org.slc.sli.api.client.impl.IRESTClient#connect(java.lang.String, java.lang.String)
   */
  @Override
  public Response connect(final String authorizationCode)
      throws OAuthException, MalformedURLException, URISyntaxException {
    OAuthService service =
        new ServiceBuilder()
            .provider(SliApi.class)
            .apiKey(config.getApiKey())
            .apiSecret(config.getApiSecret())
            .callback(config.getCallback())
            .build();
    Verifier verifier = new Verifier(authorizationCode);
    Token t = null;
    SliApi.TokenResponse r =
        ((SliApi.SLIOauth20ServiceImpl) service)
            .getAccessToken(new Token(config.getApiSecret(), authorizationCode), verifier, t);

    if (r != null && r.getToken() != null) {
      accessToken = r.getToken();
      sessionToken = accessToken.getToken();
    }

    ResponseBuilder builder = Response.status(r.getOauthResponse().getCode());
    for (Map.Entry<String, String> entry : r.getOauthResponse().getHeaders().entrySet()) {
      if (entry.getKey() == null) {
        builder.header("Status", entry.getValue());
      } else {
        builder.header(entry.getKey(), entry.getValue());
      }
    }
    builder.entity(r.getOauthResponse().getBody());

    return builder.build();
  }
コード例 #17
0
ファイル: FedoraContent.java プロジェクト: kaisternad/fcrepo4
  /**
   * Modify an existing datastream's content
   *
   * @param pathList
   * @param requestContentType Content-Type header
   * @param requestBodyStream Binary blob
   * @return 201 Created
   * @throws RepositoryException
   * @throws InvalidChecksumException
   */
  @PUT
  @Timed
  public Response modifyContent(
      @PathParam("path") final List<PathSegment> pathList,
      @QueryParam("checksum") final String checksum,
      @HeaderParam("Content-Disposition") final String contentDisposition,
      @HeaderParam("Content-Type") final MediaType requestContentType,
      @ContentLocation final InputStream requestBodyStream,
      @Context final Request request,
      @Context final HttpServletResponse servletResponse)
      throws RepositoryException, InvalidChecksumException, URISyntaxException, ParseException {

    try {
      final String path = toPath(pathList);
      final MediaType contentType = getSimpleContentType(requestContentType);

      if (nodeService.exists(session, path)) {

        final Datastream ds = datastreamService.getDatastream(session, path);

        evaluateRequestPreconditions(request, ds);
      }

      LOGGER.debug("create Datastream {}", path);

      final URI checksumURI = checksumURI(checksum);
      final String originalFileName = originalFileName(contentDisposition);

      final Datastream datastream =
          datastreamService.createDatastream(
              session,
              path,
              contentType.toString(),
              originalFileName,
              requestBodyStream,
              checksumURI);

      final boolean isNew = datastream.isNew();
      session.save();
      versionService.nodeUpdated(datastream.getNode());

      ResponseBuilder builder;
      if (isNew) {
        final HttpIdentifierTranslator subjects =
            new HttpIdentifierTranslator(session, FedoraNodes.class, uriInfo);

        builder =
            created(new URI(subjects.getSubject(datastream.getContentNode().getPath()).getURI()));
      } else {
        builder = noContent();
      }

      addCacheControlHeaders(servletResponse, datastream);

      return builder.build();
    } finally {
      session.logout();
    }
  }
コード例 #18
0
 @GET
 @Path("{search_id:[0-9]+}/allids")
 @Produces(UTF8MediaType.APPLICATION_JSON)
 public Response getAllSearchResultIds(@PathParam("search_id") long searchId) {
   List<String> searchResultIds = searchService.getAllSearchResultIds(searchId);
   ResponseBuilder builder = Response.ok(searchResultIds);
   return builder.build();
 }
コード例 #19
0
 @Override
 public Response toResponse(LocationBaseException exception) {
   ResponseBuilder rb = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
   rb.type("application/json;charset=UTF-8");
   rb.entity(exception);
   Response r = rb.build();
   return r;
 }
コード例 #20
0
 @POST
 @Consumes(MediaType.APPLICATION_JSON)
 public Response contactSAV(Mail mail) {
   emailService.envoiEmailSAV(mail.getObject(), mail.getMsg(), mail.getExpediteur());
   ResponseBuilder builder = Response.ok();
   builder.status(200);
   return builder.build();
 }
コード例 #21
0
 private void putDeviceCountIntoResponseHeaders(PushApplication app, ResponseBuilder response) {
   long appCount = 0;
   for (Variant variant : app.getVariants()) {
     long variantCount = installationDao.getNumberOfDevicesForVariantID(variant.getVariantID());
     appCount += variantCount;
     response.header("deviceCount_variant_" + variant.getVariantID(), variantCount);
   }
   response.header("deviceCount_app_" + app.getPushApplicationID(), appCount);
 }
コード例 #22
0
  public void handleValidationException(ValidationException exception, ResponseBuilder builder) {
    builder.status(BAD_REQUEST);
    ValidationErrorMessageWrapper error = new ValidationErrorMessageWrapper();

    for (ConstraintViolation<Object> violation : exception.getViolations()) {
      error.addMessage(violation.getMessage());
    }
    builder.entity(error);
  }
コード例 #23
0
 @POST
 @Path("/delete")
 public Response deletePost() {
   UserPerson userPersonForDelete = userPerson;
   Services.getInstance().getUserPersonService().delete(userPersonForDelete);
   Services.getInstance().getUserService().delete(userPersonForDelete.getUser());
   Services.getInstance().getPersonService().delete(userPersonForDelete.getPerson());
   ResponseBuilder responseBuilder = Response.ok();
   return responseBuilder.build();
 }
コード例 #24
0
 @GET
 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
 @Path("{id}")
 public final Response get(@PathParam("id") long id, @Context HttpServletRequest httpRequest) {
   final FormBean form = dbManager.selectFormBean(id);
   final ResponseBuilder builder =
       form != null ? Response.ok(form) : Response.status(Status.NOT_FOUND);
   final Response response = builder.build();
   return response;
 }
コード例 #25
0
  /**
   * @param req
   * @param returnMethod
   * @return a cors-ed response object.
   */
  private static Response toCORS(final ResponseBuilder req, final String returnMethod) {
    final ResponseBuilder rb =
        req.header("Access-Control-Allow-Origin", "*")
            .header("Access-Control-Allow-Methods", "GET, PUT, OPTIONS");

    if (returnMethod != null && !returnMethod.isEmpty())
      rb.header("Access-Control-Allow-Headers", returnMethod);

    return rb.build();
  }
コード例 #26
0
ファイル: CompositeResource.java プロジェクト: winsx/Payara
 protected Response accepted(ResponseBody rb, URI jobUri, URI newItemUri) {
   ResponseBuilder bldr = Response.status(Status.ACCEPTED).entity(rb);
   if (jobUri != null) {
     bldr.header("Location", jobUri);
   }
   if (newItemUri != null) {
     bldr.header("X-Location", newItemUri);
   }
   return bldr.build();
 }
コード例 #27
0
 private void putActivityIntoResponseHeaders(PushApplication app, ResponseBuilder response) {
   response.header(
       "activity_app_" + app.getPushApplicationID(),
       metricsService.countMessagesForPushApplication(app.getPushApplicationID()));
   for (Variant variant : app.getVariants()) {
     response.header(
         "activity_variant_" + variant.getVariantID(),
         metricsService.countMessagesForVariant(variant.getVariantID()));
   }
 }
コード例 #28
0
  @GET
  @Produces({"application/xml", "application/json"})
  @Path("/{assettype}")
  public Response getChecksums(
      @PathParam("modulename") String moduleName, @PathParam("modulePart") String modulePart) {
    ChecksumList checksumList = getChecksumList(moduleName, modulePart);

    ResponseBuilder rb = Response.ok(checksumList);
    return rb.build();
  }
コード例 #29
0
ファイル: PieResourceTest.java プロジェクト: NCIP/cacore-sdk
  public void testPie1() {
    try {

      String url = baseURL + "/rest/Pie/search;id=*/utensilCollection";

      WebClient client = WebClient.create(url);
      client.type("application/xml").accept("application/xml");
      Response response = client.get();

      if (response.getStatus() == Status.NOT_ACCEPTABLE.getStatusCode()) {
        InputStream is = (InputStream) response.getEntity();
        org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false);
        org.jdom.Document jDoc = builder.build(is);
        assertEquals(jDoc.getRootElement().getName(), "response");
      } else if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
        InputStream is = (InputStream) response.getEntity();
        org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false);
        org.jdom.Document jDoc = builder.build(is);
        assertEquals(jDoc.getRootElement().getName(), "response");
      } else if (response.getStatus() != 200) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
      }

      File myFile = new File("Pie_Search" + "XML.xml");
      System.out.println("writing data to file " + myFile.getAbsolutePath());
      FileWriter myWriter = new FileWriter(myFile);

      BufferedReader br =
          new BufferedReader(new InputStreamReader(((InputStream) response.getEntity())));

      String output;
      System.out.println("Output from Server .... \n");
      while ((output = br.readLine()) != null) {
        myWriter.write(output);
        System.out.println(output);
      }

      myWriter.flush();
      myWriter.close();

    } catch (Exception e) {
      e.printStackTrace();
      ResponseBuilder builder = Response.status(Status.INTERNAL_SERVER_ERROR);
      builder.type("application/xml");
      StringBuffer buffer = new StringBuffer();
      buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
      buffer.append("<response>");
      buffer.append("<type>ERROR</type>");
      buffer.append("<code>INTERNAL_ERROR_4</code>");
      buffer.append("<message>Failed to Query due to: " + e.getMessage() + "</message>");
      buffer.append("</response>");
      builder.entity(buffer.toString());
      throw new WebApplicationException(builder.build());
    }
  }
コード例 #30
0
  @Override
  public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {

    ResponseBuilder responseBuilder = Response.fromResponse(response.getResponse());

    responseBuilder.header(ACCESS_CONTROL_ALLOW_ORIGIN, this.origin);

    response.setResponse(responseBuilder.build());

    return response;
  }