Java Examples for org.pegdown.PegDownProcessor

The following java examples will help you to understand the usage of org.pegdown.PegDownProcessor. These source code samples are taken from different open source projects.

Example 1
Project: penmanship-master  File: Penmanship.java View source code
public String xmlForMarkdown(String markdown, String namespace, String customURLScheme) {
    PegDownProcessor pegDownProcessor = new PegDownProcessor();
    RootNode rootNode = pegDownProcessor.parseMarkdown(markdown.toCharArray());
    AndroidMarkdownVisitor androidMarkdownVisitor = new AndroidMarkdownVisitor.Builder().namespace(namespace).customURIScheme(customURLScheme).build();
    androidMarkdownVisitor.visit(rootNode);
    return androidMarkdownVisitor.render();
}
Example 2
Project: flow-netbeans-markdown-master  File: RenderableImpl.java View source code
private String renderBodyText(Set<RenderOption> renderOptions, MarkdownGlobalOptions markdownOptions, String sourceText) throws IOException {
    String bodyText;
    try {
        PegDownProcessor markdownProcessor = new PegDownProcessor(markdownOptions.getExtensionsValue());
        final boolean resolveImageUrls = renderOptions.contains(RenderOption.RESOLVE_IMAGE_URLS);
        final boolean resolveLinkUrls = renderOptions.contains(RenderOption.RESOLVE_LINK_URLS);
        if (resolveImageUrls || resolveLinkUrls) {
            RootNode rootNode = markdownProcessor.parseMarkdown(sourceText.toCharArray());
            FileObject sourceFile = context.getPrimaryFile();
            final PreviewSerializer htmlSerializer = new PreviewSerializer(sourceFile.toURL(), resolveImageUrls, resolveLinkUrls);
            bodyText = htmlSerializer.toHtml(rootNode);
        } else {
            RootNode rootNode = markdownProcessor.parseMarkdown(sourceText.toCharArray());
            final ExportSerializer htmlSerializer = new ExportSerializer(new LinkRenderer());
            bodyText = htmlSerializer.toHtml(rootNode);
        }
    } catch (ParsingTimeoutException ex) {
        throw new IOException(ex);
    }
    return bodyText;
}
Example 3
Project: gutenberg-master  File: PegdownPdfTest.java View source code
private void processString(String usecase, String mkd, Function<InvocationContext, InvocationContext> customizer) throws Exception {
    Reference<Parser> parserRef = new Reference<Parser>();
    ITextContext iTextContext = openDocument(usecase);
    PegDownPlugins plugins = PegDownPlugins.builder().withPlugin(AttributesPlugin.class).withPlugin(GenericBoxPlugin.class, parserRef).build();
    PegDownProcessor processor = new PegDownProcessor(Extensions.ALL, plugins);
    parserRef.set(processor.parser);
    RootNode rootNode = processor.parseMarkdown(mkd.toCharArray());
    InvocationContext context = customizer.apply(new InvocationContext(iTextContext));
    if (context == null) {
        fail("No context");
        return;
    }
    context.process(0, rootNode);
    context.flushPendingChapter();
    iTextContext.close();
}
Example 4
Project: Orienteer-master  File: MarkDownModel.java View source code
@Override
protected String load() {
    String markDownValue = markDawnModel.getObject();
    if (Strings.isEmpty(markDownValue))
        return "";
    Class<?> processor = WicketObjects.resolveClass("org.pegdown.PegDownProcessor");
    if (processor != null) {
        try {
            Method toHtml = processor.getMethod("markdownToHtml", String.class);
            return Objects.toString(toHtml.invoke(processor.newInstance(), markDownValue));
        } catch (Exception e) {
            throw new WicketRuntimeException("Can't use pegdown for markups", e);
        }
    }
    return markDownValue;
}
Example 5
Project: oerworldmap-master  File: StaticPage.java View source code
public Result get(String aPage) {
    String title = aPage.substring(0, 1).toUpperCase().concat(aPage.substring(1));
    String language = getLocale().getLanguage();
    String country = getLocale().getCountry();
    String extension = ".md";
    String path = "public/pages/";
    ClassLoader classLoader = mEnv.classLoader();
    String titleLocalePath = path.concat(title).concat("_").concat(language).concat("_").concat(country).concat(extension);
    String titleLanguagePath = path.concat(title).concat("_").concat(language).concat(extension);
    String titlePath = path.concat(title).concat(extension);
    String body;
    InputStream inputStream;
    try {
        inputStream = classLoader.getResourceAsStream(titleLocalePath);
        body = IOUtils.toString(inputStream);
        inputStream.close();
    } catch (NullPointerExceptionIOException |  noLocale) {
        try {
            inputStream = classLoader.getResourceAsStream(titleLanguagePath);
            body = IOUtils.toString(inputStream);
            inputStream.close();
        } catch (NullPointerExceptionIOException |  noLanguage) {
            try {
                inputStream = classLoader.getResourceAsStream(titlePath);
                body = IOUtils.toString(inputStream);
                inputStream.close();
            } catch (NullPointerExceptionIOException |  noPage) {
                return notFound("Page not found");
            }
        }
    }
    PegDownProcessor pegDownProcessor = new PegDownProcessor();
    Map<String, Object> scope = new HashMap<>();
    scope.put("title", title);
    scope.put("body", pegDownProcessor.markdownToHtml(body));
    return ok(render(title, "StaticPage/index.mustache", scope));
}
Example 6
Project: solo-master  File: Markdowns.java View source code
/**
     * Converts the specified markdown text to HTML.
     *
     * @param markdownText the specified markdown text
     * @return converted HTML, returns {@code null} if the specified markdown text is "" or {@code null}, returns
     * "Markdown error" if exception
     */
public static String toHTML(final String markdownText) {
    if (Strings.isEmptyOrNull(markdownText)) {
        return "";
    }
    final PegDownProcessor pegDownProcessor = new PegDownProcessor(Extensions.ALL_OPTIONALS | Extensions.ALL_WITH_OPTIONALS, 5000);
    String ret = pegDownProcessor.markdownToHtml(markdownText);
    if (!StringUtils.startsWith(ret, "<p>")) {
        ret = "<p>" + ret + "</p>";
    }
    return ret;
}
Example 7
Project: deltascript-master  File: DocTestRunner.java View source code
private static List<Object[]> recursiveDocScan(File f) {
    final List<Object[]> list = A.list();
    if (f.isDirectory()) {
        for (File item : f.listFiles()) list.addAll(recursiveDocScan(item));
    } else if (f.isFile() && f.getName().endsWith(".md")) {
        System.out.println("Parsing file: " + f.getName());
        try {
            final Scanner s = new Scanner(f, "UTF-8");
            final String fileText = s.useDelimiter("\\Z").next();
            s.close();
            final PegDownProcessor processor = new PegDownProcessor();
            final RootNode node = processor.parseMarkdown(fileText.toCharArray());
            final TestExtractorVisitor visitor = new TestExtractorVisitor(f.getName(), CONTEXT);
            node.accept(visitor);
            for (DocTest test : visitor.getTests()) list.add(new Object[] { test.getName(), test });
        } catch (Exception ex) {
            System.out.println("!! Error reading file !!");
            ex.printStackTrace(System.out);
        }
    }
    return list;
}
Example 8
Project: SoundLooper-master  File: HelpController.java View source code
public void loadContent(String fileName) {
    WebEngine engine = webView.getEngine();
    InputStream stream = this.getClass().getClassLoader().getResourceAsStream(fileName);
    try {
        if (stream == null) {
            throw new IOException("The stream is null");
        }
        String markdown = IOUtils.toString(stream, Charset.forName("UTF-8"));
        PegDownProcessor processor = new PegDownProcessor();
        String html = processor.markdownToHtml(markdown);
        engine.loadContent(html);
    } catch (IOException e) {
        engine.loadContent("Impossible de charger l'aide");
        logger.error("Error loading file " + fileName, e);
    }
}
Example 9
Project: jbake-master  File: MarkdownEngine.java View source code
@Override
public void processBody(final ParserContext context) {
    String[] mdExts = context.getConfig().getStringArray("markdown.extensions");
    int extensions = Extensions.NONE;
    if (mdExts.length > 0) {
        for (int index = 0; index < mdExts.length; index++) {
            String ext = mdExts[index];
            if (ext.startsWith("-")) {
                ext = ext.substring(1);
                extensions = removeExtension(extensions, extensionFor(ext));
            } else {
                if (ext.startsWith("+")) {
                    ext = ext.substring(1);
                }
                extensions = addExtension(extensions, extensionFor(ext));
            }
        }
    }
    long maxParsingTime = context.getConfig().getLong("markdown.maxParsingTimeInMillis", PegDownProcessor.DEFAULT_MAX_PARSING_TIME);
    PegDownProcessor pegdownProcessor = new PegDownProcessor(extensions, maxParsingTime);
    context.setBody(pegdownProcessor.markdownToHtml(context.getBody()));
}
Example 10
Project: tatami-master  File: SyndicView.java View source code
@Override
@SuppressWarnings("unchecked")
protected List<Item> buildFeedItems(Map<String, Object> model, HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {
    List<Item> items = new ArrayList<Item>();
    Collection<StatusDTO> listContent = (Collection<StatusDTO>) model.get("feedContent");
    if (listContent == null) {
        return items;
    }
    String statusBaseLink = (String) model.get("statusBaseLink");
    for (StatusDTO tempContent : listContent) {
        Item item = new Item();
        String statusText = tempContent.getContent();
        PegDownProcessor processor = new PegDownProcessor();
        String htmlText = processor.markdownToHtml(statusText);
        log.debug("feed html content {}", htmlText);
        // url handling  for mention & tags
        htmlText = convertLinks(htmlText);
        Content content = new Content();
        content.setType(Content.HTML);
        content.setValue(htmlText);
        item.setContent(content);
        // build link for the status
        StringBuilder linkBuilder = new StringBuilder(statusBaseLink);
        linkBuilder.append("status/").append(tempContent.getStatusId());
        item.setTitle(statusText.substring(0, Math.min(30, statusText.length())));
        item.setLink(linkBuilder.toString());
        item.setPubDate(tempContent.getStatusDate());
        items.add(item);
    }
    return items;
}
Example 11
Project: windup-master  File: MarkdownToHtmlMethod.java View source code
@Override
public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException {
    if (arguments.size() != 1) {
        throw new TemplateModelException("Error, method expects one argument (String)");
    }
    SimpleScalar freemarkerArg = (SimpleScalar) arguments.get(0);
    String markdownSource = freemarkerArg.getAsString();
    SoftReference<String> cachedResult = cache.get(markdownSource);
    String cachedResultString;
    if (cachedResult != null && (cachedResultString = cachedResult.get()) != null) {
        return cachedResultString;
    }
    try {
        // build the plugins object with our extensions
        PegDownPlugins plugins = PegDownPlugins.builder().build();
        PegDownProcessor processor = new PegDownProcessor(Extensions.FENCED_CODE_BLOCKS, MAX_PARSING_TIME_MILLIS, plugins);
        // build the node and then serialize it so that we can make sure the serializer uses our plugins
        RootNode outputNode = processor.parseMarkdown(markdownSource.toCharArray());
        // Our plugin is also a serializer, so build a plugins list for serialization as well
        List<ToHtmlSerializerPlugin> serializerPlugins = new ArrayList<>(1);
        ToHtmlSerializer serializer = new ToHtmlSerializerExtended(new LinkRenderer(), Collections.<String, VerbatimSerializer>emptyMap(), serializerPlugins);
        String result = serializer.toHtml(outputNode);
        cache.put(markdownSource, new SoftReference<>(result));
        return result;
    } catch (Throwable t) {
        LOG.log(Level.WARNING, "Failed to parse markdown due to: " + t.getMessage() + " markdown source: " + markdownSource, t);
        return markdownSource;
    }
}
Example 12
Project: cucumber-contrib-master  File: Configuration.java View source code
public PegDownProcessor getMarkdownProcessor() {
    if (markdownProcessor == null) {
        PegDownPlugins plugins = PegDownPlugins.builder().withPlugin(NamedBlockCurlyBracePlugin.class).withPlugin(NamedBlockSquareBracketAndDashPlugin.class).build();
        markdownProcessor = new PegDownProcessor(Extensions.TABLES, plugins);
    }
    return markdownProcessor;
}
Example 13
Project: gitblit-master  File: MarkdownUtils.java View source code
/**
	 * Returns the html version of the markdown source text.
	 *
	 * @param markdown
	 * @return html version of markdown text
	 * @throws java.text.ParseException
	 */
public static String transformMarkdown(String markdown, LinkRenderer linkRenderer) {
    try {
        PegDownProcessor pd = new PegDownProcessor(ALL & ~SMARTYPANTS & ~ANCHORLINKS);
        RootNode astRoot = pd.parseMarkdown(markdown.toCharArray());
        return new WorkaroundHtmlSerializer(linkRenderer == null ? new LinkRenderer() : linkRenderer).toHtml(astRoot);
    } catch (ParsingTimeoutException e) {
        return null;
    }
}
Example 14
Project: wisdom-master  File: MarkdownMojo.java View source code
/**
     * Compiles all markdown files located in the internal and external asset directories.
     *
     * @throws MojoExecutionException if a markdown file cannot be processed
     */
public void execute() throws MojoExecutionException {
    if (extensions == null || extensions.isEmpty()) {
        extensions = ImmutableList.of("md", "markdown");
    }
    if (instance == null) {
        instance = new PegDownProcessor(Extensions.ALL);
    }
    try {
        for (File f : getResources(extensions)) {
            process(f);
        }
    } catch (IOException e) {
        throw new MojoExecutionException("Error while processing a Markdown file", e);
    }
}
Example 15
Project: hale-master  File: TemplatePage.java View source code
@SuppressWarnings("serial")
@Override
protected void addControls(boolean loggedIn) {
    super.addControls(loggedIn);
    StringValue idParam = getPageParameters().get(0);
    if (!idParam.isNull() && !idParam.isEmpty()) {
        String templateId = idParam.toString();
        OrientGraph graph = DatabaseHelper.getGraph();
        try {
            Template template = null;
            try {
                template = Template.getByTemplateId(graph, templateId);
            } catch (NonUniqueResultException e) {
                log.error("Duplicate template representation: " + templateId, e);
            }
            if (template != null) {
                // name
                Label name = new Label("name", template.getName());
                add(name);
                // download
                String href = TemplateLocations.getTemplateDownloadUrl(templateId);
                ExternalLink download = new ExternalLink("download", href);
                add(download);
                // project location
                WebMarkupContainer project = new WebMarkupContainer("project");
                project.add(AttributeModifier.replace("value", TemplateLocations.getTemplateProjectUrl(scavenger, templateId)));
                add(project);
                // author
                Label author = new Label("author", template.getAuthor());
                add(author);
                // edit-buttons container
                WebMarkupContainer editButtons = new WebMarkupContainer("edit-buttons");
                editButtons.setVisible(false);
                add(editButtons);
                // deleteDialog container
                WebMarkupContainer deleteDialog = new WebMarkupContainer("deleteDialog");
                deleteDialog.setVisible(false);
                add(deleteDialog);
                // user
                String userName;
                Vertex v = template.getV();
                boolean showEditPart = UserUtil.isAdmin();
                Iterator<Vertex> owners = v.getVertices(Direction.OUT, "owner").iterator();
                if (owners.hasNext()) {
                    User user = new User(owners.next(), graph);
                    userName = UserUtil.getDisplayName(user);
                    showEditPart = loggedIn && UserUtil.getLogin().equals(user.getLogin());
                } else {
                    userName = "Unregistered user";
                }
                // edit buttons
                if (showEditPart) {
                    editButtons.setVisible(true);
                    deleteDialog.setVisible(true);
                    // edit
                    editButtons.add(new BookmarkablePageLink<>("edit", EditTemplatePage.class, new PageParameters().set(0, templateId)));
                    // update
                    editButtons.add(new BookmarkablePageLink<>("update", UpdateTemplatePage.class, new PageParameters().set(0, templateId)));
                    // delete
                    deleteDialog.add(new DeleteTemplateLink("delete", templateId));
                }
                Label user = new Label("user", userName);
                add(user);
                // description
                String descr = template.getDescription();
                String htmlDescr = null;
                if (descr == null || descr.isEmpty()) {
                    descr = "No description for the project template available.";
                } else {
                    // convert markdown to
                    htmlDescr = new PegDownProcessor(Extensions.AUTOLINKS | Extensions.SUPPRESS_ALL_HTML | Extensions.HARDWRAPS | Extensions.SMARTYPANTS).markdownToHtml(descr);
                }
                // description in pre
                Label description = new Label("description", descr);
                description.setVisible(htmlDescr == null);
                add(description);
                // description in div
                Label htmlDescription = new Label("html-description", htmlDescr);
                htmlDescription.setVisible(htmlDescr != null);
                htmlDescription.setEscapeModelStrings(false);
                add(htmlDescription);
                // invalid
                WebMarkupContainer statusInvalid = new WebMarkupContainer("invalid");
                statusInvalid.setVisible(!template.isValid());
                add(statusInvalid);
                // resources
                ResourcesPanel resources = new ResourcesPanel("resources", templateId);
                add(resources);
                // project popover
                WebMarkupContainer projectPopover = new WebMarkupContainer("project-popover");
                projectPopover.add(new HTMLPopoverBehavior(Model.of("Load template in HALE"), new PopoverConfig().withPlacement(Placement.bottom)) {

                    @Override
                    public Component newBodyComponent(String markupId) {
                        return new ProjectURLPopover(markupId);
                    }
                });
                add(projectPopover);
            } else {
                throw new AbortWithHttpErrorCodeException(HttpServletResponse.SC_NOT_FOUND, "Template not found.");
            }
        } finally {
            graph.shutdown();
        }
    } else
        throw new AbortWithHttpErrorCodeException(HttpServletResponse.SC_BAD_REQUEST, "Template identifier must be specified.");
}
Example 16
Project: idea-markdown-master  File: MarkdownAnnotator.java View source code
/** Init/reinit thread local {@link PegDownProcessor}. */
private static ThreadLocal<PegDownProcessor> initProcessor() {
    return new ThreadLocal<PegDownProcessor>() {

        @Override
        protected PegDownProcessor initialValue() {
            return new PegDownProcessor(MarkdownGlobalSettings.getInstance().getExtensionsValue(), MarkdownGlobalSettings.getInstance().getParsingTimeout());
        }
    };
}
Example 17
Project: idea-multimarkdown-master  File: MultiMarkdownLexParserManager.java View source code
public static RootNode parseMarkdownRoot(@NotNull final CharSequence buffer, @Nullable Integer pegdownExtensions, @Nullable Integer parsingTimeout) {
    int actualPegdownExtensions = (pegdownExtensions != null ? pegdownExtensions : MultiMarkdownGlobalSettings.getInstance().getExtensionsValue()) | (MultiMarkdownGlobalSettings.getInstance().githubWikiLinks.getValue() ? GITHUB_WIKI_LINKS : 0);
    if (!disable) {
        final ParsingInfo info = lastParsingResult.get();
        if (info != null && info.pegdownExtensions == actualPegdownExtensions && info.bufferHash == buffer.hashCode() && info.buffer.equals(buffer)) {
            if (log)
                logger.info("Root Parsing request satisfied by cache for thread " + Thread.currentThread());
            return info.rootNode;
        }
        if (log)
            logger.info("Root Parsing request not satisfied by cache for thread " + Thread.currentThread());
    }
    PegDownProcessor processor = new PegDownProcessor(actualPegdownExtensions, parsingTimeout != null ? parsingTimeout : MultiMarkdownGlobalSettings.getInstance().parsingTimeout.getValue());
    char[] currentChars = buffer.toString().toCharArray();
    RootNode rootNode = processor.parseMarkdown(currentChars);
    String exceptionText = null;
    try {
        rootNode = processor.parseMarkdown(currentChars);
    } catch (ParsingTimeoutException e) {
        exceptionText = e.getMessage();
    } catch (ParserRuntimeException e) {
        exceptionText = e.getMessage();
    }
    if (rootNode == null) {
        ErrorNode errorNode = new ErrorNode("Parser Timeout Error: " + exceptionText);
        errorNode.setStartIndex(0);
        errorNode.setEndIndex(buffer.length());
        ArrayList<Node> nodes = new ArrayList<Node>();
        nodes.add(errorNode);
        rootNode = new RootNode(nodes);
    }
    if (!disable)
        lastParsingResult.set(new ParsingInfo(buffer, actualPegdownExtensions, rootNode, null, false));
    return rootNode;
}
Example 18
Project: maven-confluence-plugin-master  File: Site.java View source code
//private static final Logger LOGGER = LoggerFactory.getLogger(Site.class);
/**
     * 
     * @param is
     * @return 
     */
static java.io.InputStream processMarkdown(final java.io.InputStream is, final String homePageTitle) throws IOException {
    final char[] contents = IOUtils.toCharArray(is);
    final PegDownProcessor p = new PegDownProcessor(ToConfluenceSerializer.extensions());
    final RootNode root = p.parseMarkdown(contents);
    ToConfluenceSerializer ser = new ToConfluenceSerializer() {

        @Override
        protected void notImplementedYet(Node node) {
            final int lc[] = ToConfluenceSerializer.lineAndColFromNode(new String(contents), node);
            throw new UnsupportedOperationException(String.format("Node [%s] not supported yet. line=[%d] col=[%d]", node.getClass().getSimpleName(), lc[0], lc[1]));
        }

        @Override
        protected String getHomePageTitle() {
            return homePageTitle;
        }
    };
    root.accept(ser);
    return new java.io.ByteArrayInputStream(ser.toString().getBytes());
}
Example 19
Project: netbeans-github-issues-plugin-master  File: GitHubIssuePanel.java View source code
@NbBundle.Messages({ "# {0} - count", "GitHubIssuePanel.comment.count=Comment({0})", "# {0} - count", "GitHubIssuePanel.files.changed.count=Files Changed({0})", "# {0} - count", "GitHubIssuePanel.commit.count=Commits({0})" })
public void update() {
    assert EventQueue.isDispatchThread();
    // header
    setHeader();
    if (gitHubIssue == null) {
        return;
    }
    GitHubRepository repository = getRepository();
    if (repository == null) {
        return;
    }
    boolean isCollaborator = repository.isCollaborator();
    // collaborator?
    if (isCollaborator) {
        GitHubCache cache = GitHubCache.create(repository);
        // milestone
        updateMilestones(cache, false);
        // assignee
        List<User> collaborators = cache.getCollaborators();
        assigneeComboBoxModel.removeAllElements();
        assigneeComboBoxModel.addElement(null);
        for (User collaborator : collaborators) {
            assigneeComboBoxModel.addElement(collaborator);
        }
        // label
        updateLables(cache, false);
    }
    // existing issue
    boolean isExistingIssue = !isNew();
    boolean isPullRequest = isPullRequest();
    if (isExistingIssue) {
        Issue issue = gitHubIssue.getIssue();
        if (issue != null) {
            // set existing info
            // user infomation
            User user = issue.getUser();
            GitHubCache cache = GitHubCache.create(repository);
            Icon userIcon = cache.getUserIcon(user);
            // header
            headerCreatedDateLabel.setText(DATE_FORMAT.format(issue.getCreatedAt()));
            headerUpdatedDateLabel.setText(DATE_FORMAT.format(issue.getUpdatedAt()));
            headerCreatedByUserLabel.setText(user.getLogin());
            headerCreatedByUserLabel.setIcon(userIcon);
            // title
            titleTextField.setText(issue.getTitle());
            Dimension dim = titleTextField.getPreferredSize();
            titleTextField.setMinimumSize(new Dimension(0, dim.height));
            titleTextField.setPreferredSize(new Dimension(0, dim.height));
            // description
            descriptionTabbedPanel.setText(issue.getBody());
            // assignee
            User assignee = issue.getAssignee();
            if (assignee != null) {
                setAssigneeSelected(assignee);
            }
            // milestone
            Milestone milestone = issue.getMilestone();
            if (milestone != null) {
                setMilestoneSelected(milestone);
            }
            // labels
            List<Label> labels = issue.getLabels();
            if (!labels.isEmpty()) {
                setLabelsSelected(labels);
            }
            // set attributes
            attributesViewPanel.setAttributes(issue, repository);
            // new comment
            GitHubIssueState state = GitHubIssueState.toEnum(issue.getState());
            setNewCommentButtonCloseOrReopen(state == GitHubIssueState.CLOSED);
            // editable
            boolean isEditable = gitHubIssue.isEditableUser();
            titleTextField.setEditable(isEditable);
            descriptionTabbedPanel.setEditable(isEditable);
            // add comments
            commentsPanel.removeAllComments();
            List<Comment> comments = gitHubIssue.getComments();
            // set count
            commentsCollapsibleSectionPanel.setLabel(Bundle.GitHubIssuePanel_comment_count(comments.size()));
            PegDownProcessor processor = GitHubIssues.getInstance().getPegDownProcessor();
            for (Comment comment : comments) {
                String body = comment.getBody();
                String bodyHtml = processor.markdownToHtml(body);
                // NOI18N
                comment.setBodyHtml(String.format("<html>%s</html>", bodyHtml));
            }
            commentsPanel.addComments(comments, repository);
            // PR
            if (isPullRequest) {
                PullRequest pullRequest = getPullRequest();
                PullRequestMarker base = pullRequest.getBase();
                int id = getIssue().getIssue().getNumber();
                String summary = getIssue().getSummary();
                // commits
                List<RepositoryCommit> commits = repository.getCommits(id);
                commitsPanel.removeAllCommits();
                commitsCollapsibleSectionPanel.setLabel(Bundle.GitHubIssuePanel_commit_count(commits.size()));
                for (RepositoryCommit commit : commits) {
                    Icon commiterIcon = cache.getUserIcon(commit.getCommitter());
                    commitsPanel.addCommit(commit.getCommit(), commiterIcon);
                }
                // files changed
                List<CommitFile> pullRequestsFiles = repository.getPullRequestsFiles(issue.getNumber());
                // NOI18N
                filesChangedPanel.setDisplayName(String.format("[Diff] #%s - %s", id, summary));
                filesChangedPanel.removeAllFiles();
                for (CommitFile file : pullRequestsFiles) {
                    filesChangedPanel.addFile(file, base);
                }
                filesChangedPanel.setDetails(pullRequest);
                filesChangedcollapsibleSectionPanel.setLabel(Bundle.GitHubIssuePanel_files_changed_count(pullRequestsFiles.size()));
                // mergeable?
                boolean isMergeable = isMergeable();
                mergePanel.setMergeButtonEnabled(isMergeable);
                if (isMergeable) {
                    mergePanel.setCommitMessage(summary);
                }
            }
        }
    }
    // visibility
    setCommentsSectionVisible(isExistingIssue);
    setNewCommentVisible(isExistingIssue);
    setCollaboratorsComponentsVisible(isCollaborator);
    attributesViewPanel.setVisible(isExistingIssue);
    // PR
    commitsCollapsibleSectionPanel.setVisible(isPullRequest);
    filesChangedcollapsibleSectionPanel.setVisible(isPullRequest);
    mergePanel.setVisible(isPullRequest && isCollaborator);
    fireChange();
}
Example 20
Project: enunciate-master  File: EnunciateConfiguration.java View source code
public String readDescription(EnunciateContext context, boolean raw) {
    String descriptionPackage = this.source.getString("description[@package]", null);
    if (descriptionPackage != null) {
        DecoratedPackageElement packageElement = (DecoratedPackageElement) context.getProcessingEnvironment().getElementUtils().getPackageElement(descriptionPackage);
        if (packageElement != null) {
            String docValue = packageElement.getDocValue();
            if (docValue != null) {
                return docValue;
            }
        }
    }
    String description = null;
    String descriptionFile = this.source.getString("description[@file]", null);
    if (descriptionFile != null) {
        description = readFile(descriptionFile);
    }
    String specifiedDescription = this.source.getString("description", null);
    if (specifiedDescription != null) {
        description = specifiedDescription;
    }
    if (description != null && "markdown".equalsIgnoreCase(this.source.getString("description[@format]", "html")) && !raw) {
        description = new PegDownProcessor().markdownToHtml(description);
    }
    return description == null ? this.defaultDescription : description;
}
Example 21
Project: skadi-master  File: PanelUtil.java View source code
private static VBox parseDescriptionFromMarkdown(final String markdown) {
    final VBox result = new VBox();
    final PegDownProcessor processor = new PegDownProcessor(Extensions.STRIKETHROUGH | Extensions.FENCED_CODE_BLOCKS);
    final RootNode rootNode = processor.parseMarkdown(markdown.toCharArray());
    // PanelUtil.visit(rootNode, "");
    final MarkdownVisitor visitor = new MarkdownVisitor();
    visitor.pushNode(result);
    rootNode.accept(visitor);
    result.getStylesheets().add("/styles/markdown.css");
    result.setMaxWidth(200);
    result.layout();
    return result;
}
Example 22
Project: gitblit-slack-plugin-master  File: SlackTicketHook.java View source code
protected String renderMarkdown(String markdown, String repository) {
    if (StringUtils.isEmpty(markdown)) {
        return markdown;
    }
    // extract blockquotes, insert placeholders, and render the blockquotes individually
    final String placeholder = "!!BLOCKQUOTE!!";
    List<String> list = new ArrayList<>();
    StringBuilder sb = new StringBuilder();
    StringBuilder bq = new StringBuilder();
    for (String line : markdown.split("\n")) {
        if (line.length() > 0) {
            if (line.startsWith("> ")) {
                // accumulate blockquotes
                boolean newBQ = bq.length() == 0;
                bq.append(line.substring(2)).append('\n');
                if (newBQ) {
                    // insert a placeholder
                    sb.append(placeholder).append(list.size()).append('\n');
                }
                continue;
            } else if (bq.length() > 0) {
                // render blockquote by itself and reinject blockquote syntax
                String quote = bq.toString();
                String rendered = renderMarkdown(quote, repository);
                bq.setLength(0);
                StringBuilder rsb = new StringBuilder();
                for (String rl : rendered.split("\n")) {
                    rsb.append("> ").append(rl).append('\n');
                }
                list.add(rsb.toString());
            }
        }
        sb.append(line).append('\n');
    }
    String text = sb.toString();
    try {
        IRuntimeManager runtimeManager = GitblitContext.getManager(IRuntimeManager.class);
        String canonicalUrl = runtimeManager.getSettings().getString(Keys.web.canonicalUrl, "https://localhost:8443");
        // emphasize and link mentions
        String mentionReplacement = String.format(" **[@$1](%1s/user/$1)**", canonicalUrl);
        text = text.replaceAll("\\s@([A-Za-z0-9-_]+)", mentionReplacement);
        // link ticket refs
        String ticketReplacement = MessageFormat.format("$1[#$2]({0}/tickets?r={1}&h=$2)$3", canonicalUrl, repository);
        text = text.replaceAll("([\\s,]+)#(\\d+)([\\s,:\\.\\n])", ticketReplacement);
        // link commit shas
        int shaLen = settings.getInteger(Keys.web.shortCommitIdLength, 6);
        String commitPattern = MessageFormat.format("\\s([A-Fa-f0-9]'{'{0}'}')([A-Fa-f0-9]'{'{1}'}')", shaLen, 40 - shaLen);
        String commitReplacement = String.format(" [`$1`](%1$s/commit\\?r=%2$s&h=$1$2)", canonicalUrl, repository);
        text = text.replaceAll(commitPattern, commitReplacement);
        PegDownProcessor pd = new PegDownProcessor(ALL & ~SMARTYPANTS);
        RootNode astRoot = pd.parseMarkdown(text.toCharArray());
        String slackMarkup = new SlackMarkupSerializer().toHtml(astRoot);
        slackMarkup = slackMarkup.replace("<pre><code>", "```\n");
        slackMarkup = slackMarkup.replace("</code></pre>", "```\n");
        // re-insert blockquotes
        for (int i = 0; i < list.size(); i++) {
            String quote = list.get(i);
            slackMarkup = slackMarkup.replace(placeholder + i, quote);
        }
        return slackMarkup;
    } catch (ParsingTimeoutException e) {
        log.error(null, e);
        return markdown;
    }
}
Example 23
Project: literate-api-master  File: MarkdownProjectModelBuilder.java View source code
/**
         * Parses the model.
         *
         * @param repository the repository.
         * @param filePath   the file to parse.
         * @return the model.
         * @throws IOException when things go wrong.
         */
private ProjectModel parseProjectModel(ProjectRepository repository, String filePath) throws IOException, ProjectModelValidationException {
    InputStream stream = repository.get(filePath);
    try {
        char[] chars = IOUtils.toCharArray(stream);
        RootNode document = chars.length < minLength ? null : new PegDownProcessor(GITHUB).parseMarkdown(chars);
        ProjectModel.Builder builder = ProjectModel.builder();
        if (document != null && !document.getChildren().isEmpty()) {
            Iterator<Node> iterator = document.getChildren().iterator();
            consumeEnvironmentSection(iterator, builder);
            iterator = document.getChildren().iterator();
            if (discardTo(iterator, isBuildHeader)) {
                consumeBuild(iterator, builder);
            }
            for (Map.Entry<String, Matcher<Node>> entry : isTaskHeader.entrySet()) {
                iterator = document.getChildren().iterator();
                if (discardTo(iterator, entry.getValue())) {
                    consumeTask(iterator, builder, entry.getKey());
                }
            }
        }
        ProjectModel model;
        boolean isFallbackFile = FALLBACK_FILE.equals(filePath);
        try {
            model = builder.build();
        } catch (ProjectModelBuildingException e) {
            if (!isFallbackFile) {
                model = null;
            } else {
                throw new ProjectModelValidationException("Unable to turn " + filePath + " into a valid model", e);
            }
        }
        if (model == null || model.getBuild().getCommands().isEmpty() && model.getTaskIds().isEmpty()) {
            if (!isFallbackFile && repository.isFile(FALLBACK_FILE)) {
                // try the fall-back
                return parseProjectModel(repository, FALLBACK_FILE);
            }
            StringBuilder sb = new StringBuilder();
            sb.append("Unable to turn " + filePath + " into a valid model. Please check that it contains a valid build section.\n");
            sb.append("Valid build sections include :\n");
            sb.append("- verbatim (starts by 4 spaces or tab)\n");
            sb.append("- bullet list (starts by *, +, -, or a number)\n");
            sb.append("- definition list");
            throw new ProjectModelValidationException(sb.toString());
        }
        return model;
    } finally {
        IOUtils.closeQuietly(stream);
    }
}
Example 24
Project: markdown-page-generator-plugin-master  File: MdPageGeneratorMojo.java View source code
/**
     * Going through list of DTOs and parsing the markdown into HTML.
     * Add header and footer to the big String.
     *
     * @throws MojoExecutionException Unable to write file
     */
private void processMarkdown(List<MarkdownDTO> markdownDTOs, int options) throws MojoExecutionException {
    getLog().debug("Process Markdown");
    getLog().debug("inputEncoding: '" + getInputEncoding() + "', outputEncoding: '" + getOutputEncoding() + "'");
    getLog().debug("parsingTimeout: " + getParsingTimeoutInMillis() + " ms");
    getLog().debug("applyFiltering: " + applyFiltering);
    for (MarkdownDTO dto : markdownDTOs) {
        getLog().debug("dto: " + dto);
        try {
            String headerHtml = "";
            String footerHtml = "";
            try {
                if (StringUtils.isNotEmpty(headerHtmlFile)) {
                    headerHtml = FileUtils.readFileToString(new File(headerHtmlFile), getInputEncoding());
                    headerHtml = addTitleToHtmlFile(headerHtml, dto.title);
                    headerHtml = replaceVariables(headerHtml, dto.substitutes);
                    headerHtml = updateRelativePaths(headerHtml, dto.folderDepth);
                }
                if (StringUtils.isNotEmpty(footerHtmlFile)) {
                    footerHtml = FileUtils.readFileToString(new File(footerHtmlFile), getInputEncoding());
                    footerHtml = replaceVariables(footerHtml, dto.substitutes);
                    footerHtml = updateRelativePaths(footerHtml, dto.folderDepth);
                }
            } catch (FileNotFoundException e) {
                if (failIfFilesAreMissing) {
                    throw e;
                } else {
                    getLog().warn("header and/or footer file is missing.");
                    headerHtml = "";
                    footerHtml = "";
                }
            } catch (Exception e) {
                throw new MojoExecutionException("Error while processing header/footer: " + e.getMessage(), e);
            }
            String markdown = FileUtils.readFileToString(dto.markdownFile, getInputEncoding());
            markdown = replaceVariables(markdown, dto.substitutes);
            // getLog().debug(markdown);
            PegDownProcessor pegDownProcessor = new PegDownProcessor(options, getParsingTimeoutInMillis());
            String markdownAsHtml;
            if (transformRelativeMarkdownLinks) {
                markdownAsHtml = pegDownProcessor.markdownToHtml(markdown, new MDToHTMLExpLinkRender(inputFileExtension));
            } else {
                markdownAsHtml = pegDownProcessor.markdownToHtml(markdown);
            }
            StringBuilder data = new StringBuilder();
            data.append(headerHtml);
            data.append(markdownAsHtml);
            data.append(footerHtml);
            FileUtils.writeStringToFile(dto.htmlFile, data.toString(), getOutputEncoding());
        } catch (MojoExecutionException e) {
            throw e;
        } catch (IOException e) {
            getLog().error("Error : " + e.getMessage(), e);
            throw new MojoExecutionException("Unable to write file " + e.getMessage(), e);
        }
    }
}
Example 25
Project: oj_web-master  File: Markup.java View source code
public static String fromMarkdown(String mdString) {
    if (mdString == null)
        mdString = "";
    PegDownProcessor processor = new PegDownProcessor(Extensions.FENCED_CODE_BLOCKS);
    return processor.markdownToHtml(mdString);
}
Example 26
Project: akanke-master  File: PegdownConfig.java View source code
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public PegDownProcessor pegDownProcessor() {
    return new PegDownProcessor();
}
Example 27
Project: MarkdownPapers-benchmark-master  File: PegdownDriver.java View source code
@Override
public void transform() {
    PegDownProcessor parser = new PegDownProcessor();
    String output = parser.markdownToHtml(content);
}
Example 28
Project: annotated-spring-master  File: Episode.java View source code
public String getNotesHtml() {
    String html = new PegDownProcessor(Extensions.TABLES).markdownToHtml(notes);
    html = html.replaceAll("<table>", "<table class=\"table\">");
    return html;
}
Example 29
Project: handlebars.java-master  File: MarkdownHelper.java View source code
@Override
public Object apply(final Object context, final Options options) throws IOException {
    if (options.isFalsy(context)) {
        return "";
    }
    String markdown = context.toString();
    PegDownProcessor processor = new PegDownProcessor();
    return new Handlebars.SafeString(processor.markdownToHtml(markdown));
}
Example 30
Project: moxie-master  File: MarkdownUtils.java View source code
/**
	 * Returns the html version of the markdown source text.
	 *
	 * @param markdown
	 * @return html version of markdown text
	 * @throws java.text.ParseException
	 */
public static String transformMarkdown(String markdown, LinkRenderer linkRenderer) {
    PegDownProcessor pd = new PegDownProcessor(ALL & ~SMARTYPANTS);
    String html = pd.markdownToHtml(markdown, linkRenderer == null ? new LinkRenderer() : linkRenderer);
    return html;
}
Example 31
Project: rust-netbeans-master  File: RustElementDocumentation.java View source code
private String renderMarkdownAsHtml(String markdown) {
    return new PegDownProcessor().markdownToHtml(markdown);
}
Example 32
Project: allure1-master  File: TextUtils.java View source code
public static String processMarkdown(String rawText) {
    return new PegDownProcessor(Extensions.ALL + Extensions.SUPPRESS_ALL_HTML).markdownToHtml(rawText);
}
Example 33
Project: Intellij-Plugin-master  File: MarkdownPreviewEditor.java View source code
private PegDownProcessor initProcessor() {
    MarkdownExtensions markdownExtensions = new MarkdownExtensions();
    return new PegDownProcessor(markdownExtensions.getExtensionsValue(), markdownExtensions.getParsingTimeout());
}
Example 34
Project: NoticEditor-master  File: HtmlExportStrategy.java View source code
public void setProcessor(PegDownProcessor processor) {
    this.processor = processor;
}
Example 35
Project: aokp-gerrit-master  File: MarkdownFormatter.java View source code
private RootNode parseMarkdown(String md) {
    return new PegDownProcessor(ALL & ~(HARDWRAPS)).parseMarkdown(md.toCharArray());
}
Example 36
Project: gerrit-master  File: MarkdownFormatter.java View source code
private RootNode parseMarkdown(String md) {
    int options = ALL & ~(HARDWRAPS);
    if (suppressHtml) {
        options |= SUPPRESS_ALL_HTML;
    }
    return new PegDownProcessor(options).parseMarkdown(md.toCharArray());
}
Example 37
Project: ese2010-team3-master  File: Tools.java View source code
/**
	 * Convert Markdown to HTML content (in an amazingly unoptimized way)
	 * 
	 * @param content
	 *            some Markdown content
	 * @return that content in plain and sanitized HTML (XSS safe!)
	 */
public static String markdownToHtml(String content) {
    // Markdown processor for content that's already HTML
    if (content.startsWith("<h3>"))
        return Jsoup.clean(content, Whitelist.basic());
    return Jsoup.clean(new PegDownProcessor().markdownToHtml(content), Whitelist.basic());
}
Example 38
Project: jblog-master  File: BlogUtil.java View source code
/**
    * 把markdown转�html
    * @param content
    * @return
    */
public static String markDownToHtml(String content) {
    PegDownProcessor pegDownProcessor = new PegDownProcessor(Extensions.ALL_OPTIONALS | Extensions.ALL_WITH_OPTIONALS, 5000);
    return pegDownProcessor.markdownToHtml(content);
}
Example 39
Project: documentr-master  File: MarkdownProcessor.java View source code
private RootNode parse(String markdown) {
    Parser parser = Parboiled.createParser(DocumentrParser.class);
    PegDownProcessor proc = new PegDownProcessor(parser);
    RootNode rootNode = proc.parseMarkdown(markdown.toCharArray());
    fixParaNodes(rootNode);
    return rootNode;
}
Example 40
Project: structr-master  File: Content.java View source code
@Override
protected PegDownProcessor initialValue() {
    return new PegDownProcessor(Parser.ALL);
}
Example 41
Project: crushpaper-master  File: Servlet.java View source code
@Override
protected PegDownProcessor initialValue() {
    return new PegDownProcessor();
}