update link to upper-constraints.txt
[dmaap/datarouter.git] / datarouter-node / src / main / java / org / onap / dmaap / datarouter / node / NodeServlet.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.node;
26
27 import static org.onap.dmaap.datarouter.node.utils.NodeUtils.sendResponseError;
28
29 import com.att.eelf.configuration.EELFLogger;
30 import com.att.eelf.configuration.EELFManager;
31 import jakarta.servlet.http.HttpServlet;
32 import java.io.File;
33 import java.io.FileOutputStream;
34 import java.io.FileWriter;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.io.OutputStream;
38 import java.io.Writer;
39 import java.nio.file.Files;
40 import java.nio.file.Path;
41 import java.nio.file.Paths;
42 import java.util.Enumeration;
43 import java.util.regex.Pattern;
44 import jakarta.servlet.http.HttpServletRequest;
45 import jakarta.servlet.http.HttpServletResponse;
46 import org.jetbrains.annotations.Nullable;
47 import org.onap.dmaap.datarouter.node.delivery.Delivery;
48 import org.onap.dmaap.datarouter.node.eelf.EelfMsgs;
49 import org.onap.dmaap.datarouter.node.log.StatusLog;
50 import org.onap.dmaap.datarouter.node.utils.NodeUtils;
51 import org.slf4j.MDC;
52
53 /**
54  * Servlet for handling all http and https requests to the data router node.
55  *
56  * <p>Handled requests are:
57  * <br>
58  * GET http://<i>node</i>/internal/fetchProv - fetch the provisioning data
59  * <br>
60  * PUT/DELETE https://<i>node</i>/internal/publish/<i>fileid</i> - n2n transfer
61  * <br>
62  * PUT/DELETE https://<i>node</i>/publish/<i>feedid</i>/<i>fileid</i> - publsh request
63  */
64 public class NodeServlet extends HttpServlet {
65
66     private static final String FROM = " from ";
67     private static final String INVALID_REQUEST_URI = "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.";
68     private static final String IO_EXCEPTION = "IOException";
69     private static final String ON_BEHALF_OF = "X-DMAAP-DR-ON-BEHALF-OF";
70     private final NodeConfigManager config;
71     private static final Pattern metaDataPattern;
72     private static final EELFLogger eelfLogger = EELFManager.getInstance().getLogger(NodeServlet.class);
73
74     static {
75         final String ws = "\\s*";
76         // assume that \\ and \" have been replaced by X
77         final String string = "\"[^\"]*\"";
78         final String number = "[+-]?(?:\\.\\d+|(?:0|[1-9]\\d*)(?:\\.\\d*)?)(?:[eE][+-]?\\d+)?";
79         final String value = "(?:" + string + "|" + number + "|null|true|false)";
80         final String item = string + ws + ":" + ws + value + ws;
81         final String object = ws + "\\{" + ws + "(?:" + item + "(?:" + "," + ws + item + ")*)?\\}" + ws;
82         metaDataPattern = Pattern.compile(object, Pattern.DOTALL);
83     }
84
85     private final Delivery delivery;
86
87     NodeServlet(Delivery delivery, NodeConfigManager nodeConfigManager) {
88         config = nodeConfigManager;
89         this.delivery = delivery;
90     }
91
92     /**
93      * Get the NodeConfigurationManager.
94      */
95     @Override
96     public void init() {
97         eelfLogger.debug("NODE0101 Node Servlet Configured");
98     }
99
100     private boolean down(HttpServletResponse resp) {
101         if (config.isShutdown() || !config.isConfigured()) {
102             sendResponseError(resp, HttpServletResponse.SC_SERVICE_UNAVAILABLE, eelfLogger);
103             eelfLogger.error("NODE0102 Rejecting request: Service is being quiesced");
104             return true;
105         }
106         return false;
107     }
108
109     /**
110      * Handle a GET for /internal/fetchProv.
111      */
112     @Override
113     protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
114         NodeUtils.setIpAndFqdnForEelf("doGet");
115         NodeUtils.setRequestIdAndInvocationId(req);
116         eelfLogger.info(EelfMsgs.ENTRY);
117         try {
118             eelfLogger.debug(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(ON_BEHALF_OF),
119                 getIdFromPath(req) + "");
120             if (down(resp)) {
121                 return;
122             }
123             String path = req.getPathInfo();
124             String qs = req.getQueryString();
125             String ip = req.getRemoteAddr();
126             if (qs != null) {
127                 path = path + "?" + qs;
128             }
129             if ("/internal/fetchProv".equals(path)) {
130                 config.gofetch(ip);
131                 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
132                 return;
133             } else if (path.startsWith("/internal/resetSubscription/")) {
134                 String subid = path.substring(28);
135                 if (subid.length() != 0 && subid.indexOf('/') == -1) {
136                     NodeServer.resetQueue(subid, ip);
137                     resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
138                     return;
139                 }
140             }
141
142             eelfLogger.debug("NODE0103 Rejecting invalid GET of " + path + FROM + ip);
143             sendResponseError(resp, HttpServletResponse.SC_NOT_FOUND, eelfLogger);
144         } finally {
145             eelfLogger.info(EelfMsgs.EXIT);
146         }
147     }
148
149     /**
150      * Handle all PUT requests.
151      */
152     @Override
153     protected void doPut(HttpServletRequest req, HttpServletResponse resp) {
154         NodeUtils.setIpAndFqdnForEelf("doPut");
155         NodeUtils.setRequestIdAndInvocationId(req);
156         eelfLogger.info(EelfMsgs.ENTRY);
157         eelfLogger.debug(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(ON_BEHALF_OF),
158             getIdFromPath(req) + "");
159         try {
160             common(req, resp, true);
161         } catch (IOException ioe) {
162             eelfLogger.error(IO_EXCEPTION, ioe);
163             eelfLogger.info(EelfMsgs.EXIT);
164         }
165     }
166
167     /**
168      * Handle all DELETE requests.
169      */
170     @Override
171     protected void doDelete(HttpServletRequest req, HttpServletResponse resp) {
172         NodeUtils.setIpAndFqdnForEelf("doDelete");
173         NodeUtils.setRequestIdAndInvocationId(req);
174         eelfLogger.info(EelfMsgs.ENTRY);
175         eelfLogger.debug(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(ON_BEHALF_OF),
176             getIdFromPath(req) + "");
177         try {
178             common(req, resp, false);
179         } catch (IOException ioe) {
180             eelfLogger.error(IO_EXCEPTION, ioe);
181             eelfLogger.info(EelfMsgs.EXIT);
182         }
183     }
184
185     private void common(HttpServletRequest req, HttpServletResponse resp, boolean isput) throws IOException {
186         final String PUBLISH = "/publish/";
187         final String INTERNAL_PUBLISH = "/internal/publish/";
188         final String HTTPS = "https://";
189         final String USER = " user ";
190         String fileid = getFileId(req, resp);
191         if (fileid == null) {
192             return;
193         }
194         String feedid = null;
195         String user = null;
196         String ip = req.getRemoteAddr();
197         String lip = req.getLocalAddr();
198         String pubid = null;
199         String rcvd = NodeUtils.logts(System.currentTimeMillis()) + ";from=" + ip + ";by=" + lip;
200         Target[] targets;
201         if (fileid.startsWith("/delete/")) {
202             deleteFile(req, resp, fileid, pubid);
203             return;
204         }
205         String credentials = req.getHeader("Authorization");
206         if (credentials == null) {
207             eelfLogger.error("NODE0306 Rejecting unauthenticated PUT or DELETE of " + req.getPathInfo() + FROM + req
208                 .getRemoteAddr());
209             resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Authorization header required");
210             eelfLogger.info(EelfMsgs.EXIT);
211             return;
212         }
213         if (fileid.startsWith(PUBLISH)) {
214             fileid = fileid.substring(9);
215             int index = fileid.indexOf('/');
216             if (index == -1 || index == fileid.length() - 1) {
217                 eelfLogger.error("NODE0205 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + FROM + req
218                     .getRemoteAddr());
219                 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
220                     "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.  Possible missing fileid.");
221                 eelfLogger.info(EelfMsgs.EXIT);
222                 return;
223             }
224             feedid = fileid.substring(0, index);
225             fileid = fileid.substring(index + 1);
226             pubid = config.getPublishId();
227             targets = config.getTargets(feedid);
228         } else if (fileid.startsWith(INTERNAL_PUBLISH)) {
229             if (!config.isAnotherNode(credentials, ip)) {
230                 eelfLogger.error("NODE0107 Rejecting unauthorized node-to-node transfer attempt from " + ip);
231                 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
232                 eelfLogger.info(EelfMsgs.EXIT);
233                 return;
234             }
235             fileid = fileid.substring(18);
236             pubid = generateAndValidatePublishId(req);
237             targets = config.parseRouting(req.getHeader("X-DMAAP-DR-ROUTING"));
238         } else {
239             eelfLogger.error("NODE0204 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + FROM + req
240                 .getRemoteAddr());
241             resp.sendError(HttpServletResponse.SC_NOT_FOUND,
242                 INVALID_REQUEST_URI);
243             eelfLogger.info(EelfMsgs.EXIT);
244             return;
245         }
246         if (fileid.indexOf('/') != -1) {
247             eelfLogger.error("NODE0202 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + FROM + req
248                 .getRemoteAddr());
249             resp.sendError(HttpServletResponse.SC_NOT_FOUND,
250                 INVALID_REQUEST_URI);
251             eelfLogger.info(EelfMsgs.EXIT);
252             return;
253         }
254         String qs = req.getQueryString();
255         if (qs != null) {
256             fileid = fileid + "?" + qs;
257         }
258         String hp = config.getMyName();
259         int xp = config.getExtHttpsPort();
260         if (xp != 443) {
261             hp = hp + ":" + xp;
262         }
263         String logurl = HTTPS + hp + INTERNAL_PUBLISH + fileid;
264         if (feedid != null) {
265             logurl = HTTPS + hp + PUBLISH + feedid + "/" + fileid;
266             String reason = config.isPublishPermitted(feedid, credentials, ip);
267             if (reason != null) {
268                 eelfLogger.info("NODE0111 Rejecting unauthorized publish attempt to feed " + feedid + " fileid "
269                     + fileid + " from " + ip + " reason " + reason);
270                 resp.sendError(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN, reason);
271                 eelfLogger.info(EelfMsgs.EXIT);
272                 return;
273             }
274             user = config.getAuthUser(feedid, credentials);
275             String newnode = config.getIngressNode(feedid, user, ip);
276             if (newnode != null) {
277                 String port = "";
278                 int iport = config.getExtHttpsPort();
279                 if (iport != 443) {
280                     port = ":" + iport;
281                 }
282                 String redirto = HTTPS + newnode + port + PUBLISH + feedid + "/" + fileid;
283                 eelfLogger
284                     .debug("NODE0108 Redirecting publish attempt for feed " + PathUtil.cleanString(feedid) + USER
285                         + PathUtil.cleanString(user) + " ip " + PathUtil.cleanString(ip) + " to " + PathUtil
286                         .cleanString(redirto));  //Fortify scan fixes - log forging
287                 resp.sendRedirect(PathUtil.cleanString(redirto));         //Fortify scan fixes-open redirect - 2 issues
288                 eelfLogger.info(EelfMsgs.EXIT);
289                 return;
290             }
291             resp.setHeader("X-DMAAP-DR-PUBLISH-ID", pubid);
292         }
293         if (req.getPathInfo().startsWith(INTERNAL_PUBLISH)) {
294             feedid = req.getHeader("X-DMAAP-DR-FEED-ID");
295         }
296         String fbase = PathUtil.cleanString(config.getSpoolDir() + "/" + pubid);  //Fortify scan fixes-Path manipulation
297         File data = new File(fbase);
298         File meta = new File(fbase + ".M");
299         Writer mw = null;
300         try {
301             StringBuilder mx = new StringBuilder();
302             mx.append(req.getMethod()).append('\t').append(fileid).append('\n');
303             Enumeration<String> hnames = req.getHeaderNames();
304             String ctype = null;
305             boolean hasRequestIdHeader = false;
306             boolean hasInvocationIdHeader = false;
307             while (hnames.hasMoreElements()) {
308                 String hn = hnames.nextElement();
309                 String hnlc = hn.toLowerCase();
310                 if ((isput && ("content-type".equals(hnlc)
311                     || "content-language".equals(hnlc)
312                     || "content-md5".equals(hnlc)
313                     || "content-range".equals(hnlc)))
314                     || "x-dmaap-dr-meta".equals(hnlc)
315                     || (feedid == null && "x-dmaap-dr-received".equals(hnlc))
316                     || (hnlc.startsWith("x-") && !hnlc.startsWith("x-dmaap-dr-"))) {
317                     Enumeration<String> hvals = req.getHeaders(hn);
318                     while (hvals.hasMoreElements()) {
319                         String hv = hvals.nextElement();
320                         if ("content-type".equals(hnlc)) {
321                             ctype = hv;
322                         }
323                         if ("x-onap-requestid".equals(hnlc)) {
324                             hasRequestIdHeader = true;
325                         }
326                         if ("x-invocationid".equals(hnlc)) {
327                             hasInvocationIdHeader = true;
328                         }
329                         if ("x-dmaap-dr-meta".equals(hnlc)) {
330                             if (hv.length() > 4096) {
331                                 eelfLogger.error("NODE0109 Rejecting publish attempt with metadata too long for feed "
332                                     + PathUtil.cleanString(feedid) + USER + PathUtil.cleanString(user) + " ip "
333                                     + PathUtil.cleanString(ip));  //Fortify scan fixes - log forging
334                                 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Metadata too long");
335                                 eelfLogger.info(EelfMsgs.EXIT);
336                                 return;
337                             }
338                             if (!metaDataPattern.matcher(hv.replaceAll("\\\\.", "X")).matches()) {
339                                 eelfLogger.error("NODE0109 Rejecting publish attempt with malformed metadata for feed "
340                                     + PathUtil.cleanString(feedid) + USER + PathUtil.cleanString(user) + " ip "
341                                     + PathUtil.cleanString(ip));  //Fortify scan fixes - log forging
342                                 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Malformed metadata");
343                                 eelfLogger.info(EelfMsgs.EXIT);
344                                 return;
345                             }
346                         }
347                         mx.append(hn).append('\t').append(hv).append('\n');
348                     }
349                 }
350             }
351             if (!hasRequestIdHeader) {
352                 mx.append("X-ONAP-RequestID\t").append(MDC.get("RequestId")).append('\n');
353             }
354             if (!hasInvocationIdHeader) {
355                 mx.append("X-InvocationID\t").append(MDC.get("InvocationId")).append('\n');
356             }
357             mx.append("X-DMAAP-DR-RECEIVED\t").append(rcvd).append('\n');
358             String metadata = mx.toString();
359             long exlen = getExlen(req);
360             String message = writeInputStreamToFile(req, data);
361             if (message != null) {
362                 StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user,
363                     message);
364                 throw new IOException(message);
365             }
366             Path dpath = Paths.get(fbase);
367             for (Target t : targets) {
368                 DestInfo di = t.getDestInfo();
369                 if (di == null) {
370                     //Handle this? : unknown destination
371                     continue;
372                 }
373                 String dbase = PathUtil
374                     .cleanString(di.getSpool() + "/" + pubid);  //Fortify scan fixes-Path Manipulation
375                 Files.createLink(Paths.get(dbase), dpath);
376                 mw = new FileWriter(meta);
377                 mw.write(metadata);
378                 if (di.getSubId() == null) {
379                     mw.write("X-DMAAP-DR-ROUTING\t" + t.getRouting() + "\n");
380                 }
381                 mw.close();
382                 if (!meta.renameTo(new File(dbase + ".M"))) {
383                     eelfLogger.error("Rename of file " + dbase + " failed.");
384                 }
385             }
386             resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
387             try {
388                 resp.getOutputStream().close();
389             } catch (IOException ioe) {
390                 StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user,
391                     ioe.getMessage());
392                 //Fortify scan fixes - log forging
393                 eelfLogger.error("NODE0110 IO Exception while closing IO stream " + PathUtil.cleanString(feedid)
394                     + USER + PathUtil.cleanString(user) + " ip " + PathUtil.cleanString(ip) + " " + ioe
395                     .toString(), ioe);
396                 throw ioe;
397             }
398
399             StatusLog.logPub(pubid, feedid, logurl, req.getMethod(), ctype, data.length(), ip, user,
400                 HttpServletResponse.SC_NO_CONTENT);
401         } catch (IOException ioe) {
402             eelfLogger.error("NODE0110 IO Exception receiving publish attempt for feed " + feedid + USER + user
403                 + " ip " + ip + " " + ioe.toString(), ioe);
404             eelfLogger.info(EelfMsgs.EXIT);
405             throw ioe;
406         } finally {
407             if (mw != null) {
408                 try {
409                     mw.close();
410                 } catch (Exception e) {
411                     eelfLogger.error("NODE0532 Exception common: " + e);
412                 }
413             }
414             try {
415                 Files.delete(data.toPath());
416                 Files.delete(meta.toPath());
417             } catch (Exception e) {
418                 eelfLogger.error("NODE0533 Exception common: " + e);
419             }
420         }
421     }
422
423     private String generateAndValidatePublishId(HttpServletRequest req) throws IOException {
424         String newPubId = req.getHeader("X-DMAAP-DR-PUBLISH-ID");
425
426         String regex = ".*";
427
428         if(newPubId.matches(regex)){
429             return newPubId;
430         }
431         throw new IOException("Invalid Header X-DMAAP-DR-PUBLISH-ID");
432     }
433
434     private String writeInputStreamToFile(HttpServletRequest req, File data) {
435         byte[] buf = new byte[1024 * 1024];
436         int bytesRead;
437         try (OutputStream dos = new FileOutputStream(data);
438             InputStream is = req.getInputStream()) {
439             while ((bytesRead = is.read(buf)) > 0) {
440                 dos.write(buf, 0, bytesRead);
441             }
442         } catch (IOException ioe) {
443             eelfLogger.error("NODE0530 Exception common: " + ioe, ioe);
444             eelfLogger.info(EelfMsgs.EXIT);
445             return ioe.getMessage();
446         }
447         return null;
448     }
449
450     private long getExlen(HttpServletRequest req) {
451         long exlen = -1;
452         try {
453             exlen = Long.parseLong(req.getHeader("Content-Length"));
454         } catch (Exception e) {
455             eelfLogger.error("NODE0529 Exception common: " + e);
456         }
457         return exlen;
458     }
459
460     private void deleteFile(HttpServletRequest req, HttpServletResponse resp, String fileid, String pubid) {
461         final String FROM_DR_MESSAGE = ".M) from DR Node: ";
462         try {
463             fileid = fileid.substring(8);
464             int index = fileid.indexOf('/');
465             if (index == -1 || index == fileid.length() - 1) {
466                 eelfLogger.error("NODE0112 Rejecting bad URI for DELETE of " + req.getPathInfo() + FROM + req
467                     .getRemoteAddr());
468                 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
469                     "Invalid request URI. Expecting <subId>/<pubId>.");
470                 eelfLogger.info(EelfMsgs.EXIT);
471                 return;
472             }
473             String subscriptionId = fileid.substring(0, index);
474             int subId = Integer.parseInt(subscriptionId);
475             pubid = fileid.substring(index + 1);
476             String errorMessage = "Unable to delete files (" + pubid + ", " + pubid + FROM_DR_MESSAGE
477                 + config.getMyName() + ".";
478             int subIdDir = subId - (subId % 100);
479             if (!isAuthorizedToDelete(resp, subscriptionId, errorMessage)) {
480                 return;
481             }
482             boolean result = delivery.markTaskSuccess(config.getSpoolBase() + "/s/" + subIdDir + "/" + subId, pubid);
483             if (result) {
484                 eelfLogger.debug("NODE0115 Successfully deleted files (" + pubid + ", " + pubid + FROM_DR_MESSAGE
485                     + config.getMyName());
486                 resp.setStatus(HttpServletResponse.SC_OK);
487                 eelfLogger.info(EelfMsgs.EXIT);
488             } else {
489                 eelfLogger.error("NODE0116 " + errorMessage);
490                 resp.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found on server.");
491                 eelfLogger.info(EelfMsgs.EXIT);
492             }
493         } catch (IOException ioe) {
494             eelfLogger.error("NODE0117 Unable to delete files (" + pubid + ", " + pubid + FROM_DR_MESSAGE
495                 + config.getMyName(), ioe);
496             eelfLogger.info(EelfMsgs.EXIT);
497         }
498     }
499
500     @Nullable
501     private String getFileId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
502         if (down(resp)) {
503             eelfLogger.info(EelfMsgs.EXIT);
504             return null;
505         }
506         if (!req.isSecure() && config.isTlsEnabled()) {
507             eelfLogger.error(
508                 "NODE0104 Rejecting insecure PUT or DELETE of " + req.getPathInfo() + FROM + req
509                     .getRemoteAddr());
510             resp.sendError(HttpServletResponse.SC_FORBIDDEN, "https required on publish requests");
511             eelfLogger.info(EelfMsgs.EXIT);
512             return null;
513         }
514         String fileid = req.getPathInfo();
515         if (fileid == null) {
516             eelfLogger.error("NODE0201 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + FROM + req
517                 .getRemoteAddr());
518             resp.sendError(HttpServletResponse.SC_NOT_FOUND,
519                 INVALID_REQUEST_URI);
520             eelfLogger.info(EelfMsgs.EXIT);
521             return null;
522         }
523         return fileid;
524     }
525
526     private boolean isAuthorizedToDelete(HttpServletResponse resp, String subscriptionId, String errorMessage)
527         throws IOException {
528         try {
529             boolean deletePermitted = config.isDeletePermitted(subscriptionId);
530             if (!deletePermitted) {
531                 eelfLogger.error("NODE0113 " + errorMessage + " Error: Subscription "
532                     + subscriptionId + " is not a privileged subscription");
533                 resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
534                 eelfLogger.info(EelfMsgs.EXIT);
535                 return false;
536             }
537         } catch (NullPointerException npe) {
538             eelfLogger.error("NODE0114 " + errorMessage + " Error: Subscription " + subscriptionId
539                 + " does not exist", npe);
540             resp.sendError(HttpServletResponse.SC_NOT_FOUND);
541             eelfLogger.info(EelfMsgs.EXIT);
542             return false;
543         }
544         return true;
545     }
546
547     private int getIdFromPath(HttpServletRequest req) {
548         String path = req.getPathInfo();
549         if (path == null || path.length() < 2) {
550             return -1;
551         }
552         try {
553             return Integer.parseInt(path.substring(1));
554         } catch (NumberFormatException e) {
555             return -1;
556         }
557     }
558
559     /**
560      * Utility class that validates the path url formed from
561      * the string passed in the request parameters.
562      */
563     static class PathUtil {
564
565         private PathUtil() {
566             throw new IllegalStateException("Utility Class");
567         }
568
569         /**
570          * This method takes String as the parameter and return the filtered path string.
571          *
572          * @param string String to clean
573          * @return A cleaned String
574          */
575         static String cleanString(String string) {
576             if (string == null) {
577                 return null;
578             }
579             StringBuilder cleanString = new StringBuilder();
580             for (int i = 0; i < string.length(); ++i) {
581                 cleanString.append(cleanChar(string.charAt(i)));
582             }
583             return cleanString.toString();
584         }
585
586         /**
587          * This method filters the valid special characters in path string.
588          *
589          * @param character The char to be cleaned
590          * @return The cleaned char
591          */
592         private static char cleanChar(char character) {
593             // 0 - 9
594             for (int i = 48; i < 58; ++i) {
595                 if (character == i) {
596                     return (char) i;
597                 }
598             }
599             // 'A' - 'Z'
600             for (int i = 65; i < 91; ++i) {
601                 if (character == i) {
602                     return (char) i;
603                 }
604             }
605             // 'a' - 'z'
606             for (int i = 97; i < 123; ++i) {
607                 if (character == i) {
608                     return (char) i;
609                 }
610             }
611             return getValidCharacter(character);
612         }
613
614         private static char getValidCharacter(char character) {
615             // other valid characters
616             switch (character) {
617                 case '/':
618                     return '/';
619                 case '.':
620                     return '.';
621                 case '-':
622                     return '-';
623                 case ':':
624                     return ':';
625                 case '?':
626                     return '?';
627                 case '&':
628                     return '&';
629                 case '=':
630                     return '=';
631                 case '#':
632                     return '#';
633                 case '_':
634                     return '_';
635                 case ' ':
636                     return ' ';
637                 default:
638                     return '%';
639             }
640         }
641     }
642 }