org.restlet.representation.WriterRepresentation Java Examples

The following examples show how to use org.restlet.representation.WriterRepresentation. 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: LinksResponseWriter.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
private Representation createTextHtmlRepresentation( final Object result, final Response response )
{
    return 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( "links.htm" ).process( context, writer );
                        }
                        catch( TemplateException e )
                        {
                            throw new IOException( e );
                        }
                    }
                };
}
 
Example #2
Source File: LinksResponseWriter.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
private Representation createAtomRepresentation( final Object result, final Response response )
{
    return new WriterRepresentation( MediaType.APPLICATION_ATOM )
    {
        @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( "links.atom" ).process( context, writer );
            }
            catch( TemplateException e )
            {
                throw new IOException( e );
            }
        }
    };
}
 
Example #3
Source File: EntityResource.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
private Representation representRdfXml( final EntityState entity )
    throws ResourceException
{
    Representation representation = new WriterRepresentation( MediaType.APPLICATION_RDF_XML )
    {
        @Override
        public void write( Writer writer )
            throws IOException
        {
            try
            {
                Iterable<Statement> statements = entitySerializer.serialize( entity );
                new RdfXmlSerializer().serialize( statements, writer );
            }
            catch( RDFHandlerException e )
            {
                throw new IOException( e );
            }
        }
    };
    representation.setCharacterSet( CharacterSet.UTF_8 );
    return representation;
}
 
Example #4
Source File: EntitiesResource.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private Representation representRdf()
    throws ResourceException
{
    try
    {
        final Stream<EntityReference> query = entityFinder.findEntities( EntityComposite.class, null, null, null, null, Collections.emptyMap() );

        WriterRepresentation representation = new WriterRepresentation( MediaType.APPLICATION_RDF_XML )
        {
            @Override
            public void write( Writer writer )
                throws IOException
            {
                PrintWriter out = new PrintWriter( writer );
                out.println( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<rdf:RDF\n"
                             + "\txmlns=\"urn:polygene:\"\n" + "\txmlns:polygene=\"http://polygene.apache.org/rdf/model/1.0/\"\n"
                             + "\txmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n"
                             + "\txmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\">" );
                query.forEach( qualifiedIdentity -> out.println( "<polygene:entity rdf:about=\""
                                                                 + getRequest().getResourceRef().getPath() + "/"
                                                                 + qualifiedIdentity.identity() + ".rdf\"/>" ) );

                out.println( "</rdf:RDF>" );
            }
        };
        representation.setCharacterSet( CharacterSet.UTF_8 );

        return representation;
    }
    catch( EntityFinderException e )
    {
        throw new ResourceException( Status.SERVER_ERROR_INTERNAL, e );
    }
}
 
Example #5
Source File: EntitiesResource.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private Representation representHtml()
    throws ResourceException
{
    try
    {
        Stream<EntityReference> query = entityFinder.findEntities( EntityComposite.class, null, null, null, null, Collections.emptyMap() );
        Representation representation = new WriterRepresentation( MediaType.TEXT_HTML )
        {
            @Override
            public void write( Writer buf )
                throws IOException
            {
                PrintWriter out = new PrintWriter( buf );
                out.println( "<html><head><title>All entities</title></head><body><h1>All entities</h1><ul>" );

                query.forEach( entity -> out.println( "<li><a href=\""
                                                      + getRequest().getResourceRef().clone().addSegment( entity.identity() + ".html" )
                                                      + "\">" + entity.identity() + "</a></li>" ) );
                out.println( "</ul></body></html>" );
            }
        };
        representation.setCharacterSet( CharacterSet.UTF_8 );
        return representation;
    }
    catch( EntityFinderException e )
    {
        throw new ResourceException( e );
    }
}
 
Example #6
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 #7
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 #8
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 #9
Source File: ValueCompositeRequestWriter.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
@Override
public boolean writeRequest(Object requestObject, Request request) throws ResourceException
{
   if (requestObject instanceof ValueComposite)
   {
      // Value as parameter
      final ValueComposite valueObject = (ValueComposite) requestObject;
      if (request.getMethod().equals(Method.GET))
      {
         StateHolder holder = spi.stateOf( valueObject );
         final ValueDescriptor descriptor = spi.valueDescriptorFor( valueObject );

          final Reference ref = request.getResourceRef();
          ref.setQuery( null );
          descriptor.state().properties().forEach( propertyDescriptor -> {
              try
              {
                  Object value = holder.propertyFor( propertyDescriptor.accessor() ).get();
                  String param;
                  if( value == null )
                  {
                      param = null;
                  }
                  else
                  {
                      param = serializer.serialize( value );
                  }
                  ref.addQueryParameter( propertyDescriptor.qualifiedName().name(), param );
              }
              catch( SerializationException e )
              {
                  throw new ResourceException( e );
              }
          } );
      }
      else
      {
         request.setEntity(new WriterRepresentation( MediaType.APPLICATION_JSON )
         {
             @Override
             public void write( Writer writer )
                 throws IOException
             {
                setCharacterSet( CharacterSet.UTF_8 );
                serializer.serialize( writer, valueObject );
             }
         });
      }

      return true;
   }

   return false;
}