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

The following are Jave code examples for showing how to use setEntity() of the org.restlet.Response class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: polygene-java   File: DefaultResponseWriter.java   Source Code and License Vote up 6 votes
@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
Project: prudence   File: GeneratedTextDeferredRepresentation.java   Source Code and License Vote up 6 votes
public void run()
{
	if( delay > 0 )
	{
		try
		{
			Thread.sleep( delay );
		}
		catch( InterruptedException e )
		{
			// Restore interrupt status
			Thread.currentThread().interrupt();
			return;
		}
	}

	Response response = resource.getResponse();
	response.setEntity( this );
	response.setStatus( Status.SUCCESS_OK );
	response.commit();
}
 
Example 3
Project: open-rmbt   File: TileRestlet.java   Source Code and License Vote up 5 votes
@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 4
Project: polygene-java   File: ValueDescriptorResponseWriter.java   Source Code and License Vote up 4 votes
@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 5
Project: polygene-java   File: ResourceResponseWriter.java   Source Code and License Vote up 4 votes
@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 6
Project: prudence   File: DelegatedStatusService.java   Source Code and License Vote up 4 votes
@Override
public Representation toRepresentation( Status status, Request request, Response response )
{
	if( isEnabled() )
	{
		ConcurrentMap<String, Object> attributes = response.getAttributes();

		Object passthrough = attributes.get( PASSTHROUGH_ATTRIBUTE );
		if( ( passthrough != null ) && (Boolean) passthrough )
			// Pass through
			return response.getEntity();

		Restlet handler = handlers.get( status.getCode() );
		if( handler != null )
		{
			// Reset the response
			response.setStatus( Status.SUCCESS_OK );
			response.setEntity( null );

			// Clean up saved information
			CachingUtil.clearExistingValidDocumentName( request );

			// Delegate
			handler.handle( request, response );

			// Return the status
			response.setStatus( status );

			Representation representation = response.getEntity();
			if( representation != null )
			{
				// Avoid client caching, which would require other
				// interchanges with the client that we can't handle from
				// here
				representation.setExpirationDate( null );
				representation.setModificationDate( null );
				representation.setTag( null );
			}

			attributes.put( PASSTHROUGH_ATTRIBUTE, true );
			return representation;
		}

		if( isFallback )
			// Fallbacks don't override the entity if there are no handlers
			return response.getEntity();

		if( isDebugging() && ( status.getThrowable() != null ) )
		{
			// Use the debug representation for exceptions
			attributes.put( PASSTHROUGH_ATTRIBUTE, true );
			if( debugHeader != null )
				RestletUtil.getResponseHeaders( response ).set( debugHeader, "error" );
			return createDebugRepresentation( status, request, response );
		}
	}

	return super.toRepresentation( status, request, response );
}
 
Example 7
Project: prudence   File: ResolvingRedirector.java   Source Code and License Vote up 4 votes
@Override
protected void serverRedirect( Restlet next, Reference targetRef, Request request, Response response )
{
	validateNotRecursiveServerRedirect( targetRef, request, response );

	// This is essentially the original Restlet code modified to use
	// ResolvingTemplate.

	if( next == null )
		getLogger().warning( "No next Restlet provided for server redirection to " + targetRef );
	else
	{
		// Save the base URI if it exists as we might need it for
		// redirections
		Reference resourceRef = request.getResourceRef();
		Reference baseRef = resourceRef.getBaseRef();

		// Reset the protocol and let the dispatcher handle the protocol
		request.setProtocol( null );

		// Update the request to cleanly go to the target URI
		request.setResourceRef( targetRef );
		rewrite( request );
		next.handle( request, response );

		// Allow for response rewriting and clean the headers
		response.setEntity( rewrite( response.getEntity() ) );
		rewrite( response );
		request.setResourceRef( resourceRef );

		// In case of redirection, we may have to rewrite the redirect URI
		if( response.getLocationRef() != null )
		{
			Template rt = new ResolvingTemplate( this.targetTemplate );
			rt.setLogger( getLogger() );
			int matched = rt.parse( response.getLocationRef().toString(), request );

			if( matched > 0 )
			{
				String remainingPart = (String) request.getAttributes().get( "rr" );

				if( remainingPart != null )
					response.setLocationRef( baseRef.toString() + remainingPart );
			}
		}
	}
}
 
Example 8
Project: Pinot   File: ControllerRestApplication.java   Source Code and License Vote up 4 votes
@Override
public Restlet createInboundRoot() {
  // Remove server-side HTTP timeout (see http://stackoverflow.com/questions/12943447/restlet-server-socket-timeout)
  getContext().getParameters().add("maxIoIdleTimeMs", ONE_HOUR_IN_MILLIS);
  getContext().getParameters().add("ioMaxIdleTimeMs", ONE_HOUR_IN_MILLIS);

  router = new Router(getContext());
  router.setDefaultMatchingMode(Template.MODE_EQUALS);

  /**
   * Start Routers 2.0
   */

  attachRoutesForClass(router, PinotTenantRestletResource.class);
  attachRoutesForClass(router, PinotSchemaRestletResource.class);
  attachRoutesForClass(router, PinotTableRestletResource.class);

  // GET
  attachRoutesForClass(router, PinotTableInstances.class);
  attachRoutesForClass(router, PinotTableSchema.class);
  attachRoutesForClass(router, PinotSegmentRestletResource.class);

  // PUT
  attachRoutesForClass(router, PinotTableSegmentConfigs.class);
  attachRoutesForClass(router, PinotTableIndexingConfigs.class);
  attachRoutesForClass(router, PinotTableTenantConfigs.class);
  attachRoutesForClass(router, PinotTableMetadataConfigs.class);

  // Uploading Downloading segments
  attachRoutesForClass(router, PinotSegmentUploadRestletResource.class);

  attachRoutesForClass(router, PinotVersionRestletResource.class);

  router.attach("/api", SwaggerResource.class);

  /**
   *  End Routes 2.0
   */

  attachRoutesForClass(router, PinotInstanceRestletResource.class);

  router.attach("/pinot-controller/admin", PinotControllerHealthCheck.class);

  router.attach("/pql", PqlQueryResource.class);

  final Restlet mainpage = new Restlet() {
    @Override
    public void handle(Request request, Response response) {
      final 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));
    }
  };

  final Directory webdir = new Directory(getContext(), CONSOLE_WEBAPP_ROOT_PATH);
  webdir.setDeeplyAccessible(true);
  webdir.setIndexName("index.html");
  router.attach("/query", webdir);

  final Directory swaggerUiDir = new Directory(getContext(), getClass().getClassLoader().getResource("META-INF/resources/webjars/swagger-ui/2.1.8-M1").toString());
  swaggerUiDir.setDeeplyAccessible(true);
  router.attach("/swagger-ui", swaggerUiDir);

  final Redirector redirector = new Redirector(getContext(), "/swagger-ui/index.html?url=/api", Redirector.MODE_CLIENT_TEMPORARY);
  router.attach("/help", redirector);

  return router;
}