Replacing mysql to hsqldb
[toolkit.git] / samples / dnsguard / src / main / java / org / sdnhub / dnsguard / northbound / AppNorthbound.java
1 /*
2  * Copyright (c) 2014 SDN Hub.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  *
8  * author: Luis Chiang
9  */
10
11
12 package org.sdnhub.dnsguard.northbound;
13
14 import java.util.List;
15
16 import javax.ws.rs.Consumes;
17 import javax.ws.rs.FormParam;
18 import javax.ws.rs.GET;
19 import javax.ws.rs.POST;
20 import javax.ws.rs.Path;
21 import javax.ws.rs.PathParam;
22 import javax.ws.rs.Produces;
23 import javax.ws.rs.core.Context;
24 import javax.ws.rs.core.MediaType;
25 import javax.ws.rs.core.SecurityContext;
26 import javax.ws.rs.core.UriInfo;
27
28 import org.codehaus.enunciate.jaxrs.StatusCodes;
29 import org.codehaus.enunciate.jaxrs.TypeHint;
30 import org.opendaylight.controller.northbound.commons.RestMessages;
31 import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException;
32 import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException;
33 import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils;
34 import org.opendaylight.controller.sal.authorization.Privilege;
35 import org.opendaylight.controller.sal.utils.ServiceHelper;
36 import org.sdnhub.dnsguard.DnsReply;
37 import org.sdnhub.dnsguard.IDnsGuard;
38 import org.sdnhub.dnsguard.renders.D3pieData;
39 import org.sdnhub.dnsguard.renders.DataTableObject;
40 import org.sdnhub.dnsguard.renders.DnsRecordReply;
41 import org.sdnhub.dnsguard.renders.DnsUsage;
42 import org.sdnhub.dnsguard.renders.Violator;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 import com.google.gson.Gson;
47 import com.google.gson.GsonBuilder;
48
49 /**
50  * Northbound REST API
51  *
52  * This entire web class can be accessed via /northbound prefix as specified in
53  * web.xml
54  *
55  * <br>
56  * <br>
57  * Authentication scheme : <b>HTTP Basic</b><br>
58  * Authentication realm : <b>opendaylight</b><br>
59  * Transport : <b>HTTP and HTTPS</b><br>
60  * <br>
61  * HTTPS Authentication is disabled by default.
62  */
63 @Path("/")
64 public class AppNorthbound {
65         
66         protected static final Logger log = LoggerFactory.getLogger(AppNorthbound.class);
67         
68     @Context
69     private UriInfo _uriInfo;
70     private String username;
71
72     @Context
73     public void setSecurityContext(SecurityContext context) {
74         if (context != null && context.getUserPrincipal() != null) {
75             username = context.getUserPrincipal().getName();
76         }
77     }
78
79     protected String getUserName() {
80         return username;
81     }
82     
83     /**
84      * 
85      * Sample REST API call
86      * 
87      * @return A response string
88      * 
89      *         <pre>
90      * Example:
91      * 
92      * Request URL:
93      * http://127.0.0.1:8080/dnsguard/northbound/test
94      * 
95      * Response body in XML:
96      * &lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;
97      * Sample Northbound API
98      * 
99      * Response body in JSON:
100      * Sample Northbound API
101      * </pre>
102      */
103     @Path("/test")
104     @GET
105     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
106     @TypeHint(String.class)
107     @StatusCodes()
108     public String getTest() {
109         String result = "<xml><output>Sample Northbound API from module DnsGuard</output></xml>";
110         return result;
111     }
112     
113     /**
114      * 
115      * Sample REST API call
116      * 
117      * @return A response string
118      * 
119      *         <pre>
120      * Example:
121      * 
122      * Request URL:
123      * http://127.0.0.1:8080/dnsguard/northbound/echo/{echo}
124      * 
125      * Response body in XML:
126      * &lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;
127      * Sample Northbound API
128      * 
129      * Response body in JSON:
130      * Sample Northbound API
131      * </pre>
132      */
133     @Path("/echo/{echo}")
134     @GET
135     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
136     @TypeHint(String.class)
137     @StatusCodes()
138     public String getEcho(@PathParam("echo") String echo) {
139         
140         if (!NorthboundUtils.isAuthorized(getUserName(), "default", Privilege.READ, this)) {
141             throw new UnauthorizedException("User is not authorized to perform this operation");
142         }
143         
144         IDnsGuard dnshandler = (IDnsGuard) ServiceHelper.getInstance(IDnsGuard.class, "default", this);
145         
146         if (dnshandler == null) {
147             throw new ServiceUnavailableException("DnsHandler Service " + RestMessages.SERVICEUNAVAILABLE.toString());
148         }
149
150         String result = "<xml><output>Query from module DnsGuard " + dnshandler.echo(echo)  + " </output></xml>";
151         
152         return result;
153
154    }
155
156     /**
157      * 
158      * Sample REST API call
159      * 
160      * @return A response string
161      * 
162      *         <pre>
163      * Example:
164      * 
165      * Request URL:
166      * http://127.0.0.1:8080/dnsguard/northbound/resolv
167      * 
168      * Response body in XML:
169      * &lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;
170      * Sample Northbound API
171      * 
172      * Response body in JSON:
173      * Sample Northbound API
174      * </pre>
175      */
176     @Path("/resolv/{IpFrom}/{AppIp}")
177     @GET
178     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON })
179     @TypeHint(String.class)
180     @StatusCodes()
181     public String getQuery(@PathParam("IpFrom") String ipFrom, @PathParam("AppIp") String appIP) {
182         
183         if (!NorthboundUtils.isAuthorized(getUserName(), "default", Privilege.READ, this)) {
184             throw new UnauthorizedException("User is not authorized to perform this operation");
185         }
186         
187         IDnsGuard dnshandler = (IDnsGuard) ServiceHelper.getInstance(IDnsGuard.class, "default", this);
188         
189         if (dnshandler == null) {
190             throw new ServiceUnavailableException("DnsHandler Service " + RestMessages.SERVICEUNAVAILABLE.toString());
191         }
192
193         String result = "<xml><output>ipFrom: " + dnshandler.echo(ipFrom)  + " appIP: " + dnshandler.echo(appIP)  + " </output></xml>";
194         
195         return result;
196     }
197     
198     /**
199      * 
200      * Sample REST API call
201      * 
202      * @return A response string
203      * 
204      *         <pre>
205      * Example:
206      * 
207      * Request URL:
208      * http://127.0.0.1:8080/dnsguard/northbound/lazyresolv/appIp
209      * 
210      * Response body in XML:
211      * &lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;
212      * Sample Northbound API
213      * 
214      * Response body in JSON:
215      * Sample Northbound API
216      * </pre>
217      */
218     @Path("/lazyresolv/{appIp}")
219     @GET
220     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON })
221     @TypeHint(String.class)
222     @StatusCodes()
223     public String lazyresolv(@PathParam("appIp") String appIp) {
224         
225         if (!NorthboundUtils.isAuthorized(getUserName(), "default", Privilege.READ, this)) {
226             throw new UnauthorizedException("User is not authorized to perform this operation");
227         }
228         
229         IDnsGuard dnshandler = (IDnsGuard) ServiceHelper.getInstance(IDnsGuard.class, "default", this);
230         
231         if (dnshandler == null) {
232             throw new ServiceUnavailableException("DnsHandler Service " + RestMessages.SERVICEUNAVAILABLE.toString());
233         }
234
235
236         String json = new Gson().toJson( dnshandler.lazyresolv(appIp) );
237         
238         return json;
239     }
240     
241     /***
242      * 
243      * @param http://127.0.0.1:8080/dnsguard/northbound/appsbyip/{sourceIp}
244      * @return The domains visited by an internal IP
245      */
246     @Path("/appsbyip/{sourceIp}")
247     @GET
248     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON })
249     @TypeHint(String.class)
250     @StatusCodes()
251     public String appsbyip(@PathParam("sourceIp") String sourceIp) {
252         
253         if (!NorthboundUtils.isAuthorized(getUserName(), "default", Privilege.READ, this)) {
254             throw new UnauthorizedException("User is not authorized to perform this operation");
255         }
256         
257         IDnsGuard dnshandler = (IDnsGuard) ServiceHelper.getInstance(IDnsGuard.class, "default", this);
258         
259         if (dnshandler == null) {
260             throw new ServiceUnavailableException("DnsHandler Service " + RestMessages.SERVICEUNAVAILABLE.toString());
261         }
262
263         String json = new Gson().toJson( dnshandler.appsbyip(sourceIp) );
264         
265         return json;
266     }
267
268     /**
269      * 
270      * Returns the violators of the local dns server
271      * 
272      * @return A response string
273      * 
274      *         <pre>
275      * Example:
276      * 
277      * Request URL:
278      * http://127.0.0.1:8080/dnsguard/northbound/getviolators
279      * 
280      * Response body in XML:
281      * &lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;
282      * Sample Northbound API
283      * 
284      * Response body in JSON:
285      * Sample Northbound API
286      * </pre>
287      */
288     @Path("/getviolators")
289     @GET
290     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON })
291     @TypeHint(String.class)
292     @StatusCodes()
293     public String getViolators() {
294         
295         if (!NorthboundUtils.isAuthorized(getUserName(), "default", Privilege.READ, this)) {
296             throw new UnauthorizedException("User is not authorized to perform this operation");
297         }
298         
299         IDnsGuard dnshandler = (IDnsGuard) ServiceHelper.getInstance(IDnsGuard.class, "default", this);
300         
301         if (dnshandler == null) {
302             throw new ServiceUnavailableException("DnsHandler Service " + RestMessages.SERVICEUNAVAILABLE.toString());
303         }
304         
305         List<Violator> violators = dnshandler.getViolators();
306         
307         DataTableObject dataTableObject = new DataTableObject();
308         dataTableObject.setAaData(violators);
309         
310         Gson gson = new GsonBuilder().setPrettyPrinting().create(); 
311         String json = gson.toJson( dataTableObject );
312         
313         return json;
314     }
315
316     
317     /**
318      * 
319      * Returns the violators of the local dns server
320      * 
321      * @return A response string
322      * 
323      *         <pre>
324      * Example:
325      * 
326      * Request URL:
327      * http://127.0.0.1:8080/dnsguard/northbound/getrecords
328      * 
329      * Response body in XML:
330      * &lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;
331      * Sample Northbound API
332      * 
333      * Response body in JSON:
334      * Sample Northbound API
335      * </pre>
336      */
337     @Path("/getrecords")
338     @GET
339     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON })
340     @TypeHint(String.class)
341     @StatusCodes()
342     public String getRecords() {
343         
344         if (!NorthboundUtils.isAuthorized(getUserName(), "default", Privilege.READ, this)) {
345             throw new UnauthorizedException("User is not authorized to perform this operation");
346         }
347         
348         IDnsGuard dnshandler = (IDnsGuard) ServiceHelper.getInstance(IDnsGuard.class, "default", this);
349         
350         if (dnshandler == null) {
351             throw new ServiceUnavailableException("DnsHandler Service " + RestMessages.SERVICEUNAVAILABLE.toString());
352         }
353         
354         List<DnsRecordReply> records = dnshandler.getDatabaseDnsRecords(100, 0);
355         
356         DataTableObject dataTableObject = new DataTableObject();
357         dataTableObject.setAaData(records);
358         
359         Gson gson = new GsonBuilder().setPrettyPrinting().create(); 
360         String json = gson.toJson( dataTableObject );
361         
362         return json;
363     }
364
365     /**
366      * 
367      * Returns the
368      * 
369      * @return A response string
370      * 
371      *         <pre>
372      * Example:
373      * 
374      * Request URL:
375      * http://127.0.0.1:8080/dnsguard/northbound/getrecords
376      * 
377      * Response body in XML:
378      * &lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;
379      * Sample Northbound API
380      * 
381      * Response body in JSON:
382      * Sample Northbound API
383      * </pre>
384      */
385     @Path("/findrecords/")
386     @POST
387     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON })
388     @TypeHint(String.class)
389     @StatusCodes()
390     public String findRecords(@FormParam("draw") String draw, @FormParam("start") String start, @FormParam("length") String length, @FormParam("search[value]") String search) {
391         
392         if (!NorthboundUtils.isAuthorized(getUserName(), "default", Privilege.READ, this)) {
393             throw new UnauthorizedException("User is not authorized to perform this operation");
394         }
395         
396         IDnsGuard dnshandler = (IDnsGuard) ServiceHelper.getInstance(IDnsGuard.class, "default", this);
397         
398         if (dnshandler == null) {
399             throw new ServiceUnavailableException("DnsHandler Service " + RestMessages.SERVICEUNAVAILABLE.toString());
400         }
401         
402        log.info("draw " +  draw + " start " + start + " length " + length + " search " + search);
403        
404        //TODO: LC, change behaivor
405        List<DnsRecordReply> records = dnshandler.getDatabaseDnsRecords(100, 0);
406        
407        DataTableObject dataTableObject = new DataTableObject();
408        dataTableObject.setAaData(records); 
409        dataTableObject.setiDraw(1);
410        
411        Gson gson = new GsonBuilder().setPrettyPrinting().create(); 
412        String json = gson.toJson( dataTableObject );
413        
414        return json;
415         
416     }
417     
418     /**
419      * 
420      * Returns the violators of the local dns server
421      * 
422      * @return A response string
423      * 
424      *         <pre>
425      * Example:
426      * 
427      * Request URL:
428      * http://localhost:8080/dnsguard/northbound/getTopExternalDnsUsage
429      * 
430      * Response body in XML:
431      * &lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;
432      * Sample Northbound API
433      * 
434      * Response body in JSON:
435      * Sample Northbound API
436      * </pre>
437      */
438     @Path("/getTopExternalDnsUsage")
439     @GET
440     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON })
441     @TypeHint(String.class)
442     @StatusCodes()
443     public String getTopExternalDnsUsage() {
444         
445         if (!NorthboundUtils.isAuthorized(getUserName(), "default", Privilege.READ, this)) {
446             throw new UnauthorizedException("User is not authorized to perform this operation");
447         }
448         
449         IDnsGuard dnshandler = (IDnsGuard) ServiceHelper.getInstance(IDnsGuard.class, "default", this);
450         
451         if (dnshandler == null) {
452             throw new ServiceUnavailableException("DnsHandler Service " + RestMessages.SERVICEUNAVAILABLE.toString());
453         }
454         
455         List<DnsUsage> topdns = dnshandler.getExternalDnsUsage(5);
456          
457         D3pieData pieDataObject = new D3pieData();
458         pieDataObject.setContent(topdns);
459         
460         Gson gson = new GsonBuilder().setPrettyPrinting().create(); 
461         String json = gson.toJson( pieDataObject );
462         
463         return json;
464     }
465     
466     /***
467      * 
468      * @param http://127.0.0.1:8080/dnsguard/northbound/setlocaldns/{localdns}
469      * @return The domains visited by an internal IP
470      */
471     @Path("/setlocaldns/{localdns}")
472     @GET
473     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON })
474     @TypeHint(String.class)
475     @StatusCodes()
476         public String setLocalDnsServer(@PathParam("localdns") String local_dns) {
477                 
478                 // TODO Auto-generated method stub
479         if (!NorthboundUtils.isAuthorized(getUserName(), "default", Privilege.READ, this)) {
480             throw new UnauthorizedException("User is not authorized to perform this operation");
481         }
482         
483         IDnsGuard dnshandler = (IDnsGuard) ServiceHelper.getInstance(IDnsGuard.class, "default", this);
484         
485         if (dnshandler == null) {
486             throw new ServiceUnavailableException("DnsHandler Service " + RestMessages.SERVICEUNAVAILABLE.toString());
487         }
488
489
490         String json = new Gson().toJson( dnshandler.setLocalDnsServer(local_dns) );
491         
492         return json;
493         }
494     
495     /***
496      * 
497      * @param http://127.0.0.1:8080/dnsguard/northbound/getlocaldns
498      * @return The domains visited by an internal IP
499      */
500     @Path("/getlocaldns")
501     @GET
502     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON })
503     @TypeHint(String.class)
504     @StatusCodes()
505         public String getLocalDnsServer() {
506                 
507                 // TODO Auto-generated method stub
508         if (!NorthboundUtils.isAuthorized(getUserName(), "default", Privilege.READ, this)) {
509             throw new UnauthorizedException("User is not authorized to perform this operation");
510         }
511         
512         IDnsGuard dnshandler = (IDnsGuard) ServiceHelper.getInstance(IDnsGuard.class, "default", this);
513         
514         if (dnshandler == null) {
515             throw new ServiceUnavailableException("DnsHandler Service " + RestMessages.SERVICEUNAVAILABLE.toString());
516         }
517
518
519         String json = new Gson().toJson( dnshandler.getLocalDnsServer() );
520         
521         return json;
522         }
523     
524
525
526         @POST
527         @Path("/updateconfig")
528         @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
529         @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
530         public String updateconfig(@FormParam("dbserver") String dbserver, @FormParam("dbport") String dbport, @FormParam("dbname") String dbname, @FormParam("dbuser") String dbuser, @FormParam("dbpasswd") String dbpasswd, @FormParam("ib_size") String ib_size, @FormParam("ib_max") String ib_max) throws Exception {
531  
532         String result = "<xml><output>Query from module DnsGuard  </output></xml>";
533         
534         return result;
535         }
536 }