blob: 155214e66053693f25d4e3408ce7b2653213bc0b [file] [log] [blame]
Thomas Vachuskae95da772015-02-23 15:50:11 -08001/*
2 * Copyright 2015 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.ui.impl;
17
18import org.onosproject.ui.UiExtension;
19import org.onosproject.ui.UiExtensionService;
20import org.onosproject.ui.UiView;
21
22import javax.ws.rs.GET;
23import javax.ws.rs.Path;
24import javax.ws.rs.Produces;
25import javax.ws.rs.core.Response;
26import java.io.ByteArrayInputStream;
27import java.io.IOException;
28import java.io.InputStream;
29import java.io.SequenceInputStream;
30
31import static com.google.common.collect.ImmutableList.of;
32import static com.google.common.io.ByteStreams.toByteArray;
33import static org.onosproject.ui.impl.MainViewResource.SCRIPT;
34
35/**
36 * Resource for serving the dynamically composed onos.js.
37 */
Thomas Vachuska529db0a2015-02-23 16:42:14 -080038@Path("/")
Thomas Vachuskae95da772015-02-23 15:50:11 -080039public class MainModuleResource extends AbstractInjectionResource {
40
41 private static final String MAIN_JS = "onos.js";
42
43 private static final String INJECT_VIEW_IDS_START = "// {INJECTED-VIEW-IDS-START}";
44 private static final String INJECT_VIEW_IDS_END = "// {INJECTED-VIEW-IDS-END}";
45
46 @GET
47 @Produces(SCRIPT)
48 public Response getMainModule() throws IOException {
49 UiExtensionService service = get(UiExtensionService.class);
50 InputStream jsTemplate = getClass().getClassLoader().getResourceAsStream(MAIN_JS);
51 String js = new String(toByteArray(jsTemplate));
52
53 int p1s = split(js, 0, INJECT_VIEW_IDS_START);
54 int p1e = split(js, 0, INJECT_VIEW_IDS_END);
55 int p2s = split(js, p1e, null);
56
57 StreamEnumeration streams =
58 new StreamEnumeration(of(stream(js, 0, p1s),
59 includeViewIds(service),
60 stream(js, p1e, p2s)));
61
62 return Response.ok(new SequenceInputStream(streams)).build();
63 }
64
65 // Produces an input stream including view id injections from all extensions.
66 private InputStream includeViewIds(UiExtensionService service) {
67 StringBuilder sb = new StringBuilder("\n");
68 for (UiExtension extension : service.getExtensions()) {
69 for (UiView view : extension.views()) {
70 sb.append(" '").append(view.id()).append("',");
71 }
72 }
73 return new ByteArrayInputStream(sb.toString().getBytes());
74 }
75
76}