View Javadoc
1   /*
2    * Copyright 2016 The Lannister Project
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   */
16  
17  package net.anyflow.lannister.httphandler.api;
18  
19  import java.util.stream.Collectors;
20  
21  import com.fasterxml.jackson.core.JsonProcessingException;
22  import com.fasterxml.jackson.databind.ObjectMapper;
23  import com.google.common.base.Strings;
24  
25  import io.netty.handler.codec.http.HttpResponseStatus;
26  import net.anyflow.lannister.http.HttpRequestHandler;
27  import net.anyflow.lannister.topic.Topic;
28  
29  @HttpRequestHandler.Handles(paths = { "api/topics" }, httpMethods = { "GET" })
30  public class Topics extends HttpRequestHandler {
31  
32  	private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(Topics.class);
33  
34  	@Override
35  	public String service() {
36  		String filter = Strings.nullToEmpty(httpRequest().parameter("filter"));
37  
38  		switch (filter) {
39  		case "":
40  		case "all":
41  			return all();
42  		case "nosys":
43  			return nosys();
44  
45  		default:
46  			return null;
47  		}
48  	}
49  
50  	private String all() {
51  		try {
52  			return new ObjectMapper().writeValueAsString(
53  					Topic.NEXUS.keySet().stream().map(key -> Topic.NEXUS.get(key)).collect(Collectors.toList()));
54  		}
55  		catch (JsonProcessingException e) {
56  			logger.error(e.getMessage(), e);
57  
58  			this.httpResponse().setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
59  			return null;
60  		}
61  	}
62  
63  	private String nosys() {
64  		try {
65  			return new ObjectMapper()
66  					.writeValueAsString(Topic.NEXUS.keySet().stream().filter(topicName -> !topicName.startsWith("$SYS"))
67  							.map(key -> Topic.NEXUS.get(key)).collect(Collectors.toList()));
68  		}
69  		catch (JsonProcessingException e) {
70  			logger.error(e.getMessage(), e);
71  			return null;
72  		}
73  	}
74  }