List of usage examples for org.apache.commons.lang3 StringEscapeUtils escapeHtml4
public static final String escapeHtml4(final String input)
Escapes the characters in a String using HTML entities.
For example:
"bread" & "butter"
"bread" & "butter"
.
From source file:baggage.hypertoolkit.html.Html.java
public static Tag textInput(String name) { Tag tag = input();/*from ww w.j a va2s. co m*/ tag.attr("type", "text"); tag.attr("name", StringEscapeUtils.escapeHtml4(name)); return tag; }
From source file:com.esri.gpt.control.arcims.ServletConnectorProxy.java
/** * Communicates with redirect url and works as a transparent proxy * //from ww w . j av a 2s .co m * @param request * the servlet request * @param response * the servlet response * @throws IOException * if an exception occurs */ private void executeProxy(HttpServletRequest request, HttpServletResponse response) throws IOException { HttpURLConnection httpCon = null; URL redirectURL = null; InputStream input = null; OutputStream output = null; InputStream proxyInput = null; OutputStream proxyOutput = null; try { input = request.getInputStream(); output = response.getOutputStream(); String sQueryStr = request.getQueryString(); String sAuthorization = request.getHeader("Authorization"); String requestBody = readInputCharacters(input); String requestMethod = request.getMethod(); String contentType = request.getContentType(); String encoding = request.getCharacterEncoding(); LOGGER.finer(" Request method = " + requestMethod); LOGGER.finer(" Query string = " + sQueryStr); LOGGER.finer(" Authorization header =" + sAuthorization); LOGGER.finer(" Character Encoding = " + encoding); LOGGER.finer(" The redirect URL is " + this._redirectURL + "?" + sQueryStr); redirectURL = new URL(this._redirectURL + "?" + sQueryStr); httpCon = (HttpURLConnection) redirectURL.openConnection(); httpCon.setDoInput(true); httpCon.setDoOutput(true); httpCon.setUseCaches(false); httpCon.setRequestMethod(requestMethod); httpCon.setRequestProperty("Content-type", contentType); if (sAuthorization != null) { httpCon.addRequestProperty("Authorization", sAuthorization); } proxyOutput = httpCon.getOutputStream(); send(requestBody, proxyOutput); String authenticateHdr = httpCon.getHeaderField("WWW-Authenticate"); if (authenticateHdr != null) { LOGGER.finer(" WWW-Authenticate : " + authenticateHdr); response.setHeader("WWW-Authenticate", StringEscapeUtils.escapeHtml4(Val.stripControls(authenticateHdr))); } LOGGER.finer(" Response Code : " + httpCon.getResponseCode()); if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR)) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } else { proxyInput = httpCon.getInputStream(); send(proxyInput, output); } } catch (Exception e) { e.printStackTrace(); } finally { if (input != null) { input.close(); } if (output != null) { output.close(); } if (proxyInput != null) { proxyInput.close(); } if (proxyOutput != null) { proxyOutput.close(); } if (httpCon != null) { httpCon.disconnect(); } } }
From source file:edu.kit.dama.mdm.content.util.DublinCoreHelper.java
/** * Create the Dublin Core element map.//from www .ja v a 2 s .c o m * * @param theObject The object to create the DC information for. * @param pCreator A custom creator stored as author/publisher in Dublin * Core. If not provided, the object's uploader is used if available. * * @return The Dublin Core elements as map. * * @throws ParserConfigurationException If creating the Dublin Core document * failed. */ public static Map<String, String> createDublinCoreElementMap(DigitalObject theObject, UserData pCreator) throws ParserConfigurationException { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); Map<String, String> elements = new LinkedHashMap<>(); elements.put("dc:title", StringEscapeUtils.escapeHtml4(theObject.getLabel())); if (pCreator != null) { elements.put("dc:creator", StringEscapeUtils.escapeHtml4(pCreator.getFullname())); elements.put("dc:publisher", StringEscapeUtils.escapeHtml4(pCreator.getFullname())); } else if (theObject.getUploader() != null) { elements.put("dc:creator", StringEscapeUtils.escapeHtml4(theObject.getUploader().getFullname())); elements.put("dc:publisher", StringEscapeUtils.escapeHtml4(theObject.getUploader().getFullname())); } theObject.getExperimenters().stream().filter(( experimenter) -> (theObject.getUploader() == null || !experimenter.equals(theObject.getUploader()))) .forEach((experimenter) -> { elements.put("dc:contributor", StringEscapeUtils.escapeHtml4(experimenter.getFullname())); }); //don't list uploader a second time here if (theObject.getInvestigation() != null) { elements.put("dc:subject", StringEscapeUtils.escapeHtml4(theObject.getInvestigation().getTopic())); if (theObject.getInvestigation().getDescription() != null) { elements.put("dc:description", StringEscapeUtils.escapeHtml4(theObject.getInvestigation().getDescription())); } if (theObject.getInvestigation().getStudy() != null) { if (theObject.getInvestigation().getStudy().getLegalNote() != null) { elements.put("dc:rights", StringEscapeUtils.escapeHtml4(theObject.getInvestigation().getStudy().getLegalNote())); } } } if (theObject.getStartDate() != null) { elements.put("dc:date", df.format(theObject.getStartDate())); } elements.put("dc:format", "application/octet-stream"); elements.put("dc:type", "Dataset"); elements.put("dc:identifier", StringEscapeUtils.escapeHtml4(theObject.getDigitalObjectId().getStringRepresentation())); return elements; }
From source file:com.searchcode.app.service.CodeMatcher.java
/** * If changing anything in here be wary of performance issues as it is the slowest method by a long shot. * Be especially careful of branch prediction issues which is why this method has been re-written several times * just to avoid those issues even though the result was a LONGER method * TODO wring more performance out of this method where possible *///w w w . j a v a 2s .com public List<CodeMatchResult> findMatchingLines(List<String> code, List<String> matchTerms, boolean highlightLine) { List<CodeMatchResult> resultLines = new LinkedList<>(); int codesize = code.size(); int searchThrough = codesize > this.MAXLINEDEPTH ? this.MAXLINEDEPTH : codesize; int matching = 0; // Go through each line finding matching lines for (int i = 0; i < searchThrough; i++) { String matchRes = code.get(i).toLowerCase().replaceAll("\\s+", " "); matching = 0; for (String matchTerm : matchTerms) { if (matchRes.contains(matchTerm.replace("*", ""))) { matching++; } } if (matching != 0) { resultLines.add(new CodeMatchResult(code.get(i), true, false, matching, i)); } } // Get the adjacent lines List<CodeMatchResult> adajacentLines = new LinkedList<>(); for (CodeMatchResult cmr : resultLines) { int linenumber = cmr.getLineNumber(); int previouslinenumber = linenumber - 1; int nextlinenumber = linenumber + 1; if (previouslinenumber >= 0 && !this.resultExists(resultLines, previouslinenumber)) { adajacentLines.add( new CodeMatchResult(code.get(previouslinenumber), false, false, 0, previouslinenumber)); } if (nextlinenumber < codesize && !this.resultExists(resultLines, nextlinenumber)) { adajacentLines.add(new CodeMatchResult(code.get(nextlinenumber), false, false, 0, nextlinenumber)); } } resultLines.addAll(adajacentLines); // If not matching we probably matched on the filename or past 10000 if (resultLines.size() == 0) { searchThrough = codesize > MATCHLINES ? MATCHLINES : codesize; for (int i = 0; i < searchThrough; i++) { resultLines.add(new CodeMatchResult(code.get(i), false, false, 0, i)); } } // Highlight the lines if required but always escape everything if (highlightLine) { for (CodeMatchResult cmr : resultLines) { if (cmr.isMatching()) { String line = Values.EMPTYSTRING; try { line = this.highlightLine(cmr.getLine(), matchTerms); } catch (StringIndexOutOfBoundsException ex) { Singleton.getLogger().severe("Unable to highlightLine " + cmr.getLine() + " using terms " + String.join(",", matchTerms) + " " + ex.toString()); } cmr.setLine(line); } else { cmr.setLine(StringEscapeUtils.escapeHtml4(cmr.getLine())); } } } else { for (CodeMatchResult cmr : resultLines) { cmr.setLine(StringEscapeUtils.escapeHtml4(cmr.getLine())); } } return resultLines; }
From source file:com.github.naoghuman.cm.model.matrix.MatrixModel.java
@Override public void writeExternal(ObjectOutput out) throws IOException { out.writeLong(this.getId()); out.writeLong(this.getGenerationTime()); out.writeObject(StringEscapeUtils.escapeHtml4(this.getTitle())); out.writeObject(StringEscapeUtils.escapeHtml4(this.getDescription())); }
From source file:com.primeleaf.krystal.web.view.console.HomeView.java
@SuppressWarnings("unchecked") private void printCheckouts() { try {/*from www .j ava 2s . com*/ out.println("<div class=\"panel panel-default\">"); out.println("<div class=\"panel-heading\">"); out.println("<h5><i class=\"fa fa-lock fa-lg \"></i> Checked Out Documents</h5>"); out.println("</div>"); ArrayList<CheckedOutDocument> checkedOutDocumentList = (ArrayList<CheckedOutDocument>) request .getAttribute("CHECKOUTS"); if (checkedOutDocumentList.size() > 0) { out.println("<div class=\"list-group\">"); for (CheckedOutDocument checkedOutDocument : checkedOutDocumentList) { out.println("<li class=\"list-group-item\">"); out.println("<a href=\"/console/viewdocument?documentid=" + checkedOutDocument.getDocumentId() + "&revisionid=" + checkedOutDocument.getRevisionId() + "\" class=\"\">"); out.println("<h4>" + StringEscapeUtils.escapeHtml4(checkedOutDocument.getCheckOutPath().toLowerCase()) + "</h4>"); out.println("</a>"); out.println("<h5>Document Class : " + StringEscapeUtils.escapeHtml4(checkedOutDocument.getDocumentClass().getClassName()) + "</h5>"); out.println("<p><h6><a href=\"" + HTTPConstants.BASEURL + "/console/viewdocument?documentid=" + checkedOutDocument.getDocumentId() + "&revisionid=" + checkedOutDocument.getRevisionId() + "\">" + "View Document" + "</a>"); out.println(" | <a href=\"" + HTTPConstants.BASEURL + "/console/checkindocument?documentid=" + checkedOutDocument.getDocumentId() + "&revisionid=" + checkedOutDocument.getRevisionId() + "\">Check In</a>"); out.println(" | <a href=\"" + HTTPConstants.BASEURL + "/console/cancelcheckout?documentid=" + checkedOutDocument.getDocumentId() + "&revisionid=" + checkedOutDocument.getRevisionId() + "\" class=\"confirm\" title=\"Are you sure? you want to cancel checkout?\">Cancel Checkout</a>"); out.println(" | <a href=\"" + HTTPConstants.BASEURL + "/console/revisionhistory?documentid=" + checkedOutDocument.getDocumentId() + "&revisionid=" + checkedOutDocument.getRevisionId() + "\" class=\"revisionhistory\" data-toggle=\"modal\" data-target=\"#revisionHistoryModal\">Revision History</a></h6></p>"); out.println("</li>"); } out.println("</div>"); printModal("revisionHistoryModal"); } else { out.println("<div class=\"panel-body\">"); out.println("There are no documents checked out currently"); out.println("</div>"); } out.println("</div>"); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:com.github.naoghuman.cm.model.notes.NotesModel.java
@Override public void writeExternal(ObjectOutput out) throws IOException { out.writeLong(this.getId()); out.writeLong(this.getMatrixId()); out.writeLong(this.getGenerationTime()); out.writeObject(StringEscapeUtils.escapeHtml4(this.getNotes())); }
From source file:com.technophobia.substeps.report.DetailedJsonBuilder.java
private String getStackTrace(IExecutionNode node) { String stackTrace = ""; if (node.getResult().getThrown() != null) { final StackTraceElement[] stackTraceElements = node.getResult().getThrown().getStackTrace(); final StringBuilder buf = new StringBuilder(); for (final StackTraceElement e : stackTraceElements) { buf.append(StringEscapeUtils.escapeHtml4(e.toString().trim())).append("<br/>"); }// www . ja v a2s. c o m stackTrace = buf.toString(); } return stackTrace; }
From source file:com.day.cq.wcm.foundation.forms.LayoutHelper.java
/** * Print all errors (if there are any.) If there are error messages for this * field, a div for each error message is created. The div has the class * form_row, then {@link #printTitle(String, String, boolean, Writer)} is * called and a third inner div with the message and the classes * form_rightcol and form_error is created. * * @param request The current request. * @param fieldName The name of the field (not the id!) * @param hideLabel Option to completely hide the label (removes form_leftcollabel and form_leftcolmark * divs content)/*from ww w.j a v a 2 s .c o m*/ * @param out The writer. * @throws IOException If writing fails. * @since 5.4 */ public static void printErrors(SlingHttpServletRequest request, String fieldName, boolean hideLabel, Writer out) throws IOException { final ValidationInfo info = ValidationInfo.getValidationInfo(request); // check if we have validation errors if (info != null) { String[] msgs = info.getErrorMessages(fieldName); if (msgs != null) { for (String msg : msgs) { out.write("<div class=\"form_row\">"); printTitle(null, null, false, hideLabel, out); out.write("<div class=\"form_rightcol form_error\">"); String[] msgParas = msg.split("\n"); for (int i = 0; i < msgParas.length; i++) { out.write(StringEscapeUtils.escapeHtml4(msgParas[i])); if (i + 1 < msgParas.length) { out.write("<br>"); } } out.write("</div>"); out.write("</div>"); } } } }
From source file:com.techngage.smartbin.Controller.java
private void initializeRoutes() throws IOException { // Get all the available truck ids get(new Route("/truck") { @Override// w ww .ja v a2 s. c om public Object handle(Request request, Response response) { List<Document> truckList = truckDAO.getTruckIds(); String truckStr = ""; String truckStrTmp = ""; for (int i = 0; i < truckList.size(); i++) { truckStr = (String) truckList.get(i).get("truckid"); if (i == truckList.size() - 1) { truckStrTmp = truckStrTmp + truckStr; } else { truckStrTmp = truckStrTmp + truckStr + ";"; } } return truckStrTmp; } }); // present signup form for smartbin app get(new Route("/unassign") { @Override public Object handle(Request request, Response response) { // Unassign route to truck. int routeId = Integer.parseInt(request.queryParams("routeid")); String truckId = request.queryParams("truckid"); String status = routeDAO.unassignRoute(truckId, routeId); truckDAO.updateTruckAsUnAssigned(truckId, routeDAO.checkRouteAssigned(truckId)); return status; } }); // present signup form for smartbin app get(new Route("/assign") { @Override public Object handle(Request request, Response response) { // Assign route to truck. int routeId = Integer.parseInt(request.queryParams("routeid")); String truckId = request.queryParams("truckid"); String status = routeDAO.assignRoute(truckId, routeId); truckDAO.updateTruckAsAssigned(truckId); return status; } }); // insert location and coordinates, public api called from micro-controller post(new Route("/insert") { @Override public Object handle(Request request, Response response) { String cookie = getSessionCookie(request); String username = sessionDAO.findUserNameBySessionId(cookie); if (username == null) { System.out.println("You are not authorized"); response.status(403); } else { // Insert route. String location = request.queryParams("location"); String coordinates = request.queryParams("coordinates"); boolean isDuplicate = locationDAO.checkDuplicateRoute(coordinates); if (location != null && coordinates != null && !isDuplicate) { locationDAO.insertRoute(location, coordinates); } } return null; } }); // handle the signup to smartbin web app post(new FreemarkerBasedRoute("/signup", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String email = request.queryParams("email"); String username = request.queryParams("username"); String password = request.queryParams("password"); String verify = request.queryParams("verify"); HashMap<String, String> root = new HashMap<String, String>(); root.put("username", StringEscapeUtils.escapeHtml4(username)); root.put("email", StringEscapeUtils.escapeHtml4(email)); if (validateSignup(username, password, verify, email, root)) { // good user System.out.println("Signup: Creating user with: " + username + " " + password); if (!userDAO.addUser(username, password, email)) { // duplicate user root.put("username_error", "Username already in use, Please choose another"); template.process(root, writer); } else { // good user, let's start a session String sessionID = sessionDAO.startSession(username); System.out.println("Session ID is" + sessionID); response.raw().addCookie(new Cookie("session", sessionID)); response.redirect("/dashboard"); } } else { // bad signup System.out.println("User Registration did not validate"); template.process(root, writer); } } }); // present signup form for smartbin app get(new FreemarkerBasedRoute("/signup", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); // initialize values for the form. root.put("username", ""); root.put("password", ""); root.put("email", ""); root.put("password_error", ""); root.put("username_error", ""); root.put("email_error", ""); root.put("verify_error", ""); template.process(root, writer); } }); get(new FreemarkerBasedRoute("/dashboard", "dashboard.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String cookie = getSessionCookie(request); String username = sessionDAO.findUserNameBySessionId(cookie); if (username == null) { System.out.println("dashboard() can't identify the user, redirecting to signup"); response.redirect("/login"); } else { SimpleHash root = new SimpleHash(); int totRoutes = 3; List<Document> routes = routeDAO.getRoutes(totRoutes); root.put("username", username); root.put("names", routeDAO.getRoute()); root.put("myroutes", routes); root.put("totallimitedroutes", totRoutes); root.put("totalescalatedroutes", routeDAO.getEscalatedRoutes().size()); root.put("totalcompletedroutes", routeDAO.getCompletedRoutes().size()); root.put("totalinprogressroutes", routeDAO.getEscalatedRoutes().size()); List<Document> truckList = truckDAO.getTruckIds(); /*String truckStr = ""; String truckStrTmp = ""; for(int i=0;i<truckList.size();i++){ truckStr = (String)truckList.get(i).get("truckid"); if(i == truckList.size()-1){ truckStrTmp = truckStrTmp + truckStr; } else { truckStrTmp = truckStrTmp + truckStr + ";"; } }*/ root.put("trucklist", truckList); template.process(root, writer); } } }); // present the login page get(new FreemarkerBasedRoute("/login", "login.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); root.put("username", ""); root.put("login_error", ""); template.process(root, writer); } }); // process output coming from login form. On success redirect folks to the dashboard // on failure, just return an error and let them try again. post(new FreemarkerBasedRoute("/login", "login.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String username = request.queryParams("username"); String password = request.queryParams("password"); System.out.println("Login: User submitted: " + username + " " + password); Document user = userDAO.validateLogin(username, password); if (user != null) { // valid user, let's log them in String sessionID = sessionDAO.startSession(user.get("_id").toString()); if (sessionID == null) { response.redirect("/internal_error"); } else { // set the cookie for the user's browser response.raw().addCookie(new Cookie("session", sessionID)); response.redirect("/dashboard"); } } else { SimpleHash root = new SimpleHash(); root.put("username", StringEscapeUtils.escapeHtml4(username)); root.put("password", ""); root.put("login_error", "Invalid Login"); template.process(root, writer); } } }); // allows the user to logout of the smartbin app get(new FreemarkerBasedRoute("/logout", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String sessionID = getSessionCookie(request); if (sessionID == null) { // no session to end response.redirect("/login"); } else { // deletes from session table sessionDAO.endSession(sessionID); // this should delete the cookie Cookie c = getSessionCookieActual(request); c.setMaxAge(0); response.raw().addCookie(c); response.redirect("/login"); } } }); // used to process internal errors get(new FreemarkerBasedRoute("/internal_error", "error_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); root.put("error", "System has encountered an error."); template.process(root, writer); } }); }