Merge "Unit test base"
[dmaap/datarouter.git] / datarouter-prov / src / main / java / org / onap / dmaap / datarouter / provisioning / PublishServlet.java
1 /*******************************************************************************
2  * ============LICENSE_START==================================================
3  * * org.onap.dmaap
4  * * ===========================================================================
5  * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * * ===========================================================================
7  * * Licensed under the Apache License, Version 2.0 (the "License");
8  * * you may not use this file except in compliance with the License.
9  * * You may obtain a copy of the License at
10  * *
11  *  *      http://www.apache.org/licenses/LICENSE-2.0
12  * *
13  *  * Unless required by applicable law or agreed to in writing, software
14  * * distributed under the License is distributed on an "AS IS" BASIS,
15  * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * * See the License for the specific language governing permissions and
17  * * limitations under the License.
18  * * ============LICENSE_END====================================================
19  * *
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  * *
22  ******************************************************************************/
23
24
25 package org.onap.dmaap.datarouter.provisioning;
26
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.List;
32 import java.util.Properties;
33
34 import javax.servlet.ServletConfig;
35 import javax.servlet.ServletException;
36 import javax.servlet.http.HttpServletRequest;
37 import javax.servlet.http.HttpServletResponse;
38
39 import org.json.JSONArray;
40 import org.json.JSONObject;
41 import org.json.JSONTokener;
42 import org.onap.dmaap.datarouter.provisioning.beans.EventLogRecord;
43 import org.onap.dmaap.datarouter.provisioning.beans.Feed;
44 import org.onap.dmaap.datarouter.provisioning.beans.IngressRoute;
45 import org.onap.dmaap.datarouter.provisioning.eelf.EelfMsgs;
46 import org.onap.dmaap.datarouter.provisioning.utils.*;
47
48 import com.att.eelf.configuration.EELFLogger;
49 import com.att.eelf.configuration.EELFManager;
50
51 /**
52  * This servlet handles redirects for the <publishURL> on the provisioning server,
53  * which is generated by the provisioning server to handle a particular subscriptions to a feed.
54  * See the <b>File Publishing and Delivery API</b> document for details on how these methods
55  * should be invoked.
56  *
57  * @author Robert Eby
58  * @version $Id: PublishServlet.java,v 1.8 2014/03/12 19:45:41 eby Exp $
59  */
60 @SuppressWarnings("serial")
61 public class PublishServlet extends BaseServlet {
62     private int next_node;
63     private String provstring;
64     private List<IngressRoute> irt;
65     //Adding EELF Logger Rally:US664892
66     private static EELFLogger eelflogger = EELFManager.getInstance().getLogger("org.onap.dmaap.datarouter.provisioning.PublishServlet");
67
68
69     @Override
70     public void init(ServletConfig config) throws ServletException {
71         super.init(config);
72         next_node = 0;
73         provstring = "";
74         irt = new ArrayList<IngressRoute>();
75
76     }
77     @Override
78     public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
79         setIpAndFqdnForEelf("doDelete");
80         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");
81         redirect(req, resp);
82     }
83     @Override
84     public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
85         setIpAndFqdnForEelf("doGet");
86         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");
87         redirect(req, resp);
88     }
89     @Override
90     public void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
91         setIpAndFqdnForEelf("doPut");
92         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");
93         redirect(req, resp);
94     }
95     @Override
96     public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
97         setIpAndFqdnForEelf("doPost");
98         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF, req.getHeader(BEHALF_HEADER));
99         redirect(req, resp);
100     }
101     private void redirect(HttpServletRequest req, HttpServletResponse resp) throws IOException {
102         String[] nodes = getNodes();
103         if (nodes == null || nodes.length == 0) {
104             resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "There are no nodes defined in the DR network.");
105         } else {
106             EventLogRecord elr = new EventLogRecord(req);
107             int feedid = checkPath(req);
108             if (feedid < 0) {
109                 String message = (feedid == -1)
110                     ? "Invalid request - Missing or bad feed number."
111                     : "Invalid request - Missing file ID.";
112                 elr.setMessage(message);
113                 elr.setResult(HttpServletResponse.SC_NOT_FOUND);
114                 eventlogger.info(elr);
115
116                 resp.sendError(HttpServletResponse.SC_NOT_FOUND, message);
117             } else {
118                 // Generate new URL
119                 String nextnode = getRedirectNode(feedid, req);
120                 nextnode = nextnode+":"+DB.HTTPS_PORT;
121                 String newurl = "https://" + nextnode + "/publish" + req.getPathInfo();
122                 String qs = req.getQueryString();
123                 if (qs != null)
124                     newurl += "?" + qs;
125
126                 // Log redirect in event log
127                 String message = "Redirected to: "+newurl;
128                 elr.setMessage(message);
129                 elr.setResult(HttpServletResponse.SC_MOVED_PERMANENTLY);
130                 eventlogger.info(elr);
131
132                 resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
133                 resp.setHeader("Location", newurl);
134             }
135         }
136     }
137     private String getRedirectNode(int feedid, HttpServletRequest req) {
138         // Check to see if the IRT needs to be updated
139         Poker p = Poker.getPoker();
140         String s = p.getProvisioningString();
141         synchronized (provstring) {
142             if (irt == null || (s.length() != provstring.length()) || !s.equals(provstring)) {
143                 // Provisioning string has changed -- update the IRT
144                 provstring = s;
145                 JSONObject jo = new JSONObject(new JSONTokener(provstring));
146                 JSONArray ja = jo.getJSONArray("ingress");
147                 List<IngressRoute> newlist = new ArrayList<IngressRoute>();
148                 for (int i = 0; i < ja.length(); i++) {
149                     IngressRoute iroute = new IngressRoute(ja.getJSONObject(i));
150                     newlist.add(iroute);
151                 }
152                 irt = newlist;
153             }
154         }
155
156         // Look in IRT for next node
157         for (IngressRoute route : irt) {
158             if (route.matches(feedid, req)) {
159                 // pick a node at random from the list
160                 Collection<String> nodes = route.getNodes();
161                 String[] arr = nodes.toArray(new String[0]);
162                 long id = System.currentTimeMillis() % arr.length;
163                 String node = arr[(int) id];
164                 intlogger.info("Redirecting to "+node+" because of route "+route);
165                 return node;
166             }
167         }
168
169         // No IRT rule matches, do round robin of all active nodes
170         String[] nodes = getNodes();
171         if (next_node >= nodes.length)    // The list of nodes may have grown/shrunk
172             next_node = 0;
173         return nodes[next_node++];
174     }
175     private int checkPath(HttpServletRequest req) {
176         String path = req.getPathInfo();
177         if (path == null || path.length() < 2)
178             return -1;
179         path = path.substring(1);
180         int ix = path.indexOf('/');
181         if (ix < 0 || ix == path.length()-1)
182             return -2;
183         try {
184             int feedid = Integer.parseInt(path.substring(0, ix));
185             if (!Feed.isFeedValid(feedid))
186                 return -1;
187             return feedid;
188         } catch (NumberFormatException e) {
189             return -1;
190         }
191     }
192 }