Search in sources :

Example 51 with StringRepresentation

use of org.restlet.representation.StringRepresentation in project pinot by linkedin.

the class PinotTenantRestletResource method getAllTenants.

@HttpVerb("get")
@Summary("Gets information about all tenants")
@Tags({ "tenant" })
@Paths({ "/tenants", "/tenants/" })
private StringRepresentation getAllTenants(@Parameter(name = "type", in = "query", description = "The type of tenant, either SERVER or BROKER") String type) throws JSONException {
    // Return all the tags.
    StringRepresentation presentation;
    final JSONObject ret = new JSONObject();
    if (type == null || type.equalsIgnoreCase("server")) {
        ret.put("SERVER_TENANTS", _pinotHelixResourceManager.getAllServerTenantNames());
    }
    if (type == null || type.equalsIgnoreCase("broker")) {
        ret.put("BROKER_TENANTS", _pinotHelixResourceManager.getAllBrokerTenantNames());
    }
    presentation = new StringRepresentation(ret.toString(), MediaType.APPLICATION_JSON);
    return presentation;
}
Also used : JSONObject(org.json.JSONObject) StringRepresentation(org.restlet.representation.StringRepresentation) Summary(com.linkedin.pinot.common.restlet.swagger.Summary) HttpVerb(com.linkedin.pinot.common.restlet.swagger.HttpVerb) Paths(com.linkedin.pinot.common.restlet.swagger.Paths) Tags(com.linkedin.pinot.common.restlet.swagger.Tags)

Example 52 with StringRepresentation

use of org.restlet.representation.StringRepresentation in project pinot by linkedin.

the class SwaggerResource method get.

@Get
@Override
public Representation get() {
    try {
        // Info
        JSONObject info = new JSONObject();
        info.put("title", "Pinot Controller");
        info.put("version", "0.1");
        // Paths
        JSONObject paths = new JSONObject();
        Router router = PinotRestletApplication.getRouter();
        RouteList routeList = router.getRoutes();
        for (Route route : routeList) {
            if (route instanceof TemplateRoute) {
                TemplateRoute templateRoute = (TemplateRoute) route;
                JSONObject pathObject = new JSONObject();
                String routePath = templateRoute.getTemplate().getPattern();
                // Check which methods are present
                Restlet routeTarget = templateRoute.getNext();
                if (routeTarget instanceof Finder) {
                    Finder finder = (Finder) routeTarget;
                    generateSwaggerForFinder(pathObject, routePath, finder);
                } else if (routeTarget instanceof Filter) {
                    do {
                        Filter filter = (Filter) routeTarget;
                        routeTarget = filter.getNext();
                    } while (routeTarget instanceof Filter);
                    if (routeTarget instanceof Finder) {
                        Finder finder = (Finder) routeTarget;
                        generateSwaggerForFinder(pathObject, routePath, finder);
                    }
                }
                if (pathObject.keys().hasNext()) {
                    paths.put(routePath, pathObject);
                }
            }
        }
        // Tags
        JSONArray tags = new JSONArray();
        addTag(tags, "tenant", "Tenant-related operations");
        addTag(tags, "instance", "Instance-related operations");
        addTag(tags, "table", "Table-related operations");
        addTag(tags, "segment", "Segment-related operations");
        addTag(tags, "schema", "Schema-related operations");
        addTag(tags, "version", "Version-related operations");
        // Swagger
        JSONObject swagger = new JSONObject();
        swagger.put("swagger", "2.0");
        swagger.put("info", info);
        swagger.put("paths", paths);
        swagger.put("tags", tags);
        StringRepresentation representation = new StringRepresentation(swagger.toString());
        // Set up CORS
        Series<Header> responseHeaders = (Series<Header>) getResponse().getAttributes().get("org.restlet.http.headers");
        if (responseHeaders == null) {
            responseHeaders = new Series(Header.class);
            getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
        }
        responseHeaders.add(new Header("Access-Control-Allow-Origin", "*"));
        return representation;
    } catch (JSONException e) {
        return new StringRepresentation(e.toString());
    }
}
Also used : Restlet(org.restlet.Restlet) TemplateRoute(org.restlet.routing.TemplateRoute) Finder(org.restlet.resource.Finder) JSONArray(org.json.JSONArray) Router(org.restlet.routing.Router) JSONException(org.json.JSONException) RouteList(org.restlet.util.RouteList) Series(org.restlet.util.Series) JSONObject(org.json.JSONObject) Header(org.restlet.engine.header.Header) Filter(org.restlet.routing.Filter) StringRepresentation(org.restlet.representation.StringRepresentation) Route(org.restlet.routing.Route) TemplateRoute(org.restlet.routing.TemplateRoute) Get(org.restlet.resource.Get)

Example 53 with StringRepresentation

use of org.restlet.representation.StringRepresentation in project camel by apache.

the class DefaultRestletBinding method createRepresentationFromBody.

protected Representation createRepresentationFromBody(Exchange exchange, MediaType mediaType) {
    Object body = exchange.getIn().getBody();
    if (body == null) {
        return new EmptyRepresentation();
    }
    // unwrap file
    if (body instanceof WrappedFile) {
        body = ((WrappedFile) body).getFile();
    }
    if (body instanceof InputStream) {
        return new InputRepresentation((InputStream) body, mediaType);
    } else if (body instanceof File) {
        return new FileRepresentation((File) body, mediaType);
    } else if (body instanceof byte[]) {
        return new ByteArrayRepresentation((byte[]) body, mediaType);
    } else if (body instanceof String) {
        return new StringRepresentation((CharSequence) body, mediaType);
    }
    // fallback as string
    body = exchange.getIn().getBody(String.class);
    if (body != null) {
        return new StringRepresentation((CharSequence) body, mediaType);
    } else {
        return new EmptyRepresentation();
    }
}
Also used : InputRepresentation(org.restlet.representation.InputRepresentation) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) WrappedFile(org.apache.camel.WrappedFile) StringRepresentation(org.restlet.representation.StringRepresentation) InputStream(java.io.InputStream) FileRepresentation(org.restlet.representation.FileRepresentation) ByteArrayRepresentation(org.restlet.representation.ByteArrayRepresentation) WrappedFile(org.apache.camel.WrappedFile) GenericFile(org.apache.camel.component.file.GenericFile) File(java.io.File)

Example 54 with StringRepresentation

use of org.restlet.representation.StringRepresentation in project camel by apache.

the class RestletSetBodyTest method createRouteBuilder.

@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("restlet:http://localhost:" + portNum + "/stock/{symbol}?restletMethods=get").to("http://localhost:" + portNum2 + "/test?bridgeEndpoint=true").setBody().constant("110");
            from("jetty:http://localhost:" + portNum2 + "/test").setBody().constant("response is back");
            // create ByteArrayRepresentation for response
            from("restlet:http://localhost:" + portNum + "/images/{symbol}?restletMethods=get").setBody().constant(new InputRepresentation(new ByteArrayInputStream(getAllBytes()), MediaType.IMAGE_PNG, 256));
            from("restlet:http://localhost:" + portNum + "/music/{symbol}?restletMethods=get").setHeader(Exchange.CONTENT_TYPE).constant("audio/mpeg").setBody().constant(getAllBytes());
            from("restlet:http://localhost:" + portNum + "/video/{symbol}?restletMethods=get").setHeader(Exchange.CONTENT_TYPE).constant("video/mp4").setBody().constant(new ByteArrayInputStream(getAllBytes()));
            from("restlet:http://localhost:" + portNum + "/gzip/data?restletMethods=get").setBody().constant(new EncodeRepresentation(Encoding.GZIP, new StringRepresentation("Hello World!", MediaType.TEXT_XML)));
        }
    };
}
Also used : RouteBuilder(org.apache.camel.builder.RouteBuilder) InputRepresentation(org.restlet.representation.InputRepresentation) ByteArrayInputStream(java.io.ByteArrayInputStream) StringRepresentation(org.restlet.representation.StringRepresentation) EncodeRepresentation(org.restlet.engine.application.EncodeRepresentation)

Example 55 with StringRepresentation

use of org.restlet.representation.StringRepresentation in project qi4j-sdk by Qi4j.

the class DomainEventSourceResource method handle.

@Override
public void handle(Request request, Response response) {
    long eventCount = source.count();
    long pageSize = 10;
    long startEvent = -1;
    long endEvent = -1;
    long limit = pageSize;
    final List<UnitOfWorkDomainEventsValue> eventsValues = new ArrayList<UnitOfWorkDomainEventsValue>();
    final Feed feed = new Feed();
    feed.setBaseReference(request.getResourceRef().getParentRef());
    List<Link> links = feed.getLinks();
    String remainingPart = request.getResourceRef().getRemainingPart();
    if (remainingPart.equals("/")) {
        // Current set - always contains the last "pageSize" events
        startEvent = Math.max(0, eventCount - pageSize - 1);
        feed.setTitle(new Text("Current set"));
        if (startEvent > 0) {
            long previousStart = Math.max(0, startEvent - pageSize);
            long previousEnd = startEvent - 1;
            Link link = new Link(new Reference(previousStart + "," + previousEnd), new Relation("previous"), MediaType.APPLICATION_ATOM);
            link.setTitle("Previous page");
            links.add(link);
        }
    } else {
        // Archive
        String[] indices = remainingPart.substring(1).split(",");
        if (indices.length == 1) {
            // Working set
            startEvent = Long.parseLong(indices[0]);
            endEvent = startEvent + pageSize - 1;
            limit = pageSize;
            feed.setTitle(new Text("Working set"));
        } else if (indices.length == 2) {
            feed.setTitle(new Text("Archive page"));
            startEvent = Long.parseLong(indices[0]);
            endEvent = Long.parseLong(indices[1]);
            limit = 1 + endEvent - startEvent;
        } else
            throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
        if (startEvent > 0) {
            long previousStart = Math.max(0, startEvent - pageSize);
            long previousEnd = startEvent - 1;
            Link link = new Link(new Reference(previousStart + "," + previousEnd), new Relation("previous"), MediaType.APPLICATION_ATOM);
            link.setTitle("Previous page");
            links.add(link);
        }
        long nextStart = endEvent + 1;
        long nextEnd = nextStart + pageSize - 1;
        if (nextStart < eventCount)
            if (nextEnd >= eventCount) {
                Link next = new Link(new Reference(nextStart + ""), new Relation("next"), MediaType.APPLICATION_ATOM);
                next.setTitle("Working set");
                links.add(next);
            } else {
                Link next = new Link(new Reference(nextStart + "," + nextEnd), new Relation("next"), MediaType.APPLICATION_ATOM);
                next.setTitle("Next page");
                links.add(next);
            }
    }
    try {
        source.events(startEvent, limit).transferTo(Outputs.collection(eventsValues));
    } catch (Throwable throwable) {
        throw new ResourceException(Status.SERVER_ERROR_INTERNAL, throwable);
    }
    Link last = new Link(new Reference("0," + (pageSize - 1)), new Relation("last"), MediaType.APPLICATION_ATOM);
    last.setTitle("Last archive page");
    links.add(last);
    Link first = new Link(new Reference("."), new Relation("first"), MediaType.APPLICATION_ATOM);
    first.setTitle("Current set");
    links.add(first);
    /*
        if (previousPage != -1)
        {
            Link link = new Link( new Reference( ""+previousPage ), new Relation( "prev-archive" ), MediaType.APPLICATION_ATOM );
            link.setTitle( "Previous archive page" );
            links.add( link );
        }
        if (nextPage != -1)
        {
            Link link = new Link( new Reference( "" + nextPage ), new Relation( "next-archive" ), MediaType.APPLICATION_ATOM );
            link.setTitle( "Next archive page" );
            links.add( link );
        }
        else if (startEvent != workingSetOffset)
        {
            Link next = new Link( new Reference( "" ), new Relation( "next" ), MediaType.APPLICATION_ATOM );
            next.setTitle( "Next page" );
            links.add( next );
        }
*/
    Date lastModified = null;
    for (UnitOfWorkDomainEventsValue eventsValue : eventsValues) {
        Entry entry = new Entry();
        entry.setTitle(new Text(eventsValue.usecase().get() + "(" + eventsValue.user().get() + ")"));
        entry.setPublished(new Date(eventsValue.timestamp().get()));
        entry.setModificationDate(lastModified = new Date(eventsValue.timestamp().get()));
        entry.setId(Long.toString(startEvent + 1));
        startEvent++;
        Content content = new Content();
        content.setInlineContent(new StringRepresentation(eventsValue.toString(), MediaType.APPLICATION_JSON));
        entry.setContent(content);
        feed.getEntries().add(entry);
    }
    feed.setModificationDate(lastModified);
    MediaType mediaType = request.getClientInfo().getPreferredMediaType(Iterables.toList(iterable(MediaType.TEXT_HTML, MediaType.APPLICATION_ATOM)));
    if (MediaType.APPLICATION_ATOM.equals(mediaType)) {
        WriterRepresentation representation = new WriterRepresentation(MediaType.APPLICATION_ATOM) {

            @Override
            public void write(final Writer writer) throws IOException {
                feed.write(writer);
            }
        };
        representation.setCharacterSet(CharacterSet.UTF_8);
        response.setEntity(representation);
    } else {
        WriterRepresentation representation = new WriterRepresentation(MediaType.TEXT_HTML) {

            @Override
            public void write(Writer writer) throws IOException {
                writer.append("<html><head><title>Events</title></head><body>");
                for (Link link : feed.getLinks()) {
                    writer.append("<a href=\"").append(link.getHref().getPath()).append("\">");
                    writer.append(link.getTitle());
                    writer.append("</a><br/>");
                }
                writer.append("<ol>");
                for (Entry entry : feed.getEntries()) {
                    writer.append("<li>").append(entry.getTitle().toString()).append("</li>");
                }
                writer.append("</ol></body>");
            }
        };
        representation.setCharacterSet(CharacterSet.UTF_8);
        response.setEntity(representation);
    }
/*
        } else
        {
            throw new ResourceException( Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE );
        }
*/
}
Also used : Reference(org.restlet.data.Reference) ArrayList(java.util.ArrayList) Date(java.util.Date) UnitOfWorkDomainEventsValue(org.qi4j.library.eventsourcing.domain.api.UnitOfWorkDomainEventsValue) StringRepresentation(org.restlet.representation.StringRepresentation) WriterRepresentation(org.restlet.representation.WriterRepresentation) MediaType(org.restlet.data.MediaType) ResourceException(org.restlet.resource.ResourceException) Writer(java.io.Writer)

Aggregations

StringRepresentation (org.restlet.representation.StringRepresentation)63 HttpVerb (com.linkedin.pinot.common.restlet.swagger.HttpVerb)30 Paths (com.linkedin.pinot.common.restlet.swagger.Paths)30 Summary (com.linkedin.pinot.common.restlet.swagger.Summary)30 Tags (com.linkedin.pinot.common.restlet.swagger.Tags)29 JSONException (org.json.JSONException)17 JSONObject (org.json.JSONObject)16 Responses (com.linkedin.pinot.common.restlet.swagger.Responses)14 IOException (java.io.IOException)12 JSONArray (org.json.JSONArray)12 Representation (org.restlet.representation.Representation)12 File (java.io.File)8 MediaType (org.restlet.data.MediaType)8 AbstractTableConfig (com.linkedin.pinot.common.config.AbstractTableConfig)7 PinotResourceManagerResponse (com.linkedin.pinot.controller.helix.core.PinotResourceManagerResponse)6 WriterRepresentation (org.restlet.representation.WriterRepresentation)6 ResourceException (org.restlet.resource.ResourceException)6 Schema (com.linkedin.pinot.common.data.Schema)5 Writer (java.io.Writer)5 Get (org.restlet.resource.Get)5