public static String getContentType(HttpHeaders headers) {
    Variant v = getVariant(headers);
    String contentType = v.getMediaType().getSubtype();

    List<String> kieContentTypeHeader =
        headers.getRequestHeader(KieServerConstants.KIE_CONTENT_TYPE_HEADER);
    if (kieContentTypeHeader != null && !kieContentTypeHeader.isEmpty()) {
      contentType = kieContentTypeHeader.get(0);
    }

    return contentType;
  }
 public Object getTasks(
     Request request, UriInfo uriInfo, Integer firstResult, Integer maxResults) {
   Variant variant = request.selectVariant(VARIANTS);
   if (variant != null) {
     if (MediaType.APPLICATION_JSON_TYPE.equals(variant.getMediaType())) {
       return getJsonTasks(uriInfo, firstResult, maxResults);
     } else if (Hal.APPLICATION_HAL_JSON_TYPE.equals(variant.getMediaType())) {
       return getHalTasks(uriInfo, firstResult, maxResults);
     }
   }
   throw new InvalidRequestException(
       Response.Status.NOT_ACCEPTABLE, "No acceptable content-type found");
 }
 public static boolean isPaged(HttpServletRequest httpRequest, Request request) {
   String accept = httpRequest.getHeader("Accept");
   if (StringHelper.containsNonWhitespace(accept)) {
     MediaType requestMediaType = MediaType.valueOf(accept);
     if (APPLICATION_JSON_PAGED.equals(requestMediaType)
         || APPLICATION_XML_PAGED.equals(requestMediaType)) {
       return true;
     }
   }
   Variant variant = request.selectVariant(variants);
   return (variant != null
       && (variant.equals(APPLICATION_JSON_PAGED) || variant.equals(APPLICATION_XML_PAGED)));
 }
@Singleton
@Provider
public class WebApplicationExceptionMapper implements ExceptionMapper<WebApplicationException> {
  private static final Logger LOG = LoggerFactory.getLogger(GenericExceptionMapper.class);
  private static List<Variant> supportedMediaTypes =
      Variant.mediaTypes(MediaType.APPLICATION_JSON_TYPE, MediaType.TEXT_HTML_TYPE).add().build();

  @Context private HttpContext context;

  public WebApplicationExceptionMapper() {
    LOG.info("GenericExceptionMapper Created");
  }

  @Override
  public Response toResponse(WebApplicationException error) {
    if (error.getResponse() != null && (error.getResponse().getStatus() / 100) == 3) {
      LOG.warn("Code: " + error.getResponse().getStatus());
      return error.getResponse();
    }

    MediaType mediaType = context.getRequest().selectVariant(supportedMediaTypes).getMediaType();
    if (mediaType != null && MediaType.APPLICATION_JSON_TYPE == mediaType) {
      try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);
        error.printStackTrace(ps);

        return Response.status(error.getResponse().getStatus())
            .entity(
                new JSONObject()
                    .put("code", error.getResponse().getStatus())
                    .put("url", context.getUriInfo().getPath())
                    .put("error", error.toString())
                    .put("message", error.getMessage())
                    .put("trace", baos.toString()))
            .build();
      } catch (JSONException e) {
        // TODO:
      }
    }

    final int statusCode = error.getResponse().getStatus();
    if (statusCode == Responses.NOT_FOUND) {
      return Response.status(Responses.NOT_FOUND).entity(error.getMessage()).build();
    } else {
      // internal error
      LOG.warn(
          "WebApplicationExceptionMapper "
              + error.getResponse().getStatus()
              + " "
              + error.getMessage(),
          error);
      Map<String, Object> model = Maps.newHashMap();
      model.put("exception", error);
      return Response.status(error.getResponse().getStatus())
          .entity(new Viewable("/errors/internal_error.ftl", model))
          .build();
    }
  }
}
示例#5
0
  private static LinkedList<VariantHolder> getVariantHolderList(final List<Variant> variants) {
    final LinkedList<VariantHolder> l = new LinkedList<VariantHolder>();
    for (Variant v : variants) {
      final MediaType mt = v.getMediaType();
      if (mt != null) {
        if (mt instanceof QualitySourceMediaType
            || mt.getParameters().containsKey(QualitySourceMediaType.QUALITY_SOURCE_FACTOR)) {
          int qs = QualitySourceMediaType.getQualitySource(mt);
          l.add(new VariantHolder(v, qs));
        } else {
          l.add(new VariantHolder(v));
        }
      } else {
        l.add(new VariantHolder(v));
      }
    }

    return l;
  }
 @Test
 public void testGetVersionList() {
   when(mockRequest.selectVariant(POSSIBLE_RDF_VARIANTS)).thenReturn(mockVariant);
   when(mockNodes.find(any(Session.class), anyString())).thenReturn(mockResource);
   when(mockResource.getTriples(any(IdentifierConverter.class), eq(VersionsRdfContext.class)))
       .thenReturn(mockRdfStream);
   when(mockResource.isVersioned()).thenReturn(true);
   when(mockVariant.getMediaType()).thenReturn(new MediaType("text", "turtle"));
   final RdfStream response = testObj.getVersionList();
   assertEquals("Got wrong RdfStream!", mockRdfStream, response);
 }
示例#7
0
 @Test
 public void testGetVersionList() throws RepositoryException {
   final String pid = "FedoraVersioningTest";
   when(mockRequest.selectVariant(POSSIBLE_RDF_VARIANTS)).thenReturn(mockVariant);
   when(mockNodes.getObject(any(Session.class), anyString())).thenReturn(mockResource);
   when(mockResource.getVersionTriples(any(HttpIdentifierTranslator.class)))
       .thenReturn(mockRdfStream);
   when(mockVariant.getMediaType()).thenReturn(new MediaType("text", "turtle"));
   final RdfStream response =
       testObj.getVersionList(createPathList(pid), mockRequest, getUriInfoImpl());
   assertEquals("Got wrong RdfStream!", mockRdfStream, response);
 }
 @Test
 public void testSelectVariant() {
   MutableRequest mr = new MutableRequest("", "http://example.org/app/resource", "GET");
   mr.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
   mr.header(HttpHeaders.ACCEPT_LANGUAGE, "en");
   Request r = mr.toJaxrsRequest();
   List<Variant> lv =
       Variant.mediaTypes(MediaType.APPLICATION_XML_TYPE, MediaType.APPLICATION_JSON_TYPE)
           .languages(Locale.ENGLISH, Locale.FRENCH)
           .add()
           .build();
   assertEquals(r.selectVariant(lv).getMediaType(), MediaType.APPLICATION_JSON_TYPE);
   assertEquals(r.selectVariant(lv).getLanguage(), Locale.ENGLISH);
 }
public class RestUtils {

  public static Variant defaultVariant =
      Variant.mediaTypes(MediaType.APPLICATION_JSON_TYPE).add().build().get(0);
  private static MarshallerHelper marshallerHelper = new MarshallerHelper(null);

  public static Response createCorrectVariant(Object responseObj, HttpHeaders headers) {
    return createCorrectVariant(responseObj, headers, null);
  }

  public static Response createCorrectVariant(
      Object responseObj, HttpHeaders headers, javax.ws.rs.core.Response.Status status) {
    Response.ResponseBuilder responseBuilder = null;
    Variant v = getVariant(headers);
    String contentType = getContentType(headers);

    if (status != null) {
      responseBuilder =
          Response.status(status)
              .entity(marshallerHelper.marshal(contentType, responseObj))
              .variant(v);
    } else {
      responseBuilder = Response.ok(marshallerHelper.marshal(contentType, responseObj), v);
    }
    return responseBuilder.build();
  }

  public static Response createResponse(
      Object responseObj, Variant v, javax.ws.rs.core.Response.Status status) {
    Response.ResponseBuilder responseBuilder = null;
    if (status != null) {
      responseBuilder = Response.status(status).entity(responseObj).variant(v);
    } else {
      responseBuilder = Response.ok(responseObj, v);
    }
    return responseBuilder.build();
  }

  public static Variant getVariant(HttpHeaders headers) {
    Variant v = RestEasy960Util.getVariant(headers);
    if (v == null) {
      v = defaultVariant;
    }
    return v;
  }

  public static String getClassType(HttpHeaders headers) {
    String classType = Object.class.getName();

    List<String> header = headers.getRequestHeader(KieServerConstants.CLASS_TYPE_HEADER);
    if (header != null && !header.isEmpty()) {
      classType = header.get(0);
    }

    return classType;
  }

  public static String getContentType(HttpHeaders headers) {
    Variant v = getVariant(headers);
    String contentType = v.getMediaType().getSubtype();

    List<String> kieContentTypeHeader =
        headers.getRequestHeader(KieServerConstants.KIE_CONTENT_TYPE_HEADER);
    if (kieContentTypeHeader != null && !kieContentTypeHeader.isEmpty()) {
      contentType = kieContentTypeHeader.get(0);
    }

    return contentType;
  }
}
public class TaskRestServiceImpl extends AbstractRestProcessEngineAware implements TaskRestService {

  public static final List<Variant> VARIANTS =
      Variant.mediaTypes(MediaType.APPLICATION_JSON_TYPE, Hal.APPLICATION_HAL_JSON_TYPE)
          .add()
          .build();

  public TaskRestServiceImpl(String engineName, final ObjectMapper objectMapper) {
    super(engineName, objectMapper);
  }

  public Object getTasks(
      Request request, UriInfo uriInfo, Integer firstResult, Integer maxResults) {
    Variant variant = request.selectVariant(VARIANTS);
    if (variant != null) {
      if (MediaType.APPLICATION_JSON_TYPE.equals(variant.getMediaType())) {
        return getJsonTasks(uriInfo, firstResult, maxResults);
      } else if (Hal.APPLICATION_HAL_JSON_TYPE.equals(variant.getMediaType())) {
        return getHalTasks(uriInfo, firstResult, maxResults);
      }
    }
    throw new InvalidRequestException(
        Response.Status.NOT_ACCEPTABLE, "No acceptable content-type found");
  }

  public List<TaskDto> getJsonTasks(UriInfo uriInfo, Integer firstResult, Integer maxResults) {
    TaskQueryDto queryDto = new TaskQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
    return queryTasks(queryDto, firstResult, maxResults);
  }

  public HalTaskList getHalTasks(UriInfo uriInfo, Integer firstResult, Integer maxResults) {
    TaskQueryDto queryDto = new TaskQueryDto(getObjectMapper(), uriInfo.getQueryParameters());

    ProcessEngine engine = getProcessEngine();
    TaskQuery query = queryDto.toQuery(engine);

    // get list of tasks
    List<Task> matchingTasks = executeTaskQuery(firstResult, maxResults, query);

    // get total count
    long count = query.count();

    return HalTaskList.generate(matchingTasks, count, engine);
  }

  @Override
  public List<TaskDto> queryTasks(TaskQueryDto queryDto, Integer firstResult, Integer maxResults) {
    ProcessEngine engine = getProcessEngine();
    queryDto.setObjectMapper(getObjectMapper());
    TaskQuery query = queryDto.toQuery(engine);

    List<Task> matchingTasks = executeTaskQuery(firstResult, maxResults, query);

    List<TaskDto> tasks = new ArrayList<TaskDto>();
    for (Task task : matchingTasks) {
      TaskDto returnTask = TaskDto.fromEntity(task);
      tasks.add(returnTask);
    }

    return tasks;
  }

  protected List<Task> executeTaskQuery(Integer firstResult, Integer maxResults, TaskQuery query) {

    // enable initialization of form key:
    query.initializeFormKeys();

    List<Task> matchingTasks;
    if (firstResult != null || maxResults != null) {
      matchingTasks = executePaginatedQuery(query, firstResult, maxResults);
    } else {
      matchingTasks = query.list();
    }
    return matchingTasks;
  }

  protected List<Task> executePaginatedQuery(
      TaskQuery query, Integer firstResult, Integer maxResults) {
    if (firstResult == null) {
      firstResult = 0;
    }
    if (maxResults == null) {
      maxResults = Integer.MAX_VALUE;
    }
    return query.listPage(firstResult, maxResults);
  }

  @Override
  public CountResultDto getTasksCount(UriInfo uriInfo) {
    TaskQueryDto queryDto = new TaskQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
    return queryTasksCount(queryDto);
  }

  @Override
  public CountResultDto queryTasksCount(TaskQueryDto queryDto) {
    ProcessEngine engine = getProcessEngine();
    queryDto.setObjectMapper(getObjectMapper());
    TaskQuery query = queryDto.toQuery(engine);

    long count = query.count();
    CountResultDto result = new CountResultDto();
    result.setCount(count);

    return result;
  }

  @Override
  public TaskResource getTask(String id) {
    return new TaskResourceImpl(
        getProcessEngine(), id, relativeRootResourcePath, getObjectMapper());
  }

  public void createTask(TaskDto taskDto) {
    ProcessEngine engine = getProcessEngine();
    TaskService taskService = engine.getTaskService();

    Task newTask = taskService.newTask(taskDto.getId());
    taskDto.updateTask(newTask);

    try {
      taskService.saveTask(newTask);

    } catch (NotValidException e) {
      throw new InvalidRequestException(
          Status.BAD_REQUEST, e, "Could not save task: " + e.getMessage());
    }
  }
}
public class RestUtils {

  public static Variant defaultVariant =
      Variant.mediaTypes(MediaType.APPLICATION_JSON_TYPE).add().build().get(0);
  private static MarshallerHelper marshallerHelper = new MarshallerHelper(null);

  public static Response createCorrectVariant(Object responseObj, HttpHeaders headers) {
    return createCorrectVariant(responseObj, headers, null);
  }

  public static Response createCorrectVariant(
      Object responseObj, HttpHeaders headers, javax.ws.rs.core.Response.Status status) {
    Response.ResponseBuilder responseBuilder = null;
    Variant v = getVariant(headers);
    String contentType = getContentType(headers);

    if (status != null) {
      responseBuilder =
          Response.status(status)
              .entity(marshallerHelper.marshal(contentType, responseObj))
              .variant(v);
    } else {
      responseBuilder = Response.ok(marshallerHelper.marshal(contentType, responseObj), v);
    }
    return responseBuilder.build();
  }

  public static Response createCorrectVariant(
      MarshallerHelper marshallerHelper,
      String containerId,
      Object responseObj,
      HttpHeaders headers,
      javax.ws.rs.core.Response.Status status) {
    Response.ResponseBuilder responseBuilder = null;
    Variant v = getVariant(headers);
    String contentType = getContentType(headers);

    String marshalledResponse;
    if (marshallerHelper.getRegistry().getContainer(containerId) == null) {
      marshalledResponse = marshallerHelper.marshal(contentType, responseObj);
    } else {
      marshalledResponse = marshallerHelper.marshal(containerId, contentType, responseObj);
    }
    if (status != null) {
      responseBuilder = Response.status(status).entity(marshalledResponse).variant(v);
    } else {
      responseBuilder = Response.ok(marshalledResponse, v);
    }
    return responseBuilder.build();
  }

  public static Response createResponse(
      Object responseObj, Variant v, javax.ws.rs.core.Response.Status status) {
    Response.ResponseBuilder responseBuilder = null;
    if (status != null) {
      responseBuilder = Response.status(status).entity(responseObj).variant(v);
    } else {
      responseBuilder = Response.ok(responseObj, v);
    }
    return responseBuilder.build();
  }

  public static Variant getVariant(HttpHeaders headers) {
    Variant v = RestEasy960Util.getVariant(headers);
    if (v == null) {
      v = defaultVariant;
    }
    return v;
  }

  public static String getClassType(HttpHeaders headers) {
    String classType = null;

    List<String> header = headers.getRequestHeader(KieServerConstants.CLASS_TYPE_HEADER);
    if (header != null && !header.isEmpty()) {
      classType = header.get(0);
    }

    return classType;
  }

  public static String getContentType(HttpHeaders headers) {
    Variant v = getVariant(headers);
    String contentType = v.getMediaType().getSubtype();

    List<String> kieContentTypeHeader =
        headers.getRequestHeader(KieServerConstants.KIE_CONTENT_TYPE_HEADER);
    if (kieContentTypeHeader != null && !kieContentTypeHeader.isEmpty()) {
      contentType = kieContentTypeHeader.get(0);
    }

    return contentType;
  }

  public static Response notFound(String message, Variant v) {
    return createResponse(message, v, Response.Status.NOT_FOUND);
  }

  public static Response internalServerError(String message, Variant v) {
    return createResponse(message, v, Response.Status.INTERNAL_SERVER_ERROR);
  }

  public static Response alreadyExists(String message, Variant v) {
    return createResponse(message, v, Response.Status.CONFLICT);
  }
}