Search in sources :

Example 6 with Document

use of org.jdom.Document in project libresonic by Libresonic.

the class PodcastService method doRefreshChannel.

@SuppressWarnings({ "unchecked" })
private void doRefreshChannel(PodcastChannel channel, boolean downloadEpisodes) {
    InputStream in = null;
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        channel.setStatus(PodcastStatus.DOWNLOADING);
        channel.setErrorMessage(null);
        podcastDao.updateChannel(channel);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(// 2 minutes
        2 * 60 * 1000).setSocketTimeout(// 10 minutes
        10 * 60 * 1000).build();
        HttpGet method = new HttpGet(channel.getUrl());
        method.setConfig(requestConfig);
        try (CloseableHttpResponse response = client.execute(method)) {
            in = response.getEntity().getContent();
            Document document = new SAXBuilder().build(in);
            Element channelElement = document.getRootElement().getChild("channel");
            channel.setTitle(StringUtil.removeMarkup(channelElement.getChildTextTrim("title")));
            channel.setDescription(StringUtil.removeMarkup(channelElement.getChildTextTrim("description")));
            channel.setImageUrl(getChannelImageUrl(channelElement));
            channel.setStatus(PodcastStatus.COMPLETED);
            channel.setErrorMessage(null);
            podcastDao.updateChannel(channel);
            downloadImage(channel);
            refreshEpisodes(channel, channelElement.getChildren("item"));
        }
    } catch (Exception x) {
        LOG.warn("Failed to get/parse RSS file for Podcast channel " + channel.getUrl(), x);
        channel.setStatus(PodcastStatus.ERROR);
        channel.setErrorMessage(getErrorMessage(x));
        podcastDao.updateChannel(channel);
    } finally {
        IOUtils.closeQuietly(in);
    }
    if (downloadEpisodes) {
        for (final PodcastEpisode episode : getEpisodes(channel.getId())) {
            if (episode.getStatus() == PodcastStatus.NEW && episode.getUrl() != null) {
                downloadEpisode(episode);
            }
        }
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) SAXBuilder(org.jdom.input.SAXBuilder) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) Element(org.jdom.Element) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Document(org.jdom.Document) PodcastEpisode(org.libresonic.player.domain.PodcastEpisode)

Example 7 with Document

use of org.jdom.Document in project OpenClinica by OpenClinica.

the class FormBuilderTest method createTable.

public String createTable() {
    Element root = new Element("table");
    root.setAttribute("border", "0");
    Document doc = new Document(root);
    Element thead = new Element("thead");
    Element th = new Element("th");
    th.addContent("A header");
    th.setAttribute("class", "aka_header_border");
    thead.addContent(th);
    Element th2 = new Element("th");
    th2.addContent("Another header");
    th2.setAttribute("class", "aka_header_border");
    thead.addContent(th2);
    root.addContent(thead);
    Element tr1 = new Element("tr");
    Element td1 = new Element("td");
    td1.setAttribute("valign", "top");
    td1.setAttribute("class", "cellBorders");
    td1.setText("cell contents");
    tr1.addContent(td1);
    root.addContent(tr1);
    XMLOutputter outp = new XMLOutputter();
    Format format = Format.getPrettyFormat();
    format.setOmitDeclaration(true);
    outp.setFormat(format);
    Writer writer = new StringWriter();
    try {
        outp.output(doc, writer);
    } catch (IOException e) {
        // To change body of catch statement use
        e.printStackTrace();
    // File | Settings | File Templates.
    }
    return writer.toString();
}
Also used : XMLOutputter(org.jdom.output.XMLOutputter) Format(org.jdom.output.Format) StringWriter(java.io.StringWriter) Element(org.jdom.Element) IOException(java.io.IOException) Document(org.jdom.Document) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Example 8 with Document

use of org.jdom.Document in project OpenClinica by OpenClinica.

the class HorizontalFormBuilder method createMarkup.

@Override
public String createMarkup() {
    // If the CRF is involved with ViewDataEntry and already has
    // data associated with it, pass on the responsibility to another object
    ViewPersistanceHandler persistanceHandler = new ViewPersistanceHandler();
    if (isDataEntry) {
        List<ItemDataBean> itemDataBeans;
        persistanceHandler = new ViewPersistanceHandler();
        itemDataBeans = persistanceHandler.fetchPersistedData(sectionBean.getId(), eventCRFbean.getId());
        if (!itemDataBeans.isEmpty()) {
            hasDbFormValues = true;
        }
        persistanceHandler.setItemDataBeans(itemDataBeans);
    }
    // Keep track of whether a group has any repeat behavior; true or false
    boolean repeatFlag;
    //Should the table have dark borders?
    boolean hasBorders = false;
    if (sectionBean != null) {
        hasBorders = (sectionBean.getBorders() > 0);
    }
    // The CellFactory object that generates the content for HTML table TD
    // cells.
    CellFactory cellFactory = new CellFactory();
    RepeatManager repeatManager = new RepeatManager();
    FormBeanUtil formUtil = new FormBeanUtil();
    ViewBuilderUtil builderUtil = new ViewBuilderUtil();
    // The number of repeating table rows that the group will start with.
    int repeatNumber;
    // the div tag that will be the root
    Element divRoot = new Element("div");
    divRoot.setAttribute("id", "tableRoot");
    Document doc = new Document();
    ProcessingInstruction pi = new ProcessingInstruction(Result.PI_DISABLE_OUTPUT_ESCAPING, "");
    doc.addContent(pi);
    doc.setRootElement(divRoot);
    // Show the section's title, subtitle, or instructions
    builderUtil.showTitles(divRoot, this.getSectionBean());
    // One way to generate an id for the repeating tbody or tr element
    int uniqueId = 0;
    // The tabindex attribute for select and input tags
    int tabindex = tabindexSeed;
    boolean hasDiscrepancyMgt = false;
    StudyBean studBean = this.getStudyBean();
    if (studBean != null && studBean.getStudyParameterConfig().getDiscrepancyManagement().equalsIgnoreCase("true")) {
        hasDiscrepancyMgt = true;
    }
    // its list of DisplayItemBeans
    for (DisplayItemGroupBean displayItemGroup : this.displayItemGroups) {
        List<DisplayItemBean> currentDisplayItems = displayItemGroup.getItems();
        // A Map that contains persistent (stored in a database), repeated
        // rows
        // in a matrix type table
        // The Map index is the Item id of the first member of the row; the
        // value is a List
        // of item beans that make up the row
        SortedMap<Integer, List<ItemDataBean>> ordinalItemDataMap = new TreeMap<Integer, List<ItemDataBean>>();
        // Is this a persistent matrix table and does it already have
        // repeated rows
        // in the database?
        boolean hasStoredRepeatedRows = false;
        boolean unGroupedTable = displayItemGroup.getItemGroupBean().getName().equalsIgnoreCase(BeanFactory.UNGROUPED) || !displayItemGroup.getGroupMetaBean().isRepeatingGroup();
        // Load any database values into the DisplayItemBeans
        if (hasDbFormValues) {
            currentDisplayItems = persistanceHandler.loadDataIntoDisplayBeans(currentDisplayItems, (!unGroupedTable));
            /*
                 * The highest number ordinal represents how many repeated rows
                 * there are. If the ordinal in ItemDataBeans > 1, then we know
                 * that the group has persistent repeated rows. Get a structure
                 * that maps each ordinal (i.e., >= 2) to its corresponding List
                 * of ItemDataBeans. Then iterate the existing DisplayBeans,
                 * with the number of new rows equaling the highest ordinal
                 * number minus 1. For example, in a List of ItemDataBeans, if
                 * the highest ordinal property among these beans is 5, then the
                 * matrix table has 4 repeated rows from the database. Provide
                 * each new row with its values by using the ItemDataBeans.
                 */
            if (!unGroupedTable && persistanceHandler.hasPersistentRepeatedRows(currentDisplayItems)) {
                hasStoredRepeatedRows = true;
                // if the displayitems contain duplicate item ids, then
                // these duplicates
                // represent repeated rows. Separate them into a Map of new
                // rows that
                // will be appended to the HTML table.
                ordinalItemDataMap = persistanceHandler.handleExtraGroupRows();
            }
        }
        // end if hasDbFormValues
        // Does the table have a group header?
        String groupHeader = displayItemGroup.getGroupMetaBean().getHeader();
        boolean hasGroupHeader = groupHeader != null && groupHeader.length() > 0;
        // Add group header, if there is one
        if (hasGroupHeader) {
            Element divGroupHeader = new Element("div");
            // necessary?
            divGroupHeader.setAttribute("class", "aka_group_header");
            Element strong = new Element("strong");
            strong.setAttribute("style", "float:none");
            strong.addContent(groupHeader);
            divGroupHeader.addContent(strong);
            divRoot.addContent(divGroupHeader);
        }
        // This group represents "orphaned" items (those without a group) if
        // the FormGroupBean has a group label of UNGROUPED
        Element orphanTable = null;
        if (unGroupedTable) {
            orphanTable = formUtil.createXHTMLTableFromNonGroup(currentDisplayItems, tabindex, hasDiscrepancyMgt, hasDbFormValues, false);
            // We have to track the point the tabindex has reached here
            // The tabindex will increment by the size of the
            // displayItemGroup List
            tabindex += currentDisplayItems.size();
            divRoot.addContent(orphanTable);
            continue;
        }
        // end if unGroupedTable
        uniqueId++;
        String repeatParentId = "repeatParent" + uniqueId;
        repeatNumber = displayItemGroup.getGroupMetaBean().getRepeatNum();
        // If the form has repeat behavior, this number is > 0
        // Do not allow repeat numbers < 1
        //            repeatNumber = repeatNumber < 1 ? 1 : repeatNumber;
        // And a limit of 12
        repeatNumber = repeatNumber > 12 ? 12 : repeatNumber;
        // This is always true during this iteration
        repeatFlag = displayItemGroup.getGroupMetaBean().isRepeatingGroup();
        Element table = createTable();
        // add the thead element
        Element thead = this.createThead();
        table.addContent(thead);
        divRoot.addContent(table);
        // Add the first row for the th tags
        Element thRow = new Element("tr");
        thead.addContent(thRow);
        // Does this group involve a Horizontal checkbox or radio button?
        boolean hasResponseLayout = builderUtil.hasResponseLayout(currentDisplayItems);
        // add th elements to the thead element
        // We have to create an extra thead column for the Remove Row
        // button, if
        // the table involves repeating rows
        List<Element> thTags = repeatFlag ? createTheadContentsFromDisplayItems(currentDisplayItems, true, hasBorders) : createTheadContentsFromDisplayItems(currentDisplayItems, false, hasBorders);
        for (Element el : thTags) {
            thRow.addContent(el);
        }
        if (hasResponseLayout) {
            Element thRowSubhead = new Element("tr");
            thead.addContent(thRowSubhead);
            addResponseLayoutRow(thRowSubhead, currentDisplayItems, hasBorders);
        }
        // Create the tbody tag
        Element tbody;
        Element row;
        Element td;
        tbody = this.createTbody();
        // The table adds the tbody to the XML or markup
        table.addContent(tbody);
        // For each row in the table
        // for (int i = 1; i <= repeatNumber; i++) {
        row = new Element("tr");
        // If the group has repeat behavior and repeats row by row,
        // then the
        // repetition model type attributes have to be added to the tr tag
        int repeatMax = displayItemGroup.getGroupMetaBean().getRepeatMax();
        // Make sure repeatMax >= 1
        repeatMax = repeatMax < 1 ? 40 : repeatMax;
        if (repeatFlag && !(isDataEntry && hasStoredRepeatedRows)) {
            row = repeatManager.addParentRepeatAttributes(row, repeatParentId, repeatNumber, repeatMax);
        }
        // The content for the table cells. For each item...
        for (DisplayItemBean displayBean : currentDisplayItems) {
            // What type of input: text, radio, checkbox, etc.?
            String responseName = displayBean.getMetadata().getResponseSet().getResponseType().getName();
            // is radio or checkbox, and the response_layout is horizontal
            if (displayBean.getMetadata().getResponseLayout().equalsIgnoreCase("horizontal") && (responseName.equalsIgnoreCase("checkbox") || responseName.equalsIgnoreCase("radio"))) {
                Element[] elements = cellFactory.createCellContentsForChecks(responseName, displayBean, displayBean.getMetadata().getResponseSet().getOptions().size(), ++tabindex, false, false);
                for (Element el : elements) {
                    el = builderUtil.setClassNames(el);
                    if (hasBorders) {
                        this.createDarkBorders(el);
                    }
                    if (repeatFlag) {
                        el = repeatManager.addChildRepeatAttributes(el, repeatParentId, displayBean.getItem().getId(), null);
                    }
                    row.addContent(el);
                }
                // move to the next item
                continue;
            }
            td = new Element("td");
            td = builderUtil.setClassNames(td);
            if (hasBorders) {
                this.createDarkBorders(td);
            }
            // Create cells within each row
            td = cellFactory.createCellContents(td, responseName, displayBean, ++tabindex, hasDiscrepancyMgt, hasDbFormValues, false);
            if (repeatFlag) {
                td = repeatManager.addChildRepeatAttributes(td, repeatParentId, displayBean.getItem().getId(), null);
            }
            row.addContent(td);
        }
        // We need an extra cell for holding the "Remove Row" button
        if (repeatFlag) {
            builderUtil.addRemoveRowControl(row, repeatParentId, hasBorders);
        }
        tbody.addContent(row);
        if (hasStoredRepeatedRows) {
            List<Element> storedRepeatedRows = builderUtil.generatePersistentMatrixRows(ordinalItemDataMap, currentDisplayItems, tabindex, repeatParentId, hasDiscrepancyMgt, false, hasBorders);
            // add these new rows to the table
            for (Element newRow : storedRepeatedRows) {
                tbody.addContent(newRow);
            }
        }
        // repeaters
        if (repeatFlag) {
            builderUtil.createAddRowControl(tbody, repeatParentId, (builderUtil.calcNumberofColumns(displayItemGroup) + 1), hasBorders);
        }
    }
    // end for displayFormGroup
    XMLOutputter outp = new XMLOutputter();
    Format format = Format.getPrettyFormat();
    format.setOmitDeclaration(true);
    outp.setFormat(format);
    Writer writer = new StringWriter();
    try {
        outp.output(doc, writer);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return writer.toString();
}
Also used : XMLOutputter(org.jdom.output.XMLOutputter) Element(org.jdom.Element) Document(org.jdom.Document) Format(org.jdom.output.Format) StringWriter(java.io.StringWriter) ArrayList(java.util.ArrayList) List(java.util.List) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) IOException(java.io.IOException) TreeMap(java.util.TreeMap) ProcessingInstruction(org.jdom.ProcessingInstruction) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Example 9 with Document

use of org.jdom.Document in project intellij-community by JetBrains.

the class CutCopyPasteSupport method loadComponentsToPaste.

private static boolean loadComponentsToPaste(final GuiEditor editor, final String serializedComponents, final TIntArrayList xs, final TIntArrayList ys, final ArrayList<RadComponent> componentsToPaste) {
    final PsiPropertiesProvider provider = new PsiPropertiesProvider(editor.getModule());
    try {
        //noinspection HardCodedStringLiteral
        final Document document = SAX_BUILDER.build(new StringReader(serializedComponents), "UTF-8");
        final Element rootElement = document.getRootElement();
        if (!rootElement.getName().equals(ELEMENT_SERIALIZED)) {
            return false;
        }
        final List children = rootElement.getChildren();
        for (final Object aChildren : children) {
            final Element e = (Element) aChildren;
            // we need to add component to a container in order to read them
            final LwContainer container = new LwContainer(JPanel.class.getName());
            final String parentLayout = e.getAttributeValue(ATTRIBUTE_PARENT_LAYOUT);
            if (parentLayout != null) {
                container.setLayoutManager(parentLayout);
            }
            final int x = Integer.parseInt(e.getAttributeValue(ATTRIBUTE_X));
            final int y = Integer.parseInt(e.getAttributeValue(ATTRIBUTE_Y));
            xs.add(x);
            ys.add(y);
            final Element componentElement = (Element) e.getChildren().get(0);
            final LwComponent lwComponent = LwContainer.createComponentFromTag(componentElement);
            container.addComponent(lwComponent);
            lwComponent.read(componentElement, provider);
            // pasted components should have no bindings
            FormEditingUtil.iterate(lwComponent, new FormEditingUtil.ComponentVisitor<LwComponent>() {

                public boolean visit(final LwComponent c) {
                    if (c.getBinding() != null && FormEditingUtil.findComponentWithBinding(editor.getRootContainer(), c.getBinding()) != null) {
                        c.setBinding(null);
                    }
                    c.setId(FormEditingUtil.generateId(editor.getRootContainer()));
                    return true;
                }
            });
            final ClassLoader loader = LoaderFactory.getInstance(editor.getProject()).getLoader(editor.getFile());
            final RadComponent radComponent = XmlReader.createComponent(editor, lwComponent, loader, editor.getStringDescriptorLocale());
            componentsToPaste.add(radComponent);
        }
    } catch (Exception e) {
        return false;
    }
    return true;
}
Also used : Element(org.jdom.Element) RadComponent(com.intellij.uiDesigner.radComponents.RadComponent) LwContainer(com.intellij.uiDesigner.lw.LwContainer) Document(org.jdom.Document) StringReader(java.io.StringReader) ArrayList(java.util.ArrayList) TIntArrayList(gnu.trove.TIntArrayList) List(java.util.List) LwComponent(com.intellij.uiDesigner.lw.LwComponent)

Example 10 with Document

use of org.jdom.Document in project intellij-community by JetBrains.

the class FogBugzRepository method getCases.

@SuppressWarnings("unchecked")
private Task[] getCases(String q) throws Exception {
    loginIfNeeded();
    PostMethod method = new PostMethod(getUrl() + "/api.asp");
    method.addParameter("token", myToken);
    method.addParameter("cmd", "search");
    method.addParameter("q", q);
    method.addParameter("cols", "sTitle,fOpen,dtOpened,dtLastUpdated,ixCategory");
    int status = getHttpClient().executeMethod(method);
    if (status != 200) {
        throw new Exception("Error listing cases: " + method.getStatusLine());
    }
    Document document = new SAXBuilder(false).build(method.getResponseBodyAsStream()).getDocument();
    List<Element> errorNodes = XPath.newInstance("/response/error").selectNodes(document);
    if (!errorNodes.isEmpty()) {
        throw new Exception("Error listing cases: " + errorNodes.get(0).getText());
    }
    final XPath commentPath = XPath.newInstance("events/event");
    final List<Element> nodes = (List<Element>) XPath.newInstance("/response/cases/case").selectNodes(document);
    final List<Task> tasks = ContainerUtil.mapNotNull(nodes, (NotNullFunction<Element, Task>) element -> createCase(element, commentPath));
    return tasks.toArray(new Task[tasks.size()]);
}
Also used : XPath(org.jdom.xpath.XPath) SAXBuilder(org.jdom.input.SAXBuilder) TasksIcons(icons.TasksIcons) DatatypeConfigurationException(javax.xml.datatype.DatatypeConfigurationException) Tag(com.intellij.util.xmlb.annotations.Tag) StringUtil(com.intellij.openapi.util.text.StringUtil) Date(java.util.Date) NotNullFunction(com.intellij.util.NotNullFunction) BaseRepository(com.intellij.tasks.impl.BaseRepository) PostMethod(org.apache.commons.httpclient.methods.PostMethod) DatatypeFactory(javax.xml.datatype.DatatypeFactory) ContainerUtil(com.intellij.util.containers.ContainerUtil) BaseRepositoryImpl(com.intellij.tasks.impl.BaseRepositoryImpl) XPath(org.jdom.xpath.XPath) Nullable(org.jetbrains.annotations.Nullable) Document(org.jdom.Document) List(java.util.List) Comparing(com.intellij.openapi.util.Comparing) com.intellij.tasks(com.intellij.tasks) PasswordUtil(com.intellij.openapi.util.PasswordUtil) Logger(com.intellij.openapi.diagnostic.Logger) NotNull(org.jetbrains.annotations.NotNull) Element(org.jdom.Element) javax.swing(javax.swing) SAXBuilder(org.jdom.input.SAXBuilder) PostMethod(org.apache.commons.httpclient.methods.PostMethod) Element(org.jdom.Element) List(java.util.List) Document(org.jdom.Document) DatatypeConfigurationException(javax.xml.datatype.DatatypeConfigurationException)

Aggregations

Document (org.jdom.Document)90 Element (org.jdom.Element)67 IOException (java.io.IOException)40 SAXBuilder (org.jdom.input.SAXBuilder)40 JDOMException (org.jdom.JDOMException)24 File (java.io.File)16 XMLOutputter (org.jdom.output.XMLOutputter)16 ArrayList (java.util.ArrayList)13 List (java.util.List)12 StringReader (java.io.StringReader)10 XPath (org.jdom.xpath.XPath)10 Format (org.jdom.output.Format)9 StringWriter (java.io.StringWriter)8 InputStream (java.io.InputStream)7 NotNull (org.jetbrains.annotations.NotNull)7 Nullable (org.jetbrains.annotations.Nullable)7 Writer (java.io.Writer)5 URL (java.net.URL)5 JDOMUtil.loadDocument (com.intellij.openapi.util.JDOMUtil.loadDocument)4 VirtualFile (com.intellij.openapi.vfs.VirtualFile)4