Search in sources :

Example 16 with Format

use of org.jdom.output.Format 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 17 with Format

use of org.jdom.output.Format in project vcell by virtualcell.

the class BiomodelsDB_TestSuite method writeSupportedModelsReport.

public static Document writeSupportedModelsReport(File supportInfoDir, File saveSupportedXMLPathname) throws Exception {
    if (!supportInfoDir.isDirectory()) {
        throw new IllegalArgumentException("File " + supportInfoDir.getAbsolutePath() + " must be a directory.");
    }
    File[] xmlReportFiles = supportInfoDir.listFiles(new FileFilter() {

        public boolean accept(File pathname) {
            if (pathname.isFile()) {
                if (pathname.getName().endsWith("_report.xml")) {
                    return true;
                }
            }
            return false;
        }
    });
    Document supportedDocument = new Document(new Element("Supported_BioModelsNet"));
    List<Element> supportedElements = new ArrayList<Element>();
    for (int i = 0; i < xmlReportFiles.length; i++) {
        byte[] xmlBytes = new byte[(int) xmlReportFiles[i].length()];
        FileInputStream fis = new FileInputStream(xmlReportFiles[i]);
        BufferedInputStream bis = new BufferedInputStream(fis);
        DataInputStream dis = new DataInputStream(bis);
        dis.readFully(xmlBytes);
        dis.close();
        Document document = XmlUtil.stringToXML(new String(xmlBytes), null);
        Element bioModelElement = document.getRootElement().getChild(BioModelsNetPanel.BIOMODELINFO_ELEMENT_NAME);
        Attribute supportedAttribute = bioModelElement.getAttribute(BioModelsNetPanel.SUPPORTED_ATTRIBUTE_NAME);
        if (supportedAttribute.getBooleanValue()) {
            Element newBioModelElement = new Element(BioModelsNetPanel.BIOMODELINFO_ELEMENT_NAME);
            @SuppressWarnings("unchecked") List<Attribute> attrList = bioModelElement.getAttributes();
            Iterator<Attribute> iterAttr = attrList.iterator();
            while (iterAttr.hasNext()) {
                newBioModelElement.setAttribute((Attribute) iterAttr.next().clone());
            }
            supportedElements.add(newBioModelElement);
        }
    }
    // Collections.sort(supportedElements, new ElementComparer());
    Element root = supportedDocument.getRootElement();
    for (Element e : supportedElements) {
        root.addContent(e);
    }
    if (saveSupportedXMLPathname != null) {
        try (FileWriter fw = new FileWriter(saveSupportedXMLPathname.getAbsolutePath())) {
            Format format = Format.getPrettyFormat();
            XMLOutputter out = new XMLOutputter(format);
            out.output(supportedDocument, fw);
        }
    }
    return supportedDocument;
}
Also used : XMLOutputter(org.jdom.output.XMLOutputter) Attribute(org.jdom.Attribute) Element(org.jdom.Element) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) Document(org.jdom.Document) DataInputStream(java.io.DataInputStream) FileInputStream(java.io.FileInputStream) Format(org.jdom.output.Format) BufferedInputStream(java.io.BufferedInputStream) FileFilter(java.io.FileFilter) File(java.io.File)

Example 18 with Format

use of org.jdom.output.Format in project vcell by virtualcell.

the class NFsimXMLWriter method getListOfObservables.

private static Element getListOfObservables(MathDescription mathDesc) throws SolverException {
    Element listOfObservablesElement = new Element("ListOfObservables");
    int observableIndex = 0;
    Enumeration<Variable> enum1 = mathDesc.getVariables();
    while (enum1.hasMoreElements()) {
        Variable var = enum1.nextElement();
        if (var instanceof ParticleObservable) {
            ParticleObservable particleObservable = (ParticleObservable) var;
            Element observableElement = new Element("Observable");
            String observableId = "O" + (observableIndex + 1);
            observableElement.setAttribute("id", observableId);
            observableElement.setAttribute("name", particleObservable.getName());
            observableElement.setAttribute("type", particleObservable.getType().getText());
            Element listOfPatterns = getParticleSpeciesPatternList(observableId, particleObservable);
            observableElement.addContent(listOfPatterns);
            listOfObservablesElement.addContent(observableElement);
            observableIndex++;
        }
    }
    Format format = Format.getPrettyFormat();
    XMLOutputter outp = new XMLOutputter(format);
    String sOurs = outp.outputString(listOfObservablesElement);
    return listOfObservablesElement;
}
Also used : XMLOutputter(org.jdom.output.XMLOutputter) Variable(cbit.vcell.math.Variable) Format(org.jdom.output.Format) Element(org.jdom.Element) ParticleObservable(cbit.vcell.math.ParticleObservable)

Example 19 with Format

use of org.jdom.output.Format in project vcell by virtualcell.

the class VisMeshUtils method writePointDataToVtu.

public static void writePointDataToVtu(File inputMeshFile, String dataName, double[] data, File outputMeshFile) throws IOException {
    Document meshDocument = XmlUtil.readXML(inputMeshFile);
    addPointDataToVtuXml(meshDocument, dataName, data);
    FileWriter fw = null;
    try {
        fw = new FileWriter(outputMeshFile);
        XMLOutputter xmlOut = new XMLOutputter();
        Format f = Format.getRawFormat();
        f.setLineSeparator("\n");
        f.setOmitEncoding(true);
        f.setExpandEmptyElements(true);
        xmlOut.setFormat(f);
        xmlOut.output(meshDocument, fw);
    } finally {
        if (fw != null) {
            fw.close();
        }
    }
}
Also used : XMLOutputter(org.jdom.output.XMLOutputter) Format(org.jdom.output.Format) FileWriter(java.io.FileWriter) Document(org.jdom.Document)

Example 20 with Format

use of org.jdom.output.Format in project che by eclipse.

the class EffectivePomWriter method addMavenNamespace.

/**
     * method from org.apache.maven.plugins.help.AbstractEffectiveMojo
     * Add a Pom/Settings namespaces to the effective XML content.
     *
     * @param effectiveXml not null the effective POM or Settings
     * @param isPom if <code>true</code> add the Pom xsd url, otherwise add the settings xsd url.
     * @return the content of the root element, i.e. &lt;project/&gt; or &lt;settings/&gt; with the Maven namespace or
     *         the original <code>effective</code> if an error occurred.
     * @see #POM_XSD_URL
     * @see #SETTINGS_XSD_URL
     */
protected static String addMavenNamespace(String effectiveXml, boolean isPom) {
    SAXBuilder builder = new SAXBuilder();
    try {
        Document document = builder.build(new StringReader(effectiveXml));
        Element rootElement = document.getRootElement();
        // added namespaces
        Namespace pomNamespace = Namespace.getNamespace("", "http://maven.apache.org/POM/4.0.0");
        rootElement.setNamespace(pomNamespace);
        Namespace xsiNamespace = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        rootElement.addNamespaceDeclaration(xsiNamespace);
        if (rootElement.getAttribute("schemaLocation", xsiNamespace) == null) {
            rootElement.setAttribute("schemaLocation", "http://maven.apache.org/POM/4.0.0 " + (isPom ? POM_XSD_URL : SETTINGS_XSD_URL), xsiNamespace);
        }
        ElementFilter elementFilter = new ElementFilter(Namespace.getNamespace(""));
        for (Iterator<?> i = rootElement.getDescendants(elementFilter); i.hasNext(); ) {
            Element e = (Element) i.next();
            e.setNamespace(pomNamespace);
        }
        StringWriter w = new StringWriter();
        Format format = Format.getPrettyFormat();
        XMLOutputter out = new XMLOutputter(format);
        out.output(document.getRootElement(), w);
        return w.toString();
    } catch (JDOMException e) {
        return effectiveXml;
    } catch (IOException e) {
        return effectiveXml;
    }
}
Also used : XMLOutputter(org.jdom.output.XMLOutputter) SAXBuilder(org.jdom.input.SAXBuilder) Format(org.jdom.output.Format) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) StringWriter(java.io.StringWriter) Element(org.jdom.Element) ElementFilter(org.jdom.filter.ElementFilter) StringReader(java.io.StringReader) IOException(java.io.IOException) Document(org.jdom.Document) JDOMException(org.jdom.JDOMException) Namespace(org.jdom.Namespace)

Aggregations

Format (org.jdom.output.Format)45 XMLOutputter (org.jdom.output.XMLOutputter)40 Document (org.jdom.Document)20 Element (org.jdom.Element)20 StringWriter (java.io.StringWriter)11 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)6 Namespace (org.jdom.Namespace)6 Writer (java.io.Writer)5 SAXBuilder (org.jdom.input.SAXBuilder)5 DateFormat (java.text.DateFormat)4 SimpleDateFormat (java.text.SimpleDateFormat)4 JDOMException (org.jdom.JDOMException)4 ApsSystemException (com.agiletec.aps.system.exception.ApsSystemException)3 File (java.io.File)3 FileWriter (java.io.FileWriter)3 StringReader (java.io.StringReader)3 List (java.util.List)3 TreeMap (java.util.TreeMap)3 StudyBean (org.akaza.openclinica.bean.managestudy.StudyBean)3