Java Code Examples for org.restlet.Response#setEntity()

The following examples show how to use org.restlet.Response#setEntity() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DefaultResponseWriter.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
@Override
public boolean writeResponse( final Object result, final Response response )
    throws ResourceException
{
    MediaType type = getVariant( response.getRequest(), ENGLISH, supportedMediaTypes ).getMediaType();
    if( MediaType.APPLICATION_JSON.equals( type ) )
    {
        if( result instanceof String || result instanceof Number || result instanceof Boolean )
        {
            StringRepresentation representation = new StringRepresentation( result.toString(),
                                                                            MediaType.APPLICATION_JSON );

            response.setEntity( representation );

            return true;
        }
    }

    return false;
}
 
Example 2
Source File: ExceptionProcessor.java    From container with Apache License 2.0 6 votes vote down vote up
@Override
public void process(final Exchange exchange) throws Exception {

    ExceptionProcessor.LOG.debug("Exception handling...");

    final Response response = exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class);

    if (exchange.getIn().getBody() instanceof ParseException) {
        response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        final String body = exchange.getIn().getBody(String.class);
        response.setEntity("JSON is not valid: " + body, MediaType.TEXT_ALL);
        ExceptionProcessor.LOG.warn("JSON is not valid: {}", body);
    } else if (exchange.getIn().getBody() instanceof NullPointerException) {
        response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        response.setEntity("Needed information not specified.", MediaType.TEXT_ALL);
        ExceptionProcessor.LOG.warn("Needed information not specified.");
    } else if (exchange.getIn().getBody() instanceof Exception) {
        response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        response.setEntity("Invocation failed! " + exchange.getIn().getBody().toString(), MediaType.TEXT_ALL);
        ExceptionProcessor.LOG.warn("Invocation failed! " + exchange.getIn().getBody().toString());
    }

    exchange.getOut().setBody(response);
}
 
Example 3
Source File: ExceptionProcessor.java    From container with Apache License 2.0 6 votes vote down vote up
@Override
public void process(final Exchange exchange) throws Exception {

    ExceptionProcessor.LOG.debug("Exception handling...");

    final Response response = exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class);

    if (exchange.getIn().getBody() instanceof ParseException) {
        response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        response.setEntity("JSON is not valid: " + exchange.getIn().getBody(String.class), MediaType.TEXT_ALL);
    } else if (exchange.getIn().getBody() instanceof NullPointerException) {
        response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        response.setEntity("Needed information not specified.", MediaType.TEXT_ALL);
    } else if (exchange.getIn().getBody() instanceof ApplicationBusExternalException) {
        response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        response.setEntity(exchange.getIn().getBody(String.class), MediaType.TEXT_ALL);
    } else if (exchange.getIn().getBody() instanceof ApplicationBusInternalException) {
        response.setStatus(Status.SERVER_ERROR_INTERNAL);
        response.setEntity(exchange.getIn().getBody(String.class), MediaType.TEXT_ALL);
    }

    exchange.getOut().setBody(response);
}
 
Example 4
Source File: IsFinishedResponseProcessor.java    From container with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void process(final Exchange exchange) throws Exception {

    IsFinishedResponseProcessor.LOG.debug("Processing IsFinished response....");

    final String requestID = exchange.getIn().getHeader(InvocationRoute.ID, String.class);

    IsFinishedResponseProcessor.LOG.debug("RequestID: {}", requestID);

    final Response response = exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class);

    if (exchange.getIn().getBody() instanceof Exception) {

        response.setStatus(Status.CLIENT_ERROR_NOT_FOUND);
        response.setEntity(exchange.getIn().getBody(String.class), MediaType.TEXT_ALL);
    } else {

        final Boolean isFinished = exchange.getIn().getBody(Boolean.class);

        if (isFinished) {
            IsFinishedResponseProcessor.LOG.debug("Invocation has finished, send location of result.");

            response.setStatus(Status.REDIRECTION_SEE_OTHER);
            response.setLocationRef(InvocationRoute.GET_RESULT_ENDPOINT.replace(InvocationRoute.ID_PLACEHODLER,
                requestID));
        } else {
            IsFinishedResponseProcessor.LOG.debug("Invocation has not finished yet.");

            final JSONObject obj = new JSONObject();
            obj.put("status", "PENDING");

            response.setStatus(Status.SUCCESS_OK);
            response.setEntity(obj.toJSONString(), MediaType.APPLICATION_JSON);
        }
        exchange.getOut().setBody(response);
    }
}
 
Example 5
Source File: IsFinishedResponseProcessor.java    From container with Apache License 2.0 5 votes vote down vote up
@Override
public void process(final Exchange exchange) throws Exception {

    IsFinishedResponseProcessor.LOG.debug("Processing IsFinished response....");

    final String requestID = exchange.getIn().getHeader(Route.ID, String.class);

    IsFinishedResponseProcessor.LOG.debug("RequestID: {}", requestID);

    final Response response = exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class);

    if (exchange.getIn().getBody() instanceof Exception) {

        response.setStatus(Status.CLIENT_ERROR_NOT_FOUND);
        response.setEntity(exchange.getIn().getBody(String.class), MediaType.TEXT_ALL);
    } else {

        final Boolean isFinished = exchange.getIn().getBody(Boolean.class);

        if (isFinished) {
            IsFinishedResponseProcessor.LOG.debug("Invocation has finished, send location of result.");

            response.setStatus(Status.REDIRECTION_SEE_OTHER);
            response.setLocationRef(Route.GET_RESULT_ENDPOINT.replace(Route.ID_PLACEHODLER, requestID));
        } else {
            IsFinishedResponseProcessor.LOG.debug("Invocation has not finished yet.");

            final JSONObject obj = new JSONObject();
            obj.put("status", "PENDING");

            response.setStatus(Status.SUCCESS_OK);
            response.setEntity(obj.toJSONString(), MediaType.APPLICATION_JSON);
        }
        exchange.getOut().setBody(response);
    }
}
 
Example 6
Source File: TileRestlet.java    From open-rmbt with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(final Request req, final Response res)
{
    final String zoomStr = (String) req.getAttributes().get("zoom");
    final String xStr = (String) req.getAttributes().get("x");
    final String yStr = (String) req.getAttributes().get("y");
    
    final Path path = new Path(zoomStr, xStr, yStr, req.getResourceRef().getQueryAsForm().getFirstValue("path", true));
    final Params p = getTileParameters(path, req.getResourceRef().getQueryAsForm());
    res.setEntity(new PngOutputRepresentation(getTile(p)));
}
 
Example 7
Source File: TaskResource.java    From spring-5-examples with MIT License 4 votes vote down vote up
@Override
public void handle(Request request, Response response) {
  super.handle(request, response);

  try {
    final Identifier identifier = new Identifier(Long.parseLong(request.getAttributes().get("task").toString()));

    if (request.getMethod().isSafe()) {
      final InboxModel.InboxTask value = model.getTasks().get(identifier);

      if (value == null) {
        response.setStatus(Status.CLIENT_ERROR_NOT_FOUND);
        return;
      }

      response.setEntity(new WriterRepresentation(MediaType.TEXT_HTML) {
        @Override
        public void write(Writer writer) throws IOException {
          VelocityContext context = new VelocityContext();
          context.put("task", value);
          velocity.getTemplate("inbox/task/task.html").merge(context, writer);
        }
      });
    } else {
      Inbox inbox = (Inbox) request.getAttributes().get("inbox");

      repository.<Task>update().apply("task").apply(identifier).apply(
          task ->
          {
            inbox.select(task);

            Form form = new Form(request.getEntity());

            String command = request.getAttributes().get("command").toString();
            switch (command) {
              case "changedescription": {
                Inbox.ChangeDescription changeDescription = new Inbox.ChangeDescription();
                changeDescription.description = form.getFirstValue("description");

                Inbox.changeDescription().
                    apply(inbox).
                    apply(changeDescription);
                break;
              }

              case "done": {
                Inbox.TaskDone taskDone = new Inbox.TaskDone();
                taskDone.done = form.getFirstValue("done") != null;

                Inbox.done().
                    apply(inbox).
                    apply(taskDone);
                break;
              }

              default: {
                response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST,
                    "Unknown command:" + command);
              }
            }
          }
      );


      response.redirectSeeOther(request.getReferrerRef());
    }
  } catch (Exception e) {
    response.setStatus(Status.SERVER_ERROR_INTERNAL, e);
  }
}
 
Example 8
Source File: ValueDescriptorResponseWriter.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
@Override
public boolean writeResponse( final Object result, final Response response )
    throws ResourceException
{
    if( result instanceof ValueDescriptor )
    {
        MediaType type = getVariant( response.getRequest(), ENGLISH, supportedMediaTypes ).getMediaType();
        if( APPLICATION_JSON.equals( type ) )
        {
            ValueDescriptor vd = (ValueDescriptor) result;
            JsonObjectBuilder builder = json.builderFactory().createObjectBuilder();
            vd.state().properties().forEach(
                property ->
                {
                    try
                    {
                        Object o = property.resolveInitialValue( module );
                        if( o == null )
                        {
                            builder.add( property.qualifiedName().name(), JsonValue.NULL );
                        }
                        else
                        {
                            builder.add( property.qualifiedName().name(), jsonSerializer.toJson( o ) );
                        }
                    }
                    catch( JsonException ex )
                    {
                        throw new RestResponseException( "Unable to serialize " + vd, ex );
                    }
                } );
            StringRepresentation representation = new StringRepresentation( builder.build().toString(),
                                                                            APPLICATION_JSON );
            response.setEntity( representation );
            return true;
        }
        else if( TEXT_HTML.equals( type ) )
        {
            Representation rep = new WriterRepresentation( TEXT_HTML )
            {
                @Override
                public void write( Writer writer )
                    throws IOException
                {
                    Map<String, Object> context = new HashMap<>();
                    context.put( "request", response.getRequest() );
                    context.put( "response", response );
                    context.put( "result", result );
                    try
                    {
                        cfg.getTemplate( "form.htm" ).process( context, writer );
                    }
                    catch( TemplateException e )
                    {
                        throw new IOException( e );
                    }
                }
            };
            response.setEntity( rep );
            return true;
        }
    }
    return false;
}
 
Example 9
Source File: ResourceResponseWriter.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
@Override
public boolean writeResponse( final Object result, final Response response )
    throws ResourceException
{
    if( result instanceof Resource )
    {
        Resource resourceValue = (Resource) result;

        // Allowed methods
        response.getAllowedMethods().add( Method.GET );
        if( resourceValue.commands().get().stream().anyMatch( LinksUtil.withRel( "delete" ) ) )
        {
            response.getAllowedMethods().add( Method.DELETE );
        }
        if( resourceValue.commands().get().stream().anyMatch( LinksUtil.withRel( "update" ) ) )
        {
            response.getAllowedMethods().add( Method.PUT );
        }

        // Response according to what client accepts
        MediaType type = getVariant( response.getRequest(), ENGLISH, supportedMediaTypes ).getMediaType();
        if( MediaType.APPLICATION_JSON.equals( type ) )
        {
            String json = jsonSerializer.serialize( resourceValue );
            response.setEntity( new StringRepresentation( json, MediaType.APPLICATION_JSON ) );
            return true;
        }
        else if( MediaType.TEXT_HTML.equals( type ) )
        {
            Representation rep = new WriterRepresentation( MediaType.TEXT_HTML )
            {
                @Override
                public void write( Writer writer )
                    throws IOException
                {
                    Map<String, Object> context = new HashMap<>();
                    context.put( "request", response.getRequest() );
                    context.put( "response", response );
                    context.put( "result", result );
                    try
                    {
                        cfg.getTemplate( "resource.htm" ).process( context, writer );
                    }
                    catch( TemplateException e )
                    {
                        throw new IOException( e );
                    }
                }
            };
            response.setEntity( rep );
            return true;
        }
    }

    return false;
}
 
Example 10
Source File: IsFinishedResponseProcessor.java    From container with Apache License 2.0 4 votes vote down vote up
@Override
public void process(final Exchange exchange) throws Exception {

    IsFinishedResponseProcessor.LOG.debug("Processing IsFinished response....");

    final String requestID = exchange.getIn().getHeader(Route.ID, String.class);

    IsFinishedResponseProcessor.LOG.debug("RequestID: {}", requestID);

    final Response response = exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class);

    if (exchange.getIn().getBody() instanceof Exception) {

        response.setStatus(Status.CLIENT_ERROR_NOT_FOUND);
        response.setEntity(exchange.getIn().getBody(String.class), MediaType.TEXT_ALL);
    } else {

        final Boolean isFinished = exchange.getIn().getBody(Boolean.class);

        if (isFinished) {
            IsFinishedResponseProcessor.LOG.debug("Invocation has finished, send location of result.");

            final String pollingURI = exchange.getIn().getHeader(Exchange.HTTP_URI, String.class);
            final String getResultURI =
                pollingURI + Route.GET_RESULT_ENDPOINT_SUFFIX.replace(Route.ID_PLACEHODLER, requestID);

            IsFinishedResponseProcessor.LOG.debug("GetResult URI: {}", getResultURI);

            response.setStatus(Status.REDIRECTION_SEE_OTHER);
            response.setLocationRef(getResultURI);
        } else {
            IsFinishedResponseProcessor.LOG.debug("Invocation has not finished yet.");

            final String acceptContentType = exchange.getIn().getHeader(Exchange.ACCEPT_CONTENT_TYPE, String.class);

            IsFinishedResponseProcessor.LOG.debug("AcceptContentType: {}", acceptContentType);

            if (acceptContentType.equals(MediaType.APPLICATION_JSON)) {

                final JSONObject obj = new JSONObject();
                obj.put("status", "PENDING");

                response.setStatus(Status.SUCCESS_OK);
                response.setEntity(obj.toJSONString(), MediaType.APPLICATION_JSON);
            } else if (acceptContentType.equals(MediaType.APPLICATION_XML)) {

                response.setStatus(Status.SUCCESS_OK);
                response.setEntity("<status>PENDING</status>", MediaType.APPLICATION_XML);
            } else {
                IsFinishedResponseProcessor.LOG.warn("The requested entity media type is not supported.");
                throw new ApplicationBusExternalException("The requested entity media type is not supported.",
                    Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE.getCode());
            }
        }
        exchange.getOut().setBody(response);
    }
}
 
Example 11
Source File: GetResultResponseProcessor.java    From container with Apache License 2.0 4 votes vote down vote up
@Override
public void process(final Exchange exchange) throws Exception {

    GetResultResponseProcessor.LOG.debug("Processing GetResult response....");

    final String requestID = exchange.getIn().getHeader(Route.ID, String.class);

    GetResultResponseProcessor.LOG.debug("RequestID: {}", requestID);

    final Response response = exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class);

    if (exchange.getIn().getBody() instanceof Exception) {

        response.setStatus(Status.CLIENT_ERROR_NOT_FOUND);
        response.setEntity(exchange.getIn().getBody(String.class), MediaType.TEXT_ALL);
    } else {

        final Form httpHeaders = (Form) exchange.getIn().getHeader("org.restlet.http.headers");
        final String acceptContentType = httpHeaders.getValues("Accept").toString();

        GetResultResponseProcessor.LOG.debug("AcceptContentType: {}", acceptContentType);

        final String result = exchange.getIn().getBody(String.class);

        if (acceptContentType.equals(MediaType.APPLICATION_JSON.getName())) {

            final JSONObject obj = new JSONObject();
            obj.put("result", result);

            response.setStatus(Status.SUCCESS_OK);
            response.setEntity(obj.toJSONString(), MediaType.APPLICATION_JSON);
        } else if (acceptContentType.equals(MediaType.APPLICATION_XML.getName())) {

            response.setStatus(Status.SUCCESS_OK);
            response.setEntity("<result>" + result + "</result>", MediaType.APPLICATION_XML);
        } else {
            GetResultResponseProcessor.LOG.warn("The requested entity media type (Accept header) is not supported. Supported types are {} and {}",
                MediaType.APPLICATION_JSON.getName(),
                MediaType.APPLICATION_XML.getName());
            throw new ApplicationBusExternalException(
                "The requested request entity media type (Accept header) is not supported. Supported types are "
                    + MediaType.APPLICATION_JSON.getName() + " and " + MediaType.APPLICATION_XML.getName(),
                Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE.getCode());
        }
    }

    exchange.getOut().setBody(response);
}
 
Example 12
Source File: RestAdminApplication.java    From helix with Apache License 2.0 4 votes vote down vote up
@Override
public Restlet createInboundRoot() {
  Router router = new Router(getContext());
  router.setDefaultMatchingMode(Template.MODE_EQUALS);
  router.attach("/clusters", ClustersResource.class);
  router.attach("/clusters/{clusterName}", ClusterResource.class);
  router.attach("/clusters/{clusterName}/resourceGroups", ResourceGroupsResource.class);
  router.attach("/clusters/{clusterName}/resourceGroups/{resourceName}",
      ResourceGroupResource.class);
  router.attach("/clusters/{clusterName}/workflows", WorkflowsResource.class);
  router.attach("/clusters/{clusterName}/jobQueues", JobQueuesResource.class);
  router.attach("/clusters/{clusterName}/jobQueues/{jobQueue}", JobQueueResource.class);
  router.attach("/clusters/{clusterName}/jobQueues/{jobQueue}/{job}", JobResource.class);
  router.attach("/clusters/{clusterName}/instances", InstancesResource.class);
  router.attach("/clusters/{clusterName}/instances/{instanceName}", InstanceResource.class);
  router.attach("/clusters/{clusterName}/instances/{instanceName}/currentState/{resourceName}",
      CurrentStateResource.class);
  router.attach("/clusters/{clusterName}/instances/{instanceName}/statusUpdate/{resourceName}",
      StatusUpdateResource.class);
  router.attach("/clusters/{clusterName}/instances/{instanceName}/errors/{resourceName}",
      ErrorResource.class);
  router.attach("/clusters/{clusterName}/instances/{instanceName}/currentState",
      CurrentStatesResource.class);
  router.attach("/clusters/{clusterName}/instances/{instanceName}/statusUpdate",
      StatusUpdatesResource.class);
  router.attach("/clusters/{clusterName}/instances/{instanceName}/errors", ErrorsResource.class);
  router.attach("/clusters/{clusterName}/resourceGroups/{resourceName}/idealState",
      IdealStateResource.class);
  router.attach("/clusters/{clusterName}/resourceGroups/{resourceName}/externalView",
      ExternalViewResource.class);
  router.attach("/clusters/{clusterName}/StateModelDefs/{modelName}", StateModelResource.class);
  router.attach("/clusters/{clusterName}/StateModelDefs", StateModelsResource.class);
  router.attach("/clusters/{clusterName}/SchedulerTasks", SchedulerTasksResource.class);
  router.attach("/clusters/{clusterName}/Controller", ControllerResource.class);
  router.attach("/clusters/{clusterName}/Controller/statusUpdates/{MessageType}/{MessageId}",
      ControllerStatusUpdateResource.class);
  router.attach("/clusters/{clusterName}/configs", ConfigResource.class);
  router.attach("/clusters/{clusterName}/configs/{scope}", ConfigResource.class);
  router.attach("/clusters/{clusterName}/configs/{scope}/{scopeKey1}", ConfigResource.class);
  router.attach("/clusters/{clusterName}/configs/{scope}/{scopeKey1}/{scopeKey2}",
      ConfigResource.class);
  router.attach("/clusters/{clusterName}/constraints/{constraintType}", ConstraintResource.class);
  router.attach("/clusters/{clusterName}/constraints/{constraintType}/{constraintId}",
      ConstraintResource.class);
  router.attach("/zkPath", ZkPathResource.class).setMatchingMode(Template.MODE_STARTS_WITH);
  router.attach("/zkChild", ZkChildResource.class).setMatchingMode(Template.MODE_STARTS_WITH);

  Restlet mainpage = new Restlet() {
    @Override
    public void handle(Request request, Response response) {
      StringBuilder stringBuilder = new StringBuilder();
      stringBuilder.append("<html>");
      stringBuilder.append("<head><title>Restlet Cluster Management page</title></head>");
      stringBuilder.append("<body bgcolor=white>");
      stringBuilder.append("<table border=\"0\">");
      stringBuilder.append("<tr>");
      stringBuilder.append("<td>");
      stringBuilder.append("<h1>Rest cluster management interface V1</h1>");
      stringBuilder.append("</td>");
      stringBuilder.append("</tr>");
      stringBuilder.append("</table>");
      stringBuilder.append("</body>");
      stringBuilder.append("</html>");
      response.setEntity(new StringRepresentation(stringBuilder.toString(), MediaType.TEXT_HTML));
    }
  };
  router.attach("", mainpage);
  return router;
}
 
Example 13
Source File: GetResultResponseProcessor.java    From container with Apache License 2.0 3 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void process(final Exchange exchange) throws Exception {

    GetResultResponseProcessor.LOG.debug("Processing GetResult response....");

    final String requestID = exchange.getIn().getHeader(InvocationRoute.ID, String.class);

    GetResultResponseProcessor.LOG.debug("RequestID: {}", requestID);

    final Response response = exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class);

    if (exchange.getIn().getBody() instanceof Exception) {

        response.setStatus(Status.CLIENT_ERROR_NOT_FOUND);
        response.setEntity(exchange.getIn().getBody(String.class), MediaType.TEXT_ALL);
    } else {

        final HashMap<String, String> responseMap = exchange.getIn().getBody(HashMap.class);

        final JSONObject obj = new JSONObject();
        obj.put("response", responseMap);

        response.setStatus(Status.SUCCESS_OK);
        response.setEntity(obj.toJSONString(), MediaType.APPLICATION_JSON);
    }

    exchange.getOut().setBody(response);
}
 
Example 14
Source File: GetResultResponseProcessor.java    From container with Apache License 2.0 3 votes vote down vote up
@Override
public void process(final Exchange exchange) throws Exception {

    GetResultResponseProcessor.LOG.debug("Processing GetResult response....");

    final String requestID = exchange.getIn().getHeader(Route.ID, String.class);

    GetResultResponseProcessor.LOG.debug("RequestID: {}", requestID);

    final Response response = exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class);

    if (exchange.getIn().getBody() instanceof Exception) {

        response.setStatus(Status.CLIENT_ERROR_NOT_FOUND);
        response.setEntity(exchange.getIn().getBody(String.class), MediaType.TEXT_ALL);
    } else {

        final String result = exchange.getIn().getBody(String.class);

        final JSONObject obj = new JSONObject();
        obj.put("result", result);

        response.setStatus(Status.SUCCESS_OK);
        response.setEntity(obj.toJSONString(), MediaType.APPLICATION_JSON);
    }

    exchange.getOut().setBody(response);
}