public String getFirstLastNameNaturalDiscriminator() { String firstName = this.getFirstName(); String lastName = this.getLastName(); if (firstName != null) firstName = StringUtils.toNormalized(firstName); if (lastName != null) lastName = StringUtils.toNormalized(lastName.toString()); String discriminator = String.format("%1$s-%2$s/%3$s", firstName, lastName, this.getId().toString()); return discriminator; }
@Override public void format(HtmlWriter writer) throws IOException { writer.writeStart("pre"); State state = getState(); ObjectType type = state.getType(); if (type != null) { writer.writeHtml(type.getInternalName()); writer.writeHtml(": "); } writer.writeStart( "a", "target", "_blank", "href", StringUtils.addQueryParameters( "/_debug/query", "where", "id = " + state.getId(), "action", "Run")); writer.writeHtml(getLabel()); writer.writeEnd(); writer.writeElement("br"); writer.writeHtml(ObjectUtils.toJson(state.getSimpleValues(), true)); writer.writeEnd(); }
/** * Splits the given string by commas, and returns each part unescaped. Calling {@link * #toCsv(String...)} on an array of Strings and then passing the result to this method will * always return the same array as specified by the <code>Arrays.equals()</code> method. */ public static String[] fromCsv(String string) { if (string == null) { return null; } else { // replaces a call to string.split(",") char[] charArr = string.toCharArray(); int commaCount = 0; for (char c : charArr) { if (c == ',') { commaCount++; } } String[] escaped = new String[commaCount + 1]; int index = 0; int offset = 0; int count = 0; for (char c : charArr) { if (c == ',') { escaped[index++] = new String(charArr, offset, count); offset += count + 1; count = 0; } else { count++; } } if (index == commaCount) { escaped[index] = new String(charArr, offset, count); } // end string.split(",") replacement code int length = escaped.length; List<String> unescaped = new ArrayList<String>(); for (int i = 0; i < length; i++) { String value = escaped[i]; if (value.startsWith("\"")) { // there are commas and/or double quotes escaped within StringBuilder builder = new StringBuilder(); int quoteCount = 0; do { builder.append(value); for (char c : value.toCharArray()) { if (c == '"') { quoteCount++; } } if (quoteCount % 2 == 1) { value = escaped[++i]; builder.append(','); } } while (quoteCount % 2 == 1); value = builder.toString(); } unescaped.add(StringUtils.unescapeCsv(value)); } return unescaped.toArray(new String[unescaped.size()]); } }
public static String escapeHtml(String string) { return string == null ? null : StringUtils.replaceAll( StringEscapeUtils.escapeHtml(string), "\\x22", """, // double quote "\\x27", "'"); // single quote }
@Override protected void beforeSave() { super.beforeSave(); if (StringUtils.isBlank(getName())) { // To avoid {@link com.psddev.dari.db.ValidationException} error as it implements {@link // Singleton}. ObjectType objectType = ObjectType.getInstance(getClass()); setName(objectType.getDisplayName()); } }
/** * Processes the given {@code path} under the given {@code root} and adds all associated class * files to the given {@code classNames}. */ private void processFile(Set<String> classNames, File root, String path) { File file = new File(root, path); if (file.isDirectory()) { for (File child : file.listFiles()) { processFile( classNames, root, path.isEmpty() ? child.getName() : path + File.separator + child.getName()); } } else { if (path.endsWith(CLASS_FILE_SUFFIX)) { String className = path.substring(0, path.length() - CLASS_FILE_SUFFIX.length()); className = StringUtils.replaceAll(className, Pattern.quote(File.separator), "."); classNames.add(className); } } }
private String createPublicUrl(String baseUrl, String path) { if (!ObjectUtils.isBlank(baseUrl)) { path = StringUtils.ensureEnd(baseUrl, "/") + path; try { URL url = new URL(path); path = new URI( url.getProtocol(), url.getAuthority(), url.getPath(), url.getQuery(), url.getRef()) .toASCIIString(); } catch (MalformedURLException error) { // Return the path as is if the given path is malformed. } catch (URISyntaxException error) { // Return the path as is if the resolved path is malformed. } } return path; }
/** * Finds all classes that are compatible with the given {@code baseClass} within the given {@code * loader}. */ public <T> Set<Class<? extends T>> find(ClassLoader loader, Class<T> baseClass) { Set<String> classNames = new HashSet<String>(); for (ClassLoader l = loader; l != null; l = l.getParent()) { if (l instanceof URLClassLoader && !getClassLoaderExclusions().contains(l.getClass().getName())) { for (URL url : ((URLClassLoader) l).getURLs()) { processUrl(classNames, url); } } } String classPath = System.getProperty("java.class.path"); if (!ObjectUtils.isBlank(classPath)) { for (String path : StringUtils.split(classPath, Pattern.quote(File.pathSeparator))) { try { processUrl(classNames, new File(path).toURI().toURL()); } catch (MalformedURLException ex) { } } } Set<Class<? extends T>> classes = new HashSet<Class<? extends T>>(); for (String className : classNames) { try { Class<?> c = Class.forName(className, false, loader); if (!baseClass.equals(c) && baseClass.isAssignableFrom(c)) { @SuppressWarnings("unchecked") Class<? extends T> tc = (Class<? extends T>) c; classes.add(tc); } } catch (ClassNotFoundException ex) { } catch (NoClassDefFoundError ex) { } } return classes; }
@Override public void send(MailMessage message) { if (StringUtils.isEmpty(host)) { String errorText = "SMTP Host can't be null!"; logger.error(errorText); throw new IllegalArgumentException(errorText); } if (message == null) { String errorText = "EmailMessage can't be null!"; logger.error(errorText); throw new IllegalArgumentException(errorText); } Session session; Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); if (useTls) { props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.port", tlsPort); // Note - not really tested. } else if (useSsl) { props.put("mail.smtp.socketFactory.port", sslPort); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.port", sslPort); } if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) { props.put("mail.smtp.auth", "true"); session = Session.getInstance( props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } else { session = Session.getInstance(props); } try { Message mimeMessage = new MimeMessage(session); mimeMessage.setFrom(new InternetAddress(message.getFrom())); mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(message.getTo())); mimeMessage.setSubject(message.getSubject()); if (!StringUtils.isEmpty(message.getReplyTo())) { mimeMessage.setReplyTo(InternetAddress.parse(message.getReplyTo())); } // Body, plain vs. html MimeMultipart multiPartContent = new MimeMultipart(); if (!StringUtils.isEmpty(message.getBodyPlain())) { MimeBodyPart plain = new MimeBodyPart(); plain.setText(message.getBodyPlain()); multiPartContent.addBodyPart(plain); } if (!StringUtils.isEmpty(message.getBodyHtml())) { MimeBodyPart html = new MimeBodyPart(); html.setContent(message.getBodyHtml(), "text/html"); multiPartContent.addBodyPart(html); multiPartContent.setSubType("alternative"); } mimeMessage.setContent(multiPartContent); Transport.send(mimeMessage); logger.info("Sent email to [{}] with subject [{}].", message.getTo(), message.getSubject()); } catch (MessagingException me) { logger.warn("Failed to send: [{}]", me.getMessage()); me.printStackTrace(); throw new RuntimeException(me); } }
@Override protected void doRequest( HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String format = request.getParameter("_format"); if (ObjectUtils.isBlank(format)) { chain.doFilter(request, response); return; } Writer writer = response.getWriter(); if ("js".equals(format)) { response.setContentType("text/javascript"); writer.write("(function(window, undefined) {"); writer.write("var d = window.document,"); writer.write("ss = d.getElementsByTagName('SCRIPT'),"); writer.write("s = ss[ss.length - 1],"); writer.write("f = d.createElement('IFRAME'),"); writer.write("h;"); writer.write("f.scrolling = 'no';"); writer.write("f.style.border = 'none';"); writer.write("f.style.width = '100%';"); writer.write("f.src = '"); writer.write( StringUtils.escapeJavaScript(JspUtils.getAbsoluteUrl(request, "", "_format", "_frame"))); writer.write("';"); writer.write("s.parentNode.insertBefore(f, s);"); writer.write("s.parentNode.removeChild(s);"); writer.write("window.addEventListener('message', function(event) {"); writer.write("var nh = parseInt(event.data, 10);"); writer.write("if (h !== nh) {"); writer.write("f.style.height = nh + 'px';"); writer.write("h = nh;"); writer.write("}"); writer.write("}, false);"); writer.write("})(window);"); return; } else if ("_frame".equals(format)) { @SuppressWarnings("resource") HtmlWriter html = new HtmlWriter(writer); response.setContentType("text/html"); html.writeTag("!doctype html"); html.writeStart("html"); html.writeStart("head"); html.writeEnd(); html.writeStart( "body", "style", html.cssString( "margin", 0, "padding", 0)); html.writeStart( "iframe", "scrolling", "no", "src", JspUtils.getAbsoluteUrl(request, "", "_format", null), "style", html.cssString( "border", "none", "width", "100%")); html.writeEnd(); html.writeStart("script", "type", "text/javascript"); html.writeRaw("(function(window, undefined) {"); html.writeRaw("setInterval(function() {"); html.writeRaw( "var f = document.getElementsByTagName('iframe')[0], h = f.contentDocument.body.scrollHeight;"); html.writeRaw("f.height = h + 'px';"); html.writeRaw("window.parent.postMessage('' + h, '*');"); html.writeRaw("}, 500);"); html.writeRaw("})(window);"); html.writeEnd(); html.writeEnd(); html.writeEnd(); return; } CapturingResponse capturing = new CapturingResponse(response); Object output; try { chain.doFilter(request, capturing); output = capturing.getOutput(); } catch (RuntimeException error) { output = error; } if ("json".equals(format)) { response.setContentType("application/json"); writeJson(request, writer, output); } else if ("jsonp".equals(format)) { String callback = request.getParameter("_callback"); // Legacy parameter support. if (ObjectUtils.isBlank(callback)) { callback = request.getParameter("callback"); } Preconditions.checkArgument(!ObjectUtils.isBlank(callback)); response.setContentType("application/javascript"); writer.write(callback); writer.write("("); writeJson(request, writer, output); writer.write(");"); } else if ("oembed".equals(format)) { response.setContentType("application/json+oembed"); Map<String, Object> json = new CompactMap<String, Object>(); StringWriter string = new StringWriter(); @SuppressWarnings("resource") HtmlWriter html = new HtmlWriter(string); html.writeStart( "script", "type", "text/javascript", "src", JspUtils.getAbsoluteUrl(request, "", "_format", "js")); html.writeEnd(); json.put("version", "1.0"); json.put("type", "rich"); json.put("html", string.toString()); writer.write(ObjectUtils.toJson(json)); } else { throw new IllegalArgumentException( String.format("[%s] isn't a valid API response format!", format)); } }
public static String stripHtml(CharSequence sequence) { Matcher m = StringUtils.getPattern("<[^>]*>").matcher(sequence); return m.replaceAll(""); }
@Override protected void doService(ToolPageContext page) throws IOException, ServletException { ToolUser user = page.getUser(); Collection<String> includeFields = Arrays.asList("returnToDashboardOnSave"); Object object = Query.from(Object.class).where("_id = ?", page.param(UUID.class, "id")).first(); State state = State.getInstance(object); ContentLock contentLock = null; if (object != null) { contentLock = ContentLock.Static.lock(object, null, user); } if (page.isFormPost()) { if (page.param(String.class, "action-edits") != null) { if (state != null) { Date newPublishDate = page.param(Date.class, "publishDate"); if (newPublishDate != null) { Content.ObjectModification contentData = state.as(Content.ObjectModification.class); DateTimeZone timeZone = page.getUserDateTimeZone(); newPublishDate = new Date( DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss") .withZone(timeZone) .parseMillis(new DateTime(newPublishDate).toString("yyyy-MM-dd HH:mm:ss"))); contentData.setPublishUser(page.getUser()); contentData.setPublishDate(newPublishDate); state.save(); } } } else if (page.param(String.class, "action-unlock") != null) { contentLock.delete(); page.writeStart("script", "type", "text/javascript"); page.writeRaw("window.location.reload();"); page.writeEnd(); } else if (page.param(String.class, "action-settings") != null) { try { page.include("/WEB-INF/objectPost.jsp", "object", user, "includeFields", includeFields); user.save(); } catch (Exception error) { page.getErrors().add(error); } } } String returnUrl = page.param(String.class, "returnUrl"); page.writeHeader(); page.writeStart("style", "type", "text/css"); page.writeCss(".cms-contentTools th", "width", "25%;"); page.writeEnd(); page.writeStart("div", "class", "widget cms-contentTools"); page.writeStart("h1", "class", "icon icon-wrench"); page.writeHtml("Tools"); page.writeEnd(); page.writeStart("div", "class", "tabbed"); page.writeStart("div", "class", "fixedScrollable", "data-tab", "For Editors"); if (object != null) { Content.ObjectModification contentData = state.as(Content.ObjectModification.class); Date publishDate = contentData.getPublishDate(); ToolUser publishUser = contentData.getPublishUser(); Date updateDate = contentData.getUpdateDate(); ToolUser updateUser = contentData.getUpdateUser(); page.writeStart("table", "class", "table-striped"); page.writeStart("tbody"); if (publishDate != null || publishUser != null) { page.writeStart("tr"); page.writeStart("th"); page.writeHtml("Published"); page.writeEnd(); page.writeStart("td"); if (publishDate != null) { page.writeHtml(page.formatUserDateTime(publishDate)); } page.writeEnd(); page.writeStart("td"); if (publishUser != null) { page.writeObjectLabel(publishUser); } page.writeEnd(); page.writeEnd(); } if (updateDate != null || updateUser != null) { page.writeStart("tr"); page.writeStart("th"); page.writeHtml("Last Updated"); page.writeEnd(); page.writeStart("td"); if (updateDate != null) { page.writeHtml(page.formatUserDateTime(updateDate)); } page.writeEnd(); page.writeStart("td"); if (updateUser != null) { page.writeObjectLabel(updateUser); } page.writeEnd(); page.writeEnd(); } page.writeEnd(); page.writeEnd(); page.writeStart("h2"); page.writeHtml("Advanced Edits"); page.writeEnd(); if (page.isFormPost() && page.param(String.class, "action-edits") != null) { if (page.getErrors().isEmpty()) { page.writeStart("div", "class", "message message-success"); page.writeHtml("Advanced edits successfully saved."); page.writeEnd(); } else { page.include("/WEB-INF/errors.jsp"); } } page.writeStart("form", "method", "post", "action", page.url("")); page.writeStart("div", "class", "inputContainer"); page.writeStart("div", "class", "inputLabel"); page.writeStart("label", "for", page.createId()); page.writeHtml("New Publish Date"); page.writeEnd(); page.writeEnd(); page.writeStart("div", "class", "inputSmall"); page.writeElement( "input", "type", "text", "class", "date", "name", "publishDate", "value", page.formatUserDateTime(publishDate)); page.writeEnd(); page.writeEnd(); page.writeStart("div", "class", "actions"); page.writeStart( "button", "class", "icon icon-action-save", "name", "action-edits", "value", true); page.writeHtml("Save"); page.writeEnd(); page.writeEnd(); page.writeEnd(); if (!user.equals(contentLock.getOwner())) { page.writeStart("h2"); page.writeHtml("Content Lock"); page.writeEnd(); page.writeStart("div", "class", "message message-warning"); page.writeStart("p"); page.writeHtml("Locked by "); page.writeObjectLabel(contentLock.getOwner()); page.writeHtml(" since "); page.writeHtml(page.formatUserDateTime(contentLock.getCreateDate())); page.writeHtml("."); page.writeEnd(); page.writeEnd(); page.writeStart("form", "method", "post", "action", page.url("")); page.writeStart("div", "class", "actions"); page.writeStart( "button", "class", "icon icon-unlock", "name", "action-unlock", "value", true); page.writeHtml("Unlock"); page.writeEnd(); page.writeEnd(); page.writeEnd(); } } page.writeStart("h2"); page.writeHtml("Settings"); page.writeEnd(); if (page.isFormPost() && page.param(String.class, "action-settings") != null) { if (page.getErrors().isEmpty()) { page.writeStart("div", "class", "message message-success"); page.writeHtml("Settings successfully saved."); page.writeEnd(); } else { page.include("/WEB-INF/errors.jsp"); } } page.writeStart("form", "method", "post", "action", page.url(""), "style", "margin-bottom:0;"); page.include("/WEB-INF/objectForm.jsp", "object", user, "includeFields", includeFields); page.writeStart("div", "class", "actions"); page.writeStart( "button", "class", "icon icon-action-save", "name", "action-settings", "value", true); page.writeHtml("Save"); page.writeEnd(); page.writeEnd(); page.writeEnd(); page.writeEnd(); page.writeStart("div", "class", "fixedScrollable", "data-tab", "For Developers"); page.writeStart("ul"); if (object != null) { page.writeStart("li"); page.writeStart("a", "target", "_blank", "href", page.objectUrl("/contentRaw", object)); page.writeHtml("View Raw Data"); page.writeEnd(); page.writeEnd(); } if (!ObjectUtils.isBlank(returnUrl)) { page.writeStart("li"); if (ObjectUtils.to( boolean.class, StringUtils.getQueryParameterValue(returnUrl, "deprecated"))) { page.writeStart( "a", "target", "_top", "href", StringUtils.addQueryParameters(returnUrl, "deprecated", null)); page.writeHtml("Hide Deprecated Fields"); page.writeEnd(); } else { page.writeStart( "a", "target", "_top", "href", StringUtils.addQueryParameters(returnUrl, "deprecated", true)); page.writeHtml("Show Deprecated Fields"); page.writeEnd(); } page.writeEnd(); } page.writeEnd(); if (object != null) { ObjectType type = state.getType(); page.writeStart("table", "class", "table-striped"); page.writeStart("tbody"); if (type != null) { Class<?> objectClass = type.getObjectClass(); if (objectClass != null) { page.writeStart("tr"); page.writeStart("th"); page.writeStart("label", "for", page.createId()); page.writeHtml("Class"); page.writeEnd(); page.writeEnd(); page.writeStart("td"); page.writeJavaClassLink(objectClass); page.writeEnd(); page.writeEnd(); } } page.writeStart("tr"); page.writeStart("th"); page.writeStart("label", "for", page.createId()); page.writeHtml("ID"); page.writeEnd(); page.writeEnd(); page.writeStart("td"); page.writeElement( "input", "type", "text", "id", page.getId(), "class", "code", "value", state.getId(), "readonly", "readonly", "style", "width:100%;", "onclick", "this.select();"); page.writeEnd(); page.writeEnd(); page.writeStart("tr"); page.writeStart("th"); page.writeStart("label", "for", page.createId()); page.writeHtml("URL"); page.writeEnd(); page.writeEnd(); page.writeStart("td"); page.writeElement( "input", "type", "text", "id", page.getId(), "value", JspUtils.getAbsoluteUrl( page.getRequest(), page.cmsUrl("/content/edit.jsp", "id", state.getId())), "readonly", "readonly", "style", "width:100%;", "onclick", "this.select();"); page.writeEnd(); page.writeEnd(); page.writeEnd(); page.writeEnd(); } if (object != null) { ObjectType type = state.getType(); if (type != null) { if (!ObjectUtils.isBlank(type.as(Renderer.TypeModification.class).getEmbedPath())) { String permalink = state.as(Directory.ObjectModification.class).getPermalink(); if (!ObjectUtils.isBlank(permalink)) { String siteUrl = Application.Static.getInstance(CmsTool.class).getDefaultSiteUrl(); StringBuilder embedCode = new StringBuilder(); embedCode.append("<script type=\"text/javascript\" src=\""); embedCode.append( StringUtils.addQueryParameters( StringUtils.removeEnd(siteUrl, "/") + permalink, "_embed", true, "_format", "js")); embedCode.append("\"></script>"); page.writeHtml("Embed Code:"); page.writeElement("br"); page.writeStart( "textarea", "class", "code", "data-expandable-class", "code", "readonly", "readonly", "onclick", "this.select();"); page.writeHtml(embedCode); page.writeEnd(); } } String defaultPath = type.as(Renderer.TypeModification.class).getPath(); Map<String, String> paths = type.as(Renderer.TypeModification.class).getPaths(); if (!ObjectUtils.isBlank(defaultPath) || !ObjectUtils.isBlank(paths)) { page.writeStart("h2"); page.writeHtml("Renderers"); page.writeEnd(); page.writeStart("table", "class", "table-striped"); page.writeStart("tbody"); if (!ObjectUtils.isBlank(defaultPath)) { page.writeStart("tr"); page.writeStart("th"); page.writeStart("code"); page.writeHtml("Default"); page.writeEnd(); page.writeEnd(); page.writeStart("td"); page.writeStart("code"); page.writeStart( "a", "target", "_blank", "href", DebugFilter.Static.getServletPath( page.getRequest(), "code", "action", "edit", "type", "JSP", "servletPath", defaultPath)); page.writeHtml(defaultPath); page.writeEnd(); page.writeEnd(); page.writeEnd(); page.writeEnd(); } for (Map.Entry<String, String> entry : paths.entrySet()) { page.writeStart("tr"); page.writeStart("th"); page.writeStart("code"); page.writeHtml(entry.getKey()); page.writeEnd(); page.writeEnd(); page.writeStart("td"); page.writeStart("code"); page.writeStart( "a", "target", "_blank", "href", DebugFilter.Static.getServletPath( page.getRequest(), "code", "action", "edit", "type", "JSP", "servletPath", entry.getValue())); page.writeHtml(entry.getValue()); page.writeEnd(); page.writeEnd(); page.writeEnd(); page.writeEnd(); } page.writeEnd(); page.writeEnd(); } Class<?> objectClass = type.getObjectClass(); if (objectClass != null) { Static.writeJavaAnnotationDescriptions(page, objectClass); } } } page.writeEnd(); page.writeEnd(); page.writeEnd(); page.writeFooter(); }