public static String encodeURIinUTF8(String uri) { if (uri.startsWith("<http://dbpedia.org/resource/")) { int splitPoint = uri.lastIndexOf("/")+1; String infix = uri.substring(splitPoint, uri.length()-1); if (infix.contains("%")) { return uri; } try { infix = infix.replace("\\\\", "\\"); infix = StringEscapeUtils.unescapeJava(infix); infix = URLEncoder.encode(infix, "UTF-8"); } catch (UnsupportedEncodingException ex) { System.err.println("Encoding exception: "+ex); } uri = uri.substring(0, splitPoint) + infix + ">"; } return uri; }
/** * 缩略字符串(不区分中英文字符) * * @param str 目标字符串 * @param length 截取长度 * @return */ public static String abbr(String str, int length) { if (str == null) { return ""; } try { StringBuilder sb = new StringBuilder(); int currentLength = 0; for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) { currentLength += String.valueOf(c).getBytes("GBK").length; if (currentLength <= length - 3) { sb.append(c); } else { sb.append("..."); break; } } return sb.toString(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return ""; }
/** * doPost method to handle operations: like review, save hotel, check Expedia link. * * @param request * @param response * @throws IOException */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { List<String> types = getTypes(); String type = StringEscapeUtils.escapeHtml4(request.getParameter("type")); String id = StringEscapeUtils.escapeHtml4(request.getParameter("id")); String username = getUsername(request); PrintWriter out = response.getWriter(); if (username != null && types.contains(type)) { try { out.println(dbhandler.setLike(type, id, username)); } catch (SQLException e) { System.out.println(e); } } }
private String convertMessage(String message, Map<String, String> headers) { String newMessage = message; JsonElement msgRootElement = parser.parse(message); if (msgRootElement instanceof JsonObject) { JsonObject msgRoot = (JsonObject)msgRootElement; JsonElement element = msgRoot.get(PAYLOAD_ELEMENT_KEY); if (element != null) { if (!element.isJsonObject()) { //convert payLoad to a json object if it is not already msgRoot.remove(PAYLOAD_ELEMENT_KEY); String realPayload = element.getAsString(); String escapedPayload = StringEscapeUtils.unescapeJava(realPayload); msgRoot.add(PAYLOAD_ELEMENT_KEY, parser.parse(escapedPayload)); } } JsonElement hdrElement = GSON.toJsonTree(headers); msgRoot.add("msgHeaders", hdrElement); newMessage = GSON.toJson(msgRoot); if (logger.isDebugEnabled()) { logger.debug("message to be indexed " + newMessage); } } return newMessage; }
public static String annotationToJson(SpanAnnotation annotation) { StringBuilder sb = new StringBuilder("{\n"); sb.append("name : '").append(annotation.getName()).append("',\n"); sb.append("startToken : sentence[").append(annotation.getStartTokenIndex()).append("],\n"); sb.append("endToken : sentence[").append(annotation.getEndTokenIndex()).append("]\n"); if (annotation.getFeatures().size() > 0) { sb.append(",features:{"); for (Map.Entry<String, String> entry : annotation.getFeatures().entrySet()) { sb.append("\"").append(StringEscapeUtils.escapeEcmaScript(entry.getKey())).append("\" : \"").append(StringEscapeUtils.escapeEcmaScript(entry.getValue())).append("\",\n"); } sb.delete(sb.length() - 2, sb.length()); sb.append("}"); } sb.append("}"); return sb.toString(); }
/** * Prepares the description of bug body. By adding build url, a nice header, a note and * excaptes html tags, json tags. * * @param description * @return */ private String prepareBugDescriptionForBugCreation(String description) { description = "*[Automation failed tests]*\n" + "||Testcase failing|| Parameters||\n" + description + "\n" + System.getProperty(AUTO_CREATE_ADDITIONAL_DETAILS, configuration.getProperty(AUTO_CREATE_ADDITIONAL_DETAILS, "")) + "\n" + "Build url: " + buildUrl; description = description + "\n\n\n" + "Note: This bug is created automatically by DolphinNG." + " Please do not edit summary line of the bug."; description = StringEscapeUtils.escapeHtml3(description); description = StringEscapeUtils.escapeHtml4(description); description = JSONObject.escape(description); return description; }
public String findCrumb(List<String> lines) { String crumb = ""; String rtn = ""; for (String l : lines) { if (l.indexOf("CrumbStore") > -1) { rtn = l; break; } } // ,"CrumbStore":{"crumb":"OKSUqghoLs8" if (rtn != null && !rtn.isEmpty()) { String[] vals = rtn.split(":"); // get third item crumb = vals[2].replace("\"", ""); // strip quotes crumb = StringEscapeUtils.unescapeJava(crumb); // unescape escaped values (particularly, \u002f } return crumb; }
/** * doPost method to display "who liked this review" modal data. * * @param request * @param response * @throws IOException */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { String type = StringEscapeUtils.escapeHtml4(request.getParameter("type")); String id = StringEscapeUtils.escapeHtml4(request.getParameter("id")); PrintWriter out = response.getWriter(); if (getUsername(request) != null) { try { if (type.equals("review")) { out.println(showReviewLikes(id)); } } catch (SQLException e){ System.out.println(e); } } }
/** * doGet method to display the body and footer of review modal. * * @param request * @param response * @throws IOException */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String type = StringEscapeUtils.escapeHtml4(request.getParameter("type")); String id = StringEscapeUtils.escapeHtml4(request.getParameter("id")); StringBuilder sb = new StringBuilder(); PrintWriter out = response.getWriter(); if (getUsername(request) != null) { try { sb.append(body(id, type)); sb.append(footer(type)); out.println(sb.toString()); } catch (SQLException e) { System.out.println(e); } } }
/** * Displays a review apply. * * @param model * @param id * @return * @throws ShepherException */ @RequestMapping(value = "reviews/{id}", method = RequestMethod.GET) public String review(Model model, @PathVariable(value = "id") long id) throws ShepherException { ReviewRequest reviewRequest = reviewService.get(id); if (reviewRequest == null) { throw ShepherException.createNoSuchReviewException(); } reviewService.rejectIfExpired(reviewRequest); model.addAttribute("clusters", ClusterUtil.getClusters()); model.addAttribute("cluster", reviewRequest.getCluster()); model.addAttribute("paths", reviewRequest.getPath().split("/")); model.addAttribute("reviewRequest", reviewRequest); model.addAttribute("content", StringEscapeUtils.escapeHtml4(reviewRequest.getSnapshotContent())); model.addAttribute("newContent", StringEscapeUtils.escapeHtml4(reviewRequest.getNewSnapshotContent())); String backPath = reviewRequest.getPath(); if (reviewRequest.getAction() == Action.DELETE.getValue()) { backPath = ParentPathParser.getParent(backPath); } model.addAttribute("backPath", backPath); model.addAttribute("canReview", permissionService.isPathMaster(userHolder.getUser().getName(), reviewRequest.getCluster(), reviewRequest.getPath())); return "review/review"; }
public String getClassInitBodyUnescaped(){ if(classInitBody==null) return null; Pattern pattern = Pattern.compile("\\t+"); Matcher matcher = pattern.matcher(StringEscapeUtils.unescapeJava(this.classInitBody)); StringBuilder sb=new StringBuilder(StringEscapeUtils.unescapeJava(this.classInitBody)); while(matcher.find()){ sb.insert(matcher.start(), CodeStringBuilder.getTabString()); } String tempString=sb.toString(); pattern=Pattern.compile("\\n+"); matcher=pattern.matcher(tempString); while(matcher.find()){ sb.insert(matcher.end(), CodeStringBuilder.getTabString()); } return sb.toString(); }
protected File getLastPatchFile(String baseApkVersion, String productName, File outPatchDir) throws IOException { try { String httpUrl = ((TpatchInput)input).LAST_PATCH_URL + "baseVersion=" + baseApkVersion + "&productIdentifier=" + productName; String response = HttpClientUtils.getUrl(httpUrl); if (StringUtils.isBlank(response) || response.equals("\"\"")) { return null; } File downLoadFolder = new File(outPatchDir, "LastPatch"); downLoadFolder.mkdirs(); File downLoadFile = new File(downLoadFolder, "lastpatch.tpatch"); String downLoadUrl = StringEscapeUtils.unescapeJava(response); downloadTPath(downLoadUrl.substring(1, downLoadUrl.length() - 1), downLoadFile); return downLoadFile; } catch (Exception e) { return null; } }
@Override public void apply(ApiRequest request, ApiResponse response, WebSocketSession session) { String msg = StringEscapeUtils.escapeHtml4(request.getMsg()); if (StringUtils.isBlank(msg)) { return; } Map<String, Object> attributes = session.getAttributes(); String id = session.getId(); DrawPlayerInfo info = ((DrawPlayerInfo) attributes.get("info")); DrawGuessContext ctx = (DrawGuessContext) attributes.get("ctx"); DrawGameStatus status = ctx.status(); ArrayList<String> msgs = new ArrayList<>(2); if (status == DrawGameStatus.RUN) { if (StringUtils.equals(id, ctx.getCurrentUser())) { protectSecret(info, ctx, msg, msgs); } else { processGussPerson(info, ctx, msg, msgs); } } else { msgs.add("<b>" + info.getName() + "</b>: " + msg); } response.setCode(DrawCode.DRAW_MSG.getCode()).setData(msgs); }
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) { if (exception instanceof FlowExecutionRepositoryException && !(exception instanceof BadlyFormattedFlowExecutionKeyException)) { String urlToRedirectTo = request.getRequestURI() + (request.getQueryString() != null ? '?' + request.getQueryString() : ""); log.debug("Error getting flow information for URL [{}]", urlToRedirectTo, exception); Map<String, Object> model = new HashMap(); model.put(this.modelKey, StringEscapeUtils.escapeHtml4(exception.getMessage())); return new ModelAndView(new RedirectView(urlToRedirectTo), model); } else if (exception instanceof AbstractFlowExecutionException) { if (log.isDebugEnabled()) { log.error("Flow execution error", exception); } else { log.error("Flow execution error: {}", exception.getMessage()); } return ((AbstractFlowExecutionException) exception).getModelAndView(); } else { log.debug("Ignoring the received exception due to a type mismatch", exception); return null; } }
/** * doGet method to display attractions table in Hotels page. * * @param request * @param response * @throws IOException */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String hotelId = StringEscapeUtils.escapeHtml4(request.getParameter("hotelId")); StringBuilder sb = new StringBuilder(); HttpSession session = request.getSession(); PrintWriter out = response.getWriter(); if (getUsername(request) != null) { checkDataSession(session); DataSession ds = (DataSession) session.getAttribute(NAME); setDataSession(request, ds); try { checkTAFinder(hotelId, ds); sb.append(head(ds)); sb.append(body(ds)); out.println(sb.toString()); } catch (SQLException e) { System.out.println(e); } } }
private static List<Document> extractDocuments(Pair<SyndFeed, List<SyndEntry>> feedEntry) { List<Document> ret = new ArrayList<>(); feedEntry.getRight().forEach(e -> { FeedUtils.mergeAuthors(e); String description = e.getDescription() != null ? FeedUtils.clean(e.getDescription().getValue()) : StringUtils.EMPTY; if (description.length() > FeedConstants.MAX_DESCRIP_LEN) { description = FeedUtils.truncate(description, FeedConstants.MAX_DESCRIP_LEN); } ret.add(Document.of( StringEscapeUtils.unescapeHtml4(e.getTitle()), e.getPublishedDate(), e.getAuthors(), description, e.getLink(), feedEntry.getLeft().getTitle() )); }); return ret; }
/** * 编辑爬虫模板 * * @param jsonSpiderInfo json格式的爬虫模板 * @return */ @RequestMapping(value = "editSpiderInfo", method = {RequestMethod.POST, RequestMethod.GET}) public ModelAndView editSpiderInfo(String jsonSpiderInfo) { ModelAndView modelAndView = new ModelAndView("panel/commons/editSpiderInfo"); if (StringUtils.isNotBlank(jsonSpiderInfo)) { SpiderInfo spiderInfo = gson.fromJson(jsonSpiderInfo, SpiderInfo.class); //对可能含有html的字段进行转义 spiderInfo.setPublishTimeReg(StringEscapeUtils.escapeHtml4(spiderInfo.getPublishTimeReg())); spiderInfo.setCategoryReg(StringEscapeUtils.escapeHtml4(spiderInfo.getCategoryReg())); spiderInfo.setContentReg(StringEscapeUtils.escapeHtml4(spiderInfo.getContentReg())); spiderInfo.setTitleReg(StringEscapeUtils.escapeHtml4(spiderInfo.getTitleReg())); spiderInfo.setPublishTimeXPath(StringEscapeUtils.escapeHtml4(spiderInfo.getPublishTimeXPath())); spiderInfo.setCategoryXPath(StringEscapeUtils.escapeHtml4(spiderInfo.getCategoryXPath())); spiderInfo.setContentXPath(StringEscapeUtils.escapeHtml4(spiderInfo.getContentXPath())); spiderInfo.setTitleXPath(StringEscapeUtils.escapeHtml4(spiderInfo.getTitleXPath())); for (SpiderInfo.FieldConfig config : spiderInfo.getDynamicFields()) { config.setRegex(StringEscapeUtils.escapeHtml4(config.getRegex())); config.setXpath(StringEscapeUtils.escapeHtml4(config.getXpath())); } modelAndView.addObject("spiderInfo", spiderInfo); modelAndView.addObject("jsonSpiderInfo", jsonSpiderInfo); } else { modelAndView.addObject("spiderInfo", new SpiderInfo()); } return modelAndView; }
/** * 编辑爬虫模板 * * @param spiderInfoId 爬虫模板id * @return */ @RequestMapping(value = "editSpiderInfoById", method = {RequestMethod.POST, RequestMethod.GET}) public ModelAndView editSpiderInfoById(String spiderInfoId) { ModelAndView modelAndView = new ModelAndView("panel/commons/editSpiderInfo"); SpiderInfo spiderInfo = spiderInfoService.getById(spiderInfoId).getResult(); //对可能含有html的字段进行转义 spiderInfo.setPublishTimeReg(StringEscapeUtils.escapeHtml4(spiderInfo.getPublishTimeReg())); spiderInfo.setCategoryReg(StringEscapeUtils.escapeHtml4(spiderInfo.getCategoryReg())); spiderInfo.setContentReg(StringEscapeUtils.escapeHtml4(spiderInfo.getContentReg())); spiderInfo.setTitleReg(StringEscapeUtils.escapeHtml4(spiderInfo.getTitleReg())); spiderInfo.setPublishTimeXPath(StringEscapeUtils.escapeHtml4(spiderInfo.getPublishTimeXPath())); spiderInfo.setCategoryXPath(StringEscapeUtils.escapeHtml4(spiderInfo.getCategoryXPath())); spiderInfo.setContentXPath(StringEscapeUtils.escapeHtml4(spiderInfo.getContentXPath())); spiderInfo.setTitleXPath(StringEscapeUtils.escapeHtml4(spiderInfo.getTitleXPath())); for (SpiderInfo.FieldConfig config : spiderInfo.getDynamicFields()) { config.setRegex(StringEscapeUtils.escapeHtml4(config.getRegex())); config.setXpath(StringEscapeUtils.escapeHtml4(config.getXpath())); } modelAndView.addObject("spiderInfo", spiderInfo); modelAndView.addObject("jsonSpiderInfo", gson.toJson(spiderInfo)); return modelAndView; }
/** * Creates a new chat instance. * * @return The unique id that identifies the created instance */ public String createInstance() { final String query = this.mServiceUrl + CREATE_REQUEST; try { final List<String> content = getWebContent(query); // If the answer is empty there was some error if (content.isEmpty()) { return null; } // The first line contains the id final String firstLine = content.iterator().next(); if (firstLine.trim().isEmpty()) { return null; } return StringEscapeUtils.unescapeHtml4(firstLine); } catch (final IOException e) { // Ignore the exception and return null return null; } }
/** * Gets the last answer of the chat bot for the instance with the given id. * * @param id * The id of the instance * @return The last answer of the chat bot for the given instance or * <tt>null</tt> if there was no or the server experienced an error */ public String getLastMessage(final String id) { final String query = this.mServiceUrl + GET_MESSAGE_REQUEST + ID_PARAMETER + id; try { final List<String> content = getWebContent(query); // If the answer is empty there was some error if (content.isEmpty()) { return null; } // The first line contains the message final String firstLine = content.iterator().next(); if (firstLine.trim().isEmpty()) { return null; } return StringEscapeUtils.unescapeHtml4(firstLine); } catch (final IOException e) { // Ignore the exception and return null return null; } }
@Override public ModelAndView resolveException(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception exception) { /* * Since FlowExecutionRepositoryException is a common ancestor to these exceptions and other * error cases we would likely want to hide from the user, it seems reasonable to check for * FlowExecutionRepositoryException. * * BadlyFormattedFlowExecutionKeyException is specifically ignored by this handler * because redirecting to the requested URI with this exception may cause an infinite * redirect loop (i.e. when invalid "execution" parameter exists as part of the query string */ if (!(exception instanceof FlowExecutionRepositoryException) || exception instanceof BadlyFormattedFlowExecutionKeyException) { logger.debug("Ignoring the received exception due to a type mismatch", exception); return null; } final String urlToRedirectTo = request.getRequestURI() + (request.getQueryString() != null ? '?' + request.getQueryString() : ""); logger.debug("Error getting flow information for URL [{}]", urlToRedirectTo, exception); final Map<String, Object> model = new HashMap<>(); model.put(this.modelKey, StringEscapeUtils.escapeHtml4(exception.getMessage())); return new ModelAndView(new RedirectView(urlToRedirectTo), model); }
/** * Handle request. * * @param request the request * @param response the response * @return the model and view * @throws Exception the exception */ @RequestMapping(method = RequestMethod.GET) protected ModelAndView handleRequestInternal( final HttpServletRequest request, final HttpServletResponse response) throws Exception { final Map<String, Object> list = getBeans(this.applicationContext); LOGGER.debug("Found [{}] beans to report", list.size()); final JsonSerializer<Object> serializer = new BeanObjectJsonSerializer(); final StringBuilder builder = new StringBuilder(); builder.append('['); final Set<Map.Entry<String, Object>> entries = list.entrySet(); final Iterator<Map.Entry<String, Object>> it = entries.iterator(); while (it.hasNext()) { final Map.Entry<String, Object> entry = it.next(); final Object obj = entry.getValue(); final StringWriter writer = new StringWriter(); writer.append('{'); writer.append('\"' + entry.getKey() + "\":"); serializer.toJson(writer, obj); writer.append('}'); builder.append(writer); if (it.hasNext()) { builder.append(','); } } builder.append(']'); final ModelAndView mv = new ModelAndView(VIEW_CONFIG); final String jsonData = StringEscapeUtils.escapeJson(builder.toString()); mv.addObject("jsonData", jsonData); mv.addObject("properties", casProperties.entrySet()); return mv; }
/** * Generate error view based on {@link #setFailureView(String)}. * * @param code the code * @param args the args * @return the model and view */ private ModelAndView generateErrorView(final String code, final Object[] args) { final ModelAndView modelAndView = new ModelAndView(this.failureView); final String convertedDescription = getMessageSourceAccessor().getMessage(code, args, code); modelAndView.addObject("code", StringEscapeUtils.escapeHtml4(code)); modelAndView.addObject("description", StringEscapeUtils.escapeHtml4(convertedDescription)); return modelAndView; }
/** * Pretifies the function initialization body of the function, by adding appropriate number of tabs * @return Pretified code */ public String getFunctionInitBodyUnescaped(){ if(functionInitBody==null) return null; Pattern pattern = Pattern.compile("\\t+"); Matcher matcher = pattern.matcher(StringEscapeUtils.unescapeJava(this.functionInitBody)); StringBuilder sb=new StringBuilder(StringEscapeUtils.unescapeJava(this.functionInitBody)); while(matcher.find()){ sb.insert(matcher.start(), CodeStringBuilder.getTabString()); } return StringEscapeUtils.unescapeJava(sb.toString()); }
@Override public ModelAndView resolveException(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception exception) { /* * Since FlowExecutionRepositoryException is a common ancestor to these exceptions and other * error cases we would likely want to hide from the user, it seems reasonable to check for * FlowExecutionRepositoryException. * * BadlyFormattedFlowExecutionKeyException is specifically ignored by this handler * because redirecting to the requested URI with this exception may cause an infinite * redirect loop (i.e. when invalid "execution" parameter exists as part of the query string */ if (!(exception instanceof FlowExecutionRepositoryException) || exception instanceof BadlyFormattedFlowExecutionKeyException) { LOGGER.debug("Ignoring the received exception due to a type mismatch", exception); return null; } final String urlToRedirectTo = request.getRequestURI() + (request.getQueryString() != null ? '?' + request.getQueryString() : StringUtils.EMPTY); LOGGER.debug("Error getting flow information for URL [{}]", urlToRedirectTo, exception); final Map<String, Object> model = new HashMap<>(); model.put(this.modelKey, StringEscapeUtils.escapeHtml4(exception.getMessage())); return new ModelAndView(new RedirectView(urlToRedirectTo), model); }
/** * Put cas response attributes into model. * * @param model the model * @param attributes the attributes * @param registeredService the registered service */ protected void putCasResponseAttributesIntoModel(final Map<String, Object> model, final Map<String, Object> attributes, final RegisteredService registeredService) { LOGGER.debug("Beginning to encode attributes for the response"); final Map<String, Object> encodedAttributes = this.protocolAttributeEncoder.encodeAttributes(attributes, registeredService); LOGGER.debug("Encoded attributes for the response are [{}]", encodedAttributes); super.putIntoModel(model, CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_ATTRIBUTES, encodedAttributes); final List<String> formattedAttributes = new ArrayList<>(encodedAttributes.size()); LOGGER.debug("Beginning to format/render attributes for the response"); encodedAttributes.forEach((k, v) -> { final Set<Object> values = CollectionUtils.toCollection(v); values.forEach(value -> { final String fmt = new StringBuilder() .append("<cas:".concat(k).concat(">")) .append(StringEscapeUtils.escapeXml10(value.toString().trim())) .append("</cas:".concat(k).concat(">")) .toString(); LOGGER.debug("Formatted attribute for the response: [{}]", fmt); formattedAttributes.add(fmt); }); }); super.putIntoModel(model, CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_FORMATTED_ATTRIBUTES, formattedAttributes); }
/** * Generate error view. * * @param code the code * @param args the args * @param request the request * @return the model and view */ private ModelAndView generateErrorView(final String code, final Object[] args, final HttpServletRequest request, final WebApplicationService service) { final ModelAndView modelAndView = getModelAndView(request, false, service); final String convertedDescription = this.applicationContext.getMessage(code, args, code, request.getLocale()); modelAndView.addObject(CasViewConstants.MODEL_ATTRIBUTE_NAME_ERROR_CODE, StringEscapeUtils.escapeHtml4(code)); modelAndView.addObject(CasViewConstants.MODEL_ATTRIBUTE_NAME_ERROR_DESCRIPTION, StringEscapeUtils.escapeHtml4(convertedDescription)); return modelAndView; }
public static boolean joinServer(MCLeaksSession session, String serverHash, String server) { if (session != null) { try { String url = ENDPOINT + "joinserver"; String payload = "{\"session\":\"" + session.getSession() + "\",\"mcname\":\"" + session.getMcname() + "\",\"serverhash\":\"" + serverHash + "\",\"server\":\"" + server + "\"}"; WebUtils.post(url, StringEscapeUtils.unescapeJava(payload)); return true; } catch (Exception ex) { ; } } return false; }
private Entry getEntry(final boolean hasMultipleUsers, String authorName, final JSONArray articles, final boolean isFullContent, int i) throws org.json.JSONException, org.b3log.solo.service.ServiceException { final JSONObject article = articles.getJSONObject(i); final Entry ret = new Entry(); final String title = StringEscapeUtils.escapeXml(article.getString(Article.ARTICLE_TITLE)); ret.setTitle(title); final String summary = isFullContent ? StringEscapeUtils.escapeXml(article.getString(Article.ARTICLE_CONTENT)) : StringEscapeUtils.escapeXml(article.optString(Article.ARTICLE_ABSTRACT)); ret.setSummary(summary); final Date updated = (Date) article.get(Article.ARTICLE_UPDATE_DATE); ret.setUpdated(updated); final String link = Latkes.getServePath() + article.getString(Article.ARTICLE_PERMALINK); ret.setLink(link); ret.setId(link); if (hasMultipleUsers) { authorName = StringEscapeUtils.escapeXml(articleQueryService.getAuthor(article).getString(User.USER_NAME)); } ret.setAuthor(authorName); final String tagsString = article.getString(Article.ARTICLE_TAGS_REF); final String[] tagStrings = tagsString.split(","); for (final String tagString : tagStrings) { final Category catetory = new Category(); ret.addCatetory(catetory); final String tag = tagString; catetory.setTerm(tag); } return ret; }
/** * doPost method to display user's data in MyPage, five rows of data per request. * * @param request * @param response * @throws IOException */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { Map<String, List<String>> types = getTypesMap(); String type = StringEscapeUtils.escapeHtml4(request.getParameter("type")); int finish = Integer.parseInt(request.getParameter("finish")); String username = getUsername(request); if (username != null && types.containsKey(type) && finish == 0) { try (ResultSet result = dbhandler.getMyData(types.get(type), username)) { StringBuilder sb = new StringBuilder(); PrintWriter out = response.getWriter(); int data = Integer.parseInt(request.getParameter("data")); int count = 0, display = 0; while (result.next()) { count++; if (count > data && display < 5) { display++; sb.append("<tr><td name=\"" + type + "Data\" onclick=\"" + getFunction(type, result) + "\">"); sb.append(result.getString(types.get(type).get(3))); sb.append("</td></tr>"); } } if (count == 0) { sb.append("<tr><td name=\"" + type + "Finish\">No result.</td></tr>"); } else if (count == data + display) { sb.append("<tr hidden><td name=\"" + type + "Finish\"></td></tr>"); } out.println(sb.toString()); } catch (SQLException e) { System.out.println(e); } } }
/** * Builds categories (array of category info structs) with the specified * preference. * * @return blog info XML * @throws Exception * exception */ private String buildCategories() throws Exception { final StringBuilder stringBuilder = new StringBuilder(); final List<JSONObject> tags = tagQueryService.getTags(); for (final JSONObject tag : tags) { final String tagTitle = StringEscapeUtils.escapeXml(tag.getString(Tag.TAG_TITLE)); final String tagId = tag.getString(Keys.OBJECT_ID); stringBuilder.append("<value><struct>"); stringBuilder.append("<member><name>description</name>").append("<value>").append(tagTitle) .append("</value></member>"); stringBuilder.append("<member><name>title</name>").append("<value>").append(tagTitle) .append("</value></member>"); stringBuilder.append("<member><name>categoryid</name>").append("<value>").append(tagId) .append("</value></member>"); stringBuilder.append("<member><name>htmlUrl</name>").append("<value>").append(Latkes.getServePath()) .append("/tags/").append(tagTitle).append("</value></member>"); stringBuilder.append("<member><name>rsslUrl</name>").append("<value>").append(Latkes.getServePath()) .append("/tag-articles-rss.do?oId=").append(tagId).append("</value></member>"); stringBuilder.append("</struct></value>"); } return stringBuilder.toString(); }
/** * Builds blog info struct with the specified preference. * * @param preference * the specified preference * @return blog info XML * @throws JSONException * json exception */ private String buildBlogInfo(final JSONObject preference) throws JSONException { final String blogId = preference.getString(Keys.OBJECT_ID); final String blogTitle = StringEscapeUtils.escapeXml(preference.getString(Option.ID_C_BLOG_TITLE)); final StringBuilder stringBuilder = new StringBuilder("<member><name>blogid</name><value>").append(blogId) .append("</value></member>"); stringBuilder.append("<member><name>url</name><value>").append(Latkes.getServePath()) .append("</value></member>"); stringBuilder.append("<member><name>blogName</name><value>").append(blogTitle).append("</value></member>"); return stringBuilder.toString(); }
private static Type tryToGetValidType(FreeVariable freeVariable, Map<String, Type> typesByName) throws InvalidFreeVariableProblem { Type foundType = typesByName.get(freeVariable.getType()); if (foundType == null) { throw new InvalidFreeVariableProblem( "Variable has unknown type: " + StringEscapeUtils .escapeJava(freeVariable.getType())); } return foundType; }
@Override public ObjectNode encode(Application app, CodecContext context) { checkNotNull(app, "Application cannot be null"); ApplicationService service = context.getService(ApplicationService.class); ArrayNode permissions = context.mapper().createArrayNode(); ArrayNode features = context.mapper().createArrayNode(); ArrayNode requiredApps = context.mapper().createArrayNode(); app.permissions().forEach(p -> permissions.add(p.toString())); app.features().forEach(f -> features.add(f)); app.requiredApps().forEach(a -> requiredApps.add(a)); ObjectNode result = context.mapper().createObjectNode() .put("name", app.id().name()) .put("id", app.id().id()) .put("version", app.version().toString()) .put("category", app.category()) .put("description", StringEscapeUtils.escapeJson(app.description())) .put("readme", StringEscapeUtils.escapeJson(app.readme())) .put("origin", app.origin()) .put("url", app.url()) .put("featuresRepo", app.featuresRepo().map(URI::toString).orElse("")) .put("state", service.getState(app.id()).toString()); result.set("features", features); result.set("permissions", permissions); result.set("requiredApps", requiredApps); return result; }
/** * Xml 转码. */ public static String escapeXml(String xml) { return StringEscapeUtils.escapeXml10(xml); }
/** * * @param columnName * @return the normalised string */ public static String normaliseHeader(String columnName) { columnName = StringEscapeUtils.unescapeJava(columnName); columnName = columnName.replace("\"", ""); columnName = columnName.replace("|", " "); columnName = columnName.replace(",", ""); columnName = columnName.replace("{", ""); columnName = columnName.replace("}", ""); columnName = columnName.replaceAll("\n", ""); columnName = columnName.replace(" ", " "); columnName = columnName.replace(" ", " "); columnName = columnName.replace("nbsp", " "); columnName = columnName.replaceAll("<.*>", ""); columnName = columnName.toLowerCase(); columnName = columnName.trim(); columnName = columnName.replaceAll("\\.", ""); columnName = columnName.replaceAll("\\$", ""); // clean the values from additional strings if (columnName.contains("/")) { columnName = columnName.substring(0, columnName.indexOf("/")); } if (columnName.contains("\\")) { columnName = columnName.substring(0, columnName.indexOf("\\")); } if (possibleNullValues.contains(columnName)) { columnName = nullValue; } return columnName; }
@Override public HTMLNotebookOutput convert(final Object object) { final String escaped = StringEscapeUtils.escapeHtml4(object.toString()); // Add in zero width space character (​) before @, ., $, _, and # final String wordBreaks = escaped.replaceAll("([@.$_#])", "​$1"); return new HTMLNotebookOutput(wordBreaks); }
protected void onRowAdded(List<? extends SpecificationRow<C>> added) { for (SpecificationRow<C> addedRow : added) { // Check correctness of added row if (addedRow.getCells().size() != columnHeaders.size()) { throw new IllegalArgumentException( "Illegal width for row " + StringEscapeUtils.escapeJava(addedRow.toString()) + ", expected width: " + columnHeaders.size()); } if (!addedRow.getCells().keySet().stream() .allMatch(columnId -> getOptionalColumnHeaderByName(columnId).isPresent())) { throw new IllegalArgumentException("Added row contains unknown IoVariable: " + StringEscapeUtils.escapeJava(addedRow.toString())); } } }
@Override public void changeName(String name) { PacketBuilder pb = new PacketBuilder(api); pb.setType(RequestType.PATCH); pb.setData(new JSONObject().put("name", StringEscapeUtils.escapeJson(name)).toString()); pb.setUrl("https://discordapp.com/api/webhooks/" + id); pb.makeRequest(); }