/** * @param request The request object providing information about the HTTP request * @param response The response object providing functionality for modifying the response * @return The content to be set in the response * @throws Exception implementation can choose to throw exception */ public String handlePostNewPost(Request request, Response response) throws Exception { String title = StringEscapeUtils.escapeHtml4(request.queryParams("subject")); String post = StringEscapeUtils.escapeHtml4(request.queryParams("body")); String tags = StringEscapeUtils.escapeHtml4(request.queryParams("tags")); String username = sessionDAO.findUserNameBySessionId(request.cookie("session")); if (username == null) { response.redirect("/login"); // only logged in users can post to blog return templateEngine.render(new ModelAndView(null, "redirect.ftl")); } else if (title.equals("") || post.equals("")) { SimpleHash root = new SimpleHash(); // redisplay page with errors root.put("errors", "post must contain a title and blog entry."); root.put("subject", title); root.put("username", username); root.put("tags", tags); root.put("body", post); return templateEngine.render(new ModelAndView(root, "newpost_template.ftl")); } else { // extract tags List<String> tagsArray = extractTags(tags); // substitute some <p> for the paragraph breaks post = post.replaceAll("\\r?\\n", "<p>"); String permalink = blogPostDAO.addPost(title, post, tagsArray, username); // now redirect to the blog permalink response.redirect("/post/" + permalink); return templateEngine.render(new ModelAndView(null, "redirect.ftl")); } }
public void delegateBooleanAssertion( final Type[] types, final int i2, final int i1, final boolean expected) { final Type type1 = types[i1]; final Type type2 = types[i2]; final boolean isAssignable = TypeUtils.isAssignable(type2, type1); if (expected) { Assert.assertTrue( "[" + i1 + ", " + i2 + "]: From " + StringEscapeUtils.escapeHtml4(String.valueOf(type2)) + " to " + StringEscapeUtils.escapeHtml4(String.valueOf(type1)), isAssignable); } else { Assert.assertFalse( "[" + i1 + ", " + i2 + "]: From " + StringEscapeUtils.escapeHtml4(String.valueOf(type2)) + " to " + StringEscapeUtils.escapeHtml4(String.valueOf(type1)), isAssignable); } }
/** * @param request The request object providing information about the HTTP request * @param response The response object providing functionality for modifying the response * @return The content to be set in the response * @throws Exception implementation can choose to throw exception */ public String handlePostNewComment(Request request, Response response) throws Exception { String name = StringEscapeUtils.escapeHtml4(request.queryParams("commentName")); String email = StringEscapeUtils.escapeHtml4(request.queryParams("commentEmail")); String body = StringEscapeUtils.escapeHtml4(request.queryParams("commentBody")); String permalink = request.queryParams("permalink"); Document post = blogPostDAO.findByPermalink(permalink); if (post == null) { response.redirect("/post_not_found"); return templateEngine.render(new ModelAndView(null, "redirect.ftl")); } // check that comment is good else if (name.equals("") || body.equals("")) { // bounce this back to the user for correction SimpleHash comment = new SimpleHash(); comment.put("name", name); comment.put("email", email); comment.put("body", body); SimpleHash root = new SimpleHash(); root.put("comment", comment); root.put("post", post); root.put("errors", "Post must contain your name and an actual comment"); return templateEngine.render(new ModelAndView(root, "entry_template.ftl")); } else { blogPostDAO.addPostComment(name, email, body, permalink); response.redirect("/post/" + permalink); return templateEngine.render(new ModelAndView(null, "redirect.ftl")); } }
private String postCoupon(HttpServletRequest request) { if (request.getMethod().equals("GET")) return "postCoupon"; String bizName = request.getParameter("bizName"); String bogoDesc = request.getParameter("bogoDesc"); String bizLoc = request.getParameter("bizLoc"); String couponValue = request.getParameter("couponValue"); // Date couponDate = request.getParameter("couponDate"); String zip1 = request.getParameter("zip1"); String zip2 = request.getParameter("zip2"); String zip3 = request.getParameter("zip3"); if (bizName == null || bizName.length() < 1 || bizName.length() > 40) { request.setAttribute("flash", "Content must be between 1-40 characters."); request.setAttribute("bizName", bizName); return "postCoupon"; } if (bogoDesc == null || bogoDesc.length() < 1 || bogoDesc.length() > 40) { request.setAttribute("flash", "Content must be between 1-40 characters."); request.setAttribute("bogoDesc", bogoDesc); return "postCoupon"; } if (bizLoc == null || bizLoc.length() < 1 || bizLoc.length() > 60) { request.setAttribute("flash", "Content must be between 1-60 characters."); request.setAttribute("bizLoc", bizLoc); return "postCoupon"; } if (!zip1.matches("^\\d{5}?$")) { request.setAttribute("flash", "Zipcode must be XXXXX or XXXXX-XXXX format"); request.setAttribute("zip1", zip1); return "postCoupon"; } if (!zip2.matches("^\\d{5}?$") || !zip3.matches("^\\d{5}?$")) { if (zip2.length() == 0 && zip3.length() == 0) return "postCoupon"; else request.setAttribute( "flash", "Zipcode must be XXXXX or " + "XXXXX-XXXX format " + "or can be left blank"); request.setAttribute("zip2", zip2); request.setAttribute("zip3", zip3); return "postCoupon"; } if (couponValue == null || couponValue.length() < 1 || couponValue.length() > 10) { request.setAttribute("flash", "Value must be between 1-10 characters."); request.setAttribute("couponValue", couponValue); return "postCoupon"; } bizName = StringEscapeUtils.escapeHtml4(bizName); bizName = bizName.replace("'", "'"); bogoDesc = StringEscapeUtils.escapeHtml4(bogoDesc); bogoDesc = bogoDesc.replace("'", "'"); bizLoc = StringEscapeUtils.escapeHtml4(bizLoc); bizLoc = bizLoc.replace("'", "'"); BogoDAO db = (BogoDAO) this.getServletContext().getAttribute("db"); db.addCoupon(bizName, bogoDesc, bizLoc, couponValue, zip1, zip2, zip3); if (db.getLastError() != null) { request.setAttribute("flash", db.getLastError()); return "postCoupon"; } return "tyForPosting"; }
/** * Cuts off long queries. Actually they are restricted to 50 characters. The full query is * available with descriptions (tooltip in gui) * * @param text the query to display in the result view panel */ public void setInfo(String text) { if (text != null && text.length() > 0) { String prefix = "Result for: <span class=\"" + Helper.CORPUS_FONT_FORCE + "\">"; lblInfo.setDescription(prefix + text.replaceAll("\n", " ") + "</span>"); lblInfo.setValue( text.length() < 50 ? prefix + StringEscapeUtils.escapeHtml4(text.substring(0, text.length())) : prefix + StringEscapeUtils.escapeHtml4(text.substring(0, 50)) + " ... </span>"); } }
/** * Gets the map to represent a single milestone. * * @param m the milestone * @param projects the projects cache * @return the map representing a single milestone. */ private static Map<String, String> getMilestoneJsonData(Milestone m, Map<Long, String> projects) { Map<String, String> item = new HashMap<String, String>(); item.put("title", StringEscapeUtils.escapeHtml4(m.getName())); item.put("projectId", String.valueOf(m.getProjectId())); item.put("projectName", StringEscapeUtils.escapeHtml4(projects.get(m.getProjectId()))); item.put("description", StringEscapeUtils.escapeHtml4(m.getDescription())); item.put( "date", MILESTONE_DATE_FORMAT.format(m.isCompleted() ? m.getCompletionDate() : m.getDueDate())); return item; }
/** * Create a CharacteristicBean. * * @param conn A connection to the database. * @param num_samples The number of samples in the database. * @param value The value of this sample. * @return * @throws SQLException */ private static CharacteristicBean getCharacteristicBean( Connection conn, int num_samples, String dbname, String value) throws SQLException { CharacteristicBean chrbean = new CharacteristicBean(); PreparedStatement getCount; String querystr = "SELECT COUNT(*) FROM `Samples` WHERE `" + dbname + "`"; if (value != null) { chrbean.setValue(StringEscapeUtils.escapeHtml4(value)); querystr += " = ?;"; getCount = conn.prepareStatement(querystr); getCount.setString(1, value); } else { chrbean.setValue(NO_JAVASCRIPT); querystr += " IS NULL;"; getCount = conn.prepareStatement(querystr); } ResultSet rs = getCount.executeQuery(); rs.next(); int count = rs.getInt(1); rs.close(); chrbean.setInX(((double) num_samples) / ((double) count)); chrbean.setBits(Math.abs(Math.log(chrbean.getInX()) / Math.log(2))); return chrbean; }
@RequestMapping(value = "/profileedit", method = RequestMethod.POST) public View profileEditPost( @ModelAttribute("profile") ProfileVO profileVO, HttpSession httpSession, Model model) { String error = ""; User user = userDAO.findByUserId(profileVO.getUserId()); String email = profileVO.getEmail(); if (ValidatorUtil.isValidEmail(email)) { if (userDAO.findByEmail(email) == null) { user.setEmail(email); } else { error += "Email address " + StringEscapeUtils.escapeHtml4(email) + " is taken or unavailable<br/>"; } } else { error += "Email address " + StringEscapeUtils.escapeHtml4(email) + " is invalid<br/>"; } String newPassword = profileVO.getPassword(); String newPasswordConfirm = profileVO.getConfirmPassword(); if (ValidatorUtil.isNotNull(newPassword)) { if (newPassword.equals(newPasswordConfirm)) { try { user.setPassword(PasswordHash.createHash(newPassword)); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { _log.error(e); } } else { error += "Password Mismatch<br/>"; } } user.setMovieView(profileVO.isMovieView() ? 1 : 0); user.setMusicView(profileVO.isMusicView() ? 1 : 0); user.setConsoleView(profileVO.isConsoleView() ? 1 : 0); List<Integer> exCatIds = profileVO.getExCatIds(); // TODO update excats if (ValidatorUtil.isNull(error)) { userDAO.update(user); } httpSession.setAttribute("errors", error); return safeRedirect("/profileedit"); }
private String getPointsMsg(SubmissionResult result) { if (!result.getPoints().isEmpty()) { String msg = "Points permanently awarded: " + StringUtils.join(result.getPoints(), ", ") + "."; return "<html>" + StringEscapeUtils.escapeHtml4(msg).replace("\n", "<br />\n") + "</html>"; } else { return ""; } }
/** * gives an {@link OverpassPopup} of an {@link OverpassFeature}<br> * If it is not stored, it will be created automatically * * @since 0.0.1 * @param id the OpenStreetMap identifier to get the popup of * @param entityType the {@link EntityType} of the requested object * @return the {@link OverpassPopup} of the {@link Entity} with the identifier <code>id</code> */ public static OverpassPopup getPopup(long id, EntityType entityType) { PopupStore.clean(); if (!(PopupStore.expires.containsKey(id))) { String content; String entityTypeName = entityType.name().toLowerCase(); long delay; try { String query = "[out:popup];" + entityTypeName + "(" + id + ");out;"; content = IOUtils.toString( (new URL( "http://overpass-api.de/api/interpreter?data=" + URLEncoder.encode(query, "UTF-8"))) .openStream()); delay = PopupStore.try_again_delay; } catch (IOException e) { content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"; content += "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\r\n"; content += "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\r\n"; content += "<head>\r\n"; content += "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" lang=\"en\"/>\r\n"; content += "<title>Error on loading popup content!</title>\r\n"; content += "</head>\r\n"; content += "<body>\r\n"; content += "<p align=\"center\"><strong>Couldn't load popup content from Overpass API!</strong></p>\r\n"; content += "<p>The following exception occurred:<br />\r\n"; content += "<code><pre>" + StringEscapeUtils.escapeHtml4(ExceptionUtils.getStackTrace(e)) + "</pre></code>\r\n"; content += "</p>\r\n"; content += "<p style=\"font-size:smaller\">OpenStreetMap object: <a href=\"https://www.openstreetmap.org/" + entityTypeName + "/" + id + "\" target=\"_blank\">" + id + "</a></p>\r\n"; content += "</body>\r\n"; content += "</html>\r\n"; delay = PopupStore.expire_delay; } PopupStore.popups.put(id, new OverpassPopup(entityType, id, content)); PopupStore.expires.put(id, (new DateTime()).plus(delay)); } return PopupStore.popups.get(id); }
private void addResponseToList( EmoticonListResponse emoticonListResponse, final List<Emoticon> emoticons) { for (EmoticonListResponse.Item item : emoticonListResponse.getItems()) { final Emoticon newEmoticon = new Emoticon( StringEscapeUtils.escapeHtml4("(" + item.getShortcut() + ")"), item.getUrl()); emoticons.add(newEmoticon); } }
public String escapeHtml(String text) { String value = text; if (text == null) { return text; } else { value = StringEscapeUtils.escapeHtml3(value); value = StringEscapeUtils.escapeHtml4(value); } return value; }
@Override public String intercept(ActionInvocation invocation) throws Exception { // TODO Auto-generated method stub ActionContext actionContext = invocation.getInvocationContext(); Map<String, Object> map = actionContext.getParameters(); for (Map.Entry<String, Object> entry : map.entrySet()) { String value = ((String[]) (entry.getValue()))[0]; entry.setValue(StringEscapeUtils.escapeHtml4(value)); } return invocation.invoke(); }
@Override public String toHTML( Strings strings, Locale locale, String extension, String name, String value) { try { PropertyExtensionDescriptor descriptor = extensionManager.getPropertyExtensionDescriptor(extension, name); return descriptor.toHTML(strings, locale, value); } catch (PropertyExtensionNotFoundException e) { return StringEscapeUtils.escapeHtml4(value); } }
public static String getQueryParams(HttpServletRequest request, String[] queryParamsToIgnore) { String result = ""; for (Object key : request.getParameterMap().keySet()) { if (!Arrays.asList(queryParamsToIgnore).contains(key)) { if (StringUtils.isBlank(result)) { result = result + GET_VAR_SEPARATOR; } String[] value = request.getParameterValues((String) key); result = result + key + "=" + StringEscapeUtils.escapeHtml4(value[0]); } } return result; }
/** * Gets the roadmap calendar json data via ajax. * * @return the result code. * @throws Exception if there is any error. * @since 1.1 */ public String getRoadmapCalendar() throws Exception { Map<String, List<Map<String, String>>> result = new HashMap<String, List<Map<String, String>>>(); final Map<Long, String> projects = DataProvider.getEnterpriseDashboardFilteredProjects(getFormData()); viewData.setProjects(projects); getViewData().setResponsiblePersonIds(new HashSet<Long>()); final List<Milestone> milestones; if (projects == null || projects.size() == 0) { milestones = new ArrayList<Milestone>(); } else { milestones = getMilestoneService() .getAllForProjects( new ArrayList<Long>(projects.keySet()), ALL_MILESTONE_STATUS, SortOrder.ASCENDING); } // extra all the responsible person user id from the milestone for (Milestone m : milestones) { m.setName(StringEscapeUtils.escapeHtml4(StringEscapeUtils.escapeJson(m.getName()))); m.setDescription( StringEscapeUtils.escapeHtml4(StringEscapeUtils.escapeJson(m.getDescription()))); if (m.getOwners() != null && m.getOwners().size() > 0) { getViewData().getResponsiblePersonIds().add(m.getOwners().get(0).getUserId()); } } // set the milestones viewData.setMilestones(milestones); return SUCCESS; }
@Override public String format(LoggingEvent event) { String newMsg = StringEscapeUtils.escapeHtml4(event.getMessage().toString()); LoggingEvent encodedEvent = new LoggingEvent( event.fqnOfCategoryClass, event.getLogger(), event.timeStamp, event.level, newMsg, event.getThrowableInformation().getThrowable()); String baseFmt = super.format(encodedEvent).replace("@{{", "<").replace("@}}", ">"); return "<div class=step${event.level.toString()}>${baseFmt}</div><br/>"; }
public void buildFinished(IJavaProject project) { try { StringBuilder sb = new StringBuilder(); PreProcessing(project.getElementName()); IEclipsePreferences prefs = InstanceScope.INSTANCE.getNode(Constants.BUNDLE_NAME); String fileName = prefs.get("LTiEFileName", "Empty String") + project.getElementName() + ".MTD"; sb.append("<COMPILE_INSTANCE>"); Calendar c = Calendar.getInstance(); SimpleDateFormat format = new SimpleDateFormat("EEE, MMM d, yyyy 'at' HH:mm:ss z"); sb.append( "<TIME UTC=\"" + c.getTimeInMillis() + "\">" + format.format(c.getTime()) + "</TIME>"); IPackageFragment[] packages = project.getPackageFragments(); sb.append("<PACKAGES>"); for (IPackageFragment aPackage : packages) { if (aPackage.getKind() == IPackageFragmentRoot.K_SOURCE) { String packageName = aPackage.getElementName().isEmpty() ? "default" : aPackage.getElementName(); Constants.writer.println("Package Fragment Name: " + packageName); sb.append("<PACKAGE>"); sb.append("<NAME>" + packageName + "</NAME>"); sb.append("<FILES>"); for (ICompilationUnit unit : aPackage.getCompilationUnits()) { sb.append("<FILE>"); sb.append("<NAME>" + unit.getElementName() + "</NAME>"); printFileInternals(unit, sb); printFilesProblems(unit, sb); sb.append("<SOURCE>" + StringEscapeUtils.escapeHtml4(unit.getSource()) + "</SOURCE>"); sb.append("</FILE>"); } ProcessUMLFiles(aPackage.getNonJavaResources(), sb); sb.append("</FILES>"); sb.append("</PACKAGE>"); } } sb.append("</PACKAGES>"); Object[] nonJavaResources = project.getNonJavaResources(); if (nonJavaResources != null && nonJavaResources.length > 0) { sb.append("<FILES>"); ProcessUMLFiles(nonJavaResources, sb); sb.append("</FILES>"); } sb.append("</COMPILE_INSTANCE>"); PrintWriter out = new PrintWriter(new FileWriter(fileName, true)); out.write(XMLFormatter.format(sb.toString())); out.close(); } catch (Exception e) { e.printStackTrace(Constants.writer); } }
public static void add(String agent, Date sampleDate, String message) { if (log.isDebugEnabled()) { log.debug(String.format("FaultsDB.processItem(%s, %s, %s)", agent, sampleDate, message)); } try { String ins_sql = ("INSERT INTO fault_data (agent_name, event_time, message, short_message) VALUES (?, ?, ?, ?)"); ErrorInfo errorInfo = extractShortMessage(message); String escapedMsg = StringEscapeUtils.escapeHtml4(errorInfo.content.replace("\n", "\\n")); String shortMessage = StringEscapeUtils.escapeHtml4(errorInfo.shortMessage.replace("\n", "\\n")); /* TODO TEMP CHANGE brsantos */ // DbExecutor.runActionPreparedStatement(ins_sql, agent, sampleDate, escapedMsg, // shortMessage); } catch (Throwable t) { log.error("Failed to insert new information item.", t); } }
/** * @param request The request object providing information about the HTTP request * @param response The response object providing functionality for modifying the response * @return The content to be set in the response * @throws Exception implementation can choose to throw exception */ public String handleGetByTag(Request request, Response response) throws Exception { String username = sessionDAO.findUserNameBySessionId(request.cookie("session")); SimpleHash root = new SimpleHash(); String tag = StringEscapeUtils.escapeHtml4(request.params(":thetag")); List<Document> posts = blogPostDAO.findByTagDateDescending(tag); root.put("myposts", posts); if (username != null) { root.put("username", username); } return templateEngine.render(new ModelAndView(root, "blog_template.ftl")); }
public static ConfigurationObject mock() { List<Constraint> constraints = Lists.newArrayList(); Set<String> parameters = Sets.newHashSet(); for (int i = 0; i < 3; i++) { Constraint c = new Constraint(); c.setWebService("http://example.org/ws/" + i); Set<String> params = Sets.newHashSet(); for (int j = 0; j < 5; j++) { params.add("http://example.org/ws/" + i + "#p" + j); } c.setParameters(params); parameters.addAll(params); constraints.add(c); } List<Equivalence> equivalences = Lists.newArrayList(); for (String param : parameters) { Equivalence equivalence = new Equivalence(); equivalence.setParameter(param); HashSet<String> others = Sets.newHashSet(parameters); others.remove(param); equivalence.setEqParameters(others); equivalences.add(equivalence); } ConfigurationObject co = new ConfigurationObject(); co.setConstraints(constraints); co.setEquivalences(equivalences); StringBuilder builder = new StringBuilder(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(Mock.class.getClassLoader().getResourceAsStream("testms")))) { while (reader.ready()) { builder.append(reader.readLine()).append("\n"); } } catch (IOException e) { } co.setDatamodel(StringEscapeUtils.escapeHtml4(builder.toString())); return co; }
private void ProcessUMLFiles(Object[] packageFragments, StringBuilder sb) throws FileNotFoundException { for (Object obj : packageFragments) { if (obj instanceof File) { File file = (File) obj; if (file.getFileExtension().equals("uml")) { sb.append("<FILE>"); sb.append("<NAME>" + file.getName() + "</NAME>"); sb.append("<SOURCE>"); Scanner s = new Scanner(new FileInputStream(file.getRawLocation().toString())); s.useDelimiter("\\Z"); sb.append(StringEscapeUtils.escapeHtml4(s.next())); s.close(); sb.append("</SOURCE>"); sb.append("</FILE>"); } } } }
/* * type: title , content */ @RequestMapping(value = "/update/{docid}/{type}", method = RequestMethod.POST) @ResponseBody public String update( @PathVariable long docid, @RequestParam("post-text") String content, @PathVariable String type, HttpServletRequest request, HttpServletResponse response) throws Exception { String retValue = ""; // request.setCharacterEncoding("utf8"); // response.setCharacterEncoding("utf8"); // response.setContentType("application/json;charset=UTF-8"); HttpSession session = request.getSession(); User user = (User) session.getAttribute("loginuser"); if (user == null) { retValue = "{\"success\":\"false\",\"msg\":\"请登录。\"}"; return retValue; } // String content =post-text;// request.getParameter("post-text"); if (StringUtils.isEmpty(content)) { return retValue = "{\"success\":\"false\",\"msg\":\"提交内容不能为空。\"}"; } Map map = new HashMap(); map.put("docid", docid); if ("title".equals(type)) { map.put("title", StringEscapeUtils.escapeHtml4(content)); } else if ("content".equals(type)) { map.put("content", content); } try { docService.update(map); retValue = "{\"success\":\"true\",\"msg\":\"提交成功!\"}"; return retValue; } catch (Exception e) { log.error(e.getMessage()); retValue = "{\"success\":\"false\",\"msg\":\"保存失败,稍后再提交。\"}"; return retValue; } }
/** * Common method used to strip unwanted characters from form input strings * * @param inputStr * @return Returns the cleaned string */ protected String escapeFormInput(String inputStr) { return StringEscapeUtils.escapeHtml4(inputStr); }
/** Html 转码. */ public static String escapeHtml(String html) { return StringEscapeUtils.escapeHtml4(html); }
private String format(String theResultBody, EncodingEnum theEncodingEnum) { String str = StringEscapeUtils.escapeHtml4(theResultBody); if (str == null || theEncodingEnum == null) { return str; } StringBuilder b = new StringBuilder(); if (theEncodingEnum == EncodingEnum.JSON) { boolean inValue = false; boolean inQuote = false; for (int i = 0; i < str.length(); i++) { char prevChar = (i > 0) ? str.charAt(i - 1) : ' '; char nextChar = str.charAt(i); char nextChar2 = (i + 1) < str.length() ? str.charAt(i + 1) : ' '; char nextChar3 = (i + 2) < str.length() ? str.charAt(i + 2) : ' '; char nextChar4 = (i + 3) < str.length() ? str.charAt(i + 3) : ' '; char nextChar5 = (i + 4) < str.length() ? str.charAt(i + 4) : ' '; char nextChar6 = (i + 5) < str.length() ? str.charAt(i + 5) : ' '; if (inQuote) { b.append(nextChar); if (prevChar != '\\' && nextChar == '&' && nextChar2 == 'q' && nextChar3 == 'u' && nextChar4 == 'o' && nextChar5 == 't' && nextChar6 == ';') { b.append("quot;</span>"); i += 5; inQuote = false; } else if (nextChar == '\\' && nextChar2 == '"') { b.append("quot;</span>"); i += 5; inQuote = false; } } else { if (nextChar == ':') { inValue = true; b.append(nextChar); } else if (nextChar == '[' || nextChar == '{') { b.append("<span class='hlControl'>"); b.append(nextChar); b.append("</span>"); inValue = false; } else if (nextChar == '}' || nextChar == '}' || nextChar == ',') { b.append("<span class='hlControl'>"); b.append(nextChar); b.append("</span>"); inValue = false; } else if (nextChar == '&' && nextChar2 == 'q' && nextChar3 == 'u' && nextChar4 == 'o' && nextChar5 == 't' && nextChar6 == ';') { if (inValue) { b.append("<span class='hlQuot'>""); } else { b.append("<span class='hlTagName'>""); } inQuote = true; i += 5; } else if (nextChar == ':') { b.append("<span class='hlControl'>"); b.append(nextChar); b.append("</span>"); inValue = true; } else { b.append(nextChar); } } } } else { boolean inQuote = false; boolean inTag = false; for (int i = 0; i < str.length(); i++) { char nextChar = str.charAt(i); char nextChar2 = (i + 1) < str.length() ? str.charAt(i + 1) : ' '; char nextChar3 = (i + 2) < str.length() ? str.charAt(i + 2) : ' '; char nextChar4 = (i + 3) < str.length() ? str.charAt(i + 3) : ' '; char nextChar5 = (i + 4) < str.length() ? str.charAt(i + 4) : ' '; char nextChar6 = (i + 5) < str.length() ? str.charAt(i + 5) : ' '; if (inQuote) { b.append(nextChar); if (nextChar == '&' && nextChar2 == 'q' && nextChar3 == 'u' && nextChar4 == 'o' && nextChar5 == 't' && nextChar6 == ';') { b.append("quot;</span>"); i += 5; inQuote = false; } } else if (inTag) { if (nextChar == '&' && nextChar2 == 'g' && nextChar3 == 't' && nextChar4 == ';') { b.append("</span><span class='hlControl'>></span>"); inTag = false; i += 3; } else if (nextChar == ' ') { b.append("</span><span class='hlAttr'>"); b.append(nextChar); } else if (nextChar == '&' && nextChar2 == 'q' && nextChar3 == 'u' && nextChar4 == 'o' && nextChar5 == 't' && nextChar6 == ';') { b.append("<span class='hlQuot'>""); inQuote = true; i += 5; } else { b.append(nextChar); } } else { if (nextChar == '&' && nextChar2 == 'l' && nextChar3 == 't' && nextChar4 == ';') { b.append("<span class='hlControl'><</span><span class='hlTagName'>"); inTag = true; i += 3; } else { b.append(nextChar); } } } } return b.toString(); }
/** * Take in all the lists from the mapset and generate a JSON object array for each entry, to be * used by the search-selector widget * * @param pEvalNode Current ENI to get options from * @param pBaseURL Base URL of static servlet to replace %IMAGE_BASE% with in suggestion text * @return String of the JSON array to be set at the top of the page */ private String mapsetToJSON(EvaluatedNodeInfoItem pEvalNode, String pBaseURL) { JSONArray lMapsetJSON = new JSONArray(); JSONObject lMapsetObject = new JSONObject(); JSONObject lJSONEntry; int i = 1; for (FieldSelectOption lItem : filteredOptionList(pEvalNode)) { FieldSelectOption lSearchableItem = lItem; String lHiddenSearchable = lItem.getAdditionalProperty(HIDDEN_SEARCHABLE_MS_PROPERTY); String lSuggestion = lItem.getAdditionalProperty(SUGGESTION_DISPLAY_MS_PROPERTY); String lLevel = lItem.getAdditionalProperty(LEVEL_MS_PROPERTY); if ((pEvalNode.getFieldMgr().getVisibility() == NodeVisibility.VIEW && !lItem.isSelected())) { // Skip putting it in the JSON if it's got null entries or in read only mode and not // selected continue; } lJSONEntry = new JSONObject(); lJSONEntry.put("id", lSearchableItem.getExternalFieldValue()); lJSONEntry.put(KEY_JSON_PROPERTY, lSearchableItem.getDisplayKey()); lJSONEntry.put(SORT_JSON_PROPERTY, i++); // Add suggestion text (if none in mapset the JS will use the key safely escaped) if (!XFUtil.isNull(lSuggestion)) { lJSONEntry.put( SUGGESTION_DISPLAY_JSON_PROPERTY, StringEscapeUtils.escapeHtml4(lSuggestion.replaceAll("%IMAGE_BASE%", pBaseURL))); } lJSONEntry.put(HIDDEN_SEARCHABLE_JSON_PROPERTY, XFUtil.nvl(lHiddenSearchable, "")); // Add entry for hierarchical data if (lLevel != null) { lJSONEntry.put(LEVEL_JSON_PROPERTY, lLevel); } // If it was selected add that entry if (lSearchableItem.isSelected()) { lJSONEntry.put(SELECTED_JSON_PROPERTY, true); } // If it's a historical entry add that entry if (lSearchableItem.isHistorical()) { lJSONEntry.put(HISTORICAL_JSON_PROPERTY, true); lJSONEntry.put(SUGGESTABLE_JSON_PROPERTY, false); } else { lJSONEntry.put(SUGGESTABLE_JSON_PROPERTY, true); } if (lSearchableItem.getAdditionalProperty(OptionFieldMgr.FREE_TEXT_ADDITIONAL_PROPERTY) != null) { lJSONEntry.put(FREE_TEXT_JSON_PROPERTY, true); } lJSONEntry.put(DISABLED_JSON_PROPERTY, lSearchableItem.isDisabled()); lMapsetJSON.add(lJSONEntry); lMapsetObject.put(lSearchableItem.getExternalFieldValue(), lJSONEntry); } return lMapsetObject.toJSONString(); }
private void addAttributesToMap( HashMap<String, String> newAttributes, ArrayList<String> classes, Attr attribute, JadeModel model, JadeTemplate template) throws ExpressionException { String name = attribute.getName(); String key = name; boolean escaped = false; // if ("class".equals(key)) { // classes.push(attr.val); // classEscaping.push(attr.escaped); // } else if (isConstant(attr.val)) { // if (buffer) { // this.buffer(runtime.attr(key, toConstant(attr.val), escaped, this.terse)); // } else { // var val = toConstant(attr.val); // if (key === 'style') val = runtime.style(val); // if (escaped && !(key.indexOf('data') === 0 && typeof val !== 'string')) { // val = runtime.escape(val); // } // buf.push(utils.stringify(key) + ': ' + utils.stringify(val)); // } // } else { // if (buffer) { // this.bufferExpression('jade.attr("' + key + '", ' + attr.val + ', ' + // utils.stringify(escaped) + ', ' + utils.stringify(this.terse) + ')'); // } else { // var val = attr.val; // if (key === 'style') { // val = 'jade.style(' + val + ')'; // } // if (escaped && !(key.indexOf('data') === 0)) { // val = 'jade.escape(' + val + ')'; // } else if (escaped) { // val = '(typeof (jade_interp = ' + val + ') == "string" ? // jade.escape(jade_interp) : jade_interp)'; // } // buf.push(utils.stringify(key) + ': ' + val); // } // } String value = null; Object attributeValue = attribute.getValue(); if ("class".equals(key)) { if (attributeValue instanceof String) { escaped = attribute.isEscaped(); value = getInterpolatedAttributeValue(name, attributeValue, escaped, model, template); } else if (attributeValue instanceof ExpressionString) { escaped = ((ExpressionString) attributeValue).isEscape(); Object expressionValue = evaluateExpression( (ExpressionString) attributeValue, model, template.getExpressionHandler()); if (expressionValue != null && expressionValue.getClass().isArray()) { StringBuffer s = new StringBuffer(""); boolean first = true; if (expressionValue instanceof int[]) { for (int o : (int[]) expressionValue) { if (!first) s.append(" "); s.append(o); first = false; } } else { for (Object o : (Object[]) expressionValue) { if (!first) s.append(" "); s.append(o.toString()); first = false; } } value = s.toString(); } else if (expressionValue != null && expressionValue instanceof Boolean) { if ((Boolean) expressionValue) value = expressionValue.toString(); } else if (expressionValue != null) { value = expressionValue.toString(); } } if (!StringUtils.isBlank(value)) classes.add(value); return; // }else if("id".equals(key)){ // value = (String) attribute; } else if (attributeValue instanceof String) { escaped = attribute.isEscaped(); value = getInterpolatedAttributeValue(name, attributeValue, escaped, model, template); } else if (attributeValue instanceof Boolean) { if ((Boolean) attributeValue) { value = name; } else { return; } if (template.isTerse()) { value = null; } } else if (attributeValue instanceof ExpressionString) { escaped = ((ExpressionString) attributeValue).isEscape(); Object expressionValue = evaluateExpression( (ExpressionString) attributeValue, model, template.getExpressionHandler()); if (expressionValue == null) { return; } // TODO: refactor if (expressionValue instanceof Boolean) { if ((Boolean) expressionValue) { value = name; } else { return; } if (template.isTerse()) { value = null; } } else { value = expressionValue.toString(); value = StringEscapeUtils.escapeHtml4(value); } } else if (attributeValue instanceof String) { value = (String) attributeValue; // } else { // return ""; } newAttributes.put(name, value); }
/** * Establish optional search tagger widget parameters from optional search selector attributes * * @param pEvalNode Evaluated Node to get attribute values from * @return JSONObject with extra tagger parameters */ private JSONObject establishExtraParams(EvaluatedNodeInfo pEvalNode) { JSONObject lExtraParams = new JSONObject(); try { String lFieldSuggestionWidth = pEvalNode.getStringAttribute(NodeAttribute.SEARCH_SUGGESTION_WIDTH); if (lFieldSuggestionWidth != null) { lExtraParams.put("suggestWidth", Float.valueOf(lFieldSuggestionWidth) + "em"); } String lFieldSuggestionMaxWidth = pEvalNode.getStringAttribute(NodeAttribute.SEARCH_SUGGESTION_MAX_WIDTH); if (lFieldSuggestionMaxWidth != null) { lExtraParams.put("suggestMaxWidth", Float.valueOf(lFieldSuggestionMaxWidth) + "em"); } String lFieldSuggestionMaxHeight = pEvalNode.getStringAttribute(NodeAttribute.SEARCH_SUGGESTION_MAX_HEIGHT); if (lFieldSuggestionMaxHeight != null) { lExtraParams.put("suggestMaxHeight", Float.valueOf(lFieldSuggestionMaxHeight) + "em"); } String lPlaceholder = pEvalNode.getStringAttribute(NodeAttribute.PLACEHOLDER); if (lPlaceholder != null) { lExtraParams.put("placeholder", lPlaceholder); } String lSearchCharacterThreshold = pEvalNode.getStringAttribute(NodeAttribute.SEARCH_CHARACTER_THRESHOLD); if (lSearchCharacterThreshold != null) { lExtraParams.put("characterThreshold", Integer.valueOf(lSearchCharacterThreshold)); } if (pEvalNode.getMaxDataLength() != Integer.MAX_VALUE) { lExtraParams.put("characterLimit", Integer.valueOf(pEvalNode.getMaxDataLength())); } String lIndentMultiplier = pEvalNode.getStringAttribute(NodeAttribute.SEARCH_INDENT_MULTIPLIER); if (lIndentMultiplier != null) { lExtraParams.put("indentMultiplier", Float.valueOf(lIndentMultiplier)); } String lSearchTypingTimeout = pEvalNode.getStringAttribute(NodeAttribute.SEARCH_TYPING_TIMEOUT); if (lSearchTypingTimeout != null) { lExtraParams.put("typingTimeThreshold", Float.valueOf(lSearchTypingTimeout)); } if (pEvalNode.getBooleanAttribute(NodeAttribute.SEARCH_DISPLAY_HIERARCHY, false)) { lExtraParams.put("displayHierarchy", true); } if (pEvalNode.getBooleanAttribute(NodeAttribute.SEARCH_CASE_SENSITIVE, false)) { lExtraParams.put("caseSensitive", true); } if (pEvalNode.getBooleanAttribute(NodeAttribute.SEARCH_CLEAR_FILTER_ON_BLUR, true)) { lExtraParams.put("clearFilterOnBlur", true); } else { lExtraParams.put("clearFilterOnBlur", false); } if (pEvalNode.getBooleanAttribute(NodeAttribute.SEARCH_SORTED_OUTPUT, true)) { lExtraParams.put("sortedOutput", true); } else { lExtraParams.put("sortedOutput", false); } if (pEvalNode.getBooleanAttribute(NodeAttribute.SEARCH_MANDATORY_SELECTION, false)) { lExtraParams.put("mandatorySelection", true); } if (pEvalNode.getBooleanAttribute(NodeAttribute.SEARCH_FREE_TEXT_INPUT, false)) { lExtraParams.put("freeTextInput", true); lExtraParams.put( "freeTextPrefix", pEvalNode.getExternalFieldName() + "/" + FieldValueMapping.FREE_TEXT_PREFIX); StringAttributeResult lFreeTextMessage = pEvalNode.getStringAttributeResultOrNull(NodeAttribute.SEARCH_FREE_TEXT_INPUT_MESSAGE); if (lFreeTextMessage != null) { String lSafeMessage; if (lFreeTextMessage.isEscapingRequired()) { lSafeMessage = StringEscapeUtils.escapeHtml4(lFreeTextMessage.getString()); } else { lSafeMessage = lFreeTextMessage.getString(); } lExtraParams.put("freeTextMessage", lSafeMessage); } lExtraParams.put( "freeTextSuggest", pEvalNode.getBooleanAttribute(NodeAttribute.SEARCH_FREE_TEXT_SUGGEST, false)); } String lNoSuggestionsText = pEvalNode.getStringAttribute(NodeAttribute.SEARCH_NO_SUGGESTIONS_TEXT); if (lNoSuggestionsText != null) { lExtraParams.put("noSuggestText", lNoSuggestionsText); } String lEmptyListText = pEvalNode.getStringAttribute(NodeAttribute.SEARCH_EMPTY_SUGGESTIONS_TEXT); if (lEmptyListText != null) { lExtraParams.put("emptyListText", lEmptyListText); } String lLimitedText = pEvalNode.getStringAttribute(NodeAttribute.SEARCH_LIMITED_SUGGESTIONS_TEXT); if (lLimitedText != null) { lExtraParams.put("limitedText", lLimitedText); } } catch (NumberFormatException ex) { throw new ExInternal( "Failed to convert XPath result to Float for search-selector attributes", ex); } return lExtraParams; }
/** * Adds the other hipchat emoticons, such as ;), ;-), etc * * @param result */ private void addOtherHipchatEmoticons(List<Emoticon> result) { result.add( new Emoticon( StringEscapeUtils.escapeHtml4("(zzz)"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/zzz.gif")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4("8)"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/cool.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4("8-)"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/cool.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4(":#"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/footinmouth.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4(":$"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/moneymouth.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4(":'("), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/cry.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4(":')"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/happytear.gif")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4(":("), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/frown.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4(":)"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/smile.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4(":-)"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/smile.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4(":-*"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/kiss.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4(":D"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/bigsmile.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4(":-D"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/bigsmile.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4(":Z"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/sealed.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4(":\\"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/slant.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4(":o"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/gasp.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4(":p"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/tongue.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4(":|"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/straightface.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4(":-|"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/straightface.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4(";)"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/wink.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4(";-)"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/wink.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4(";p"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/winktongue.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4(">:-("), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/angry.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4("O:)"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/innocent.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4("(embarrassed)"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/embarrassed.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4("(oops)"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/oops.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4("(thumbsup)"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/thumbs_up.png")); result.add( new Emoticon( StringEscapeUtils.escapeHtml4("(thumbsdown)"), "https://dujrsrsgsd3nh.cloudfront.net/img/emoticons/thumbs_down.png")); }