List of usage examples for javax.xml.parsers DocumentBuilderFactory setFeature
public abstract void setFeature(String name, boolean value) throws ParserConfigurationException;
From source file:org.pentaho.metadata.util.XmiParser.java
/** * Creates an instance of DocumentBuilderFactory class with enabled {@link XMLConstants#FEATURE_SECURE_PROCESSING} property. * Enabling this feature prevents from some XXE attacks (e.g. XML bomb) * See PPP-3506 for more details./* www.j ava2 s . co m*/ * * @throws ParserConfigurationException if feature can't be enabled * */ public static DocumentBuilderFactory createSecureDocBuilderFactory() throws ParserConfigurationException { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); return documentBuilderFactory; }
From source file:org.pentaho.osgi.platform.webjars.utils.RequireJsGenerator.java
public static RequireJsGenerator parsePom(InputStream inputStream) throws Exception { try {// w ww .j av a 2 s . co m byte[] bytes = IOUtils.toByteArray(inputStream); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); Document pom = documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(bytes)); return new RequireJsGenerator(pom); } catch (Exception e) { throw new Exception("Error reading POM", e); } }
From source file:org.pentaho.reporting.engine.classic.extensions.datasources.xpath.LegacyXPathTableModel.java
private DocumentBuilderFactory calculateDocumentBuilderFactory(final Configuration configuration) throws ParserConfigurationException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setXIncludeAware(false);//from w ww.j a va 2s .co m if (!"true".equals(configuration.getConfigProperty(XPATH_ENABLE_DTDS))) { dbf.setFeature(DISALLOW_DOCTYPE_DECL, true); } return dbf; }
From source file:org.sakaiproject.citation.impl.BaseConfigurationService.java
/** * Get a DOM Document builder./*from w w w .jav a2s . c om*/ * @return The DocumentBuilder * @throws DomException */ protected DocumentBuilder getXmlDocumentBuilder() { try { DocumentBuilderFactory factory; factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(false); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); return factory.newDocumentBuilder(); } catch (Exception exception) { m_log.warn("Failed to get XML DocumentBuilder: " + exception); } return null; }
From source file:org.sakaiproject.dav.DavServlet.java
/** * Return JAXP document builder instance. *///from ww w . j av a 2s.c o m protected DocumentBuilder getDocumentBuilder() throws ServletException { DocumentBuilder documentBuilder = null; DocumentBuilderFactory documentBuilderFactory = null; try { documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilderFactory.setExpandEntityReferences(false); documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new ServletException("Sakaidavservlet.jaxpfailed"); } return documentBuilder; }
From source file:org.sakaiproject.dav.DavServlet.java
/** * PROPPATCH Method.//w w w .ja v a 2 s . c om */ @SuppressWarnings("deprecation") protected void doProppatch(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Check that the resource is not locked if (isLocked(req)) { resp.sendError(SakaidavStatus.SC_LOCKED); } // we can't actually do this, but MS requires us to. Say we did. // I'm trying to be as close to valid here, so I generate an OK // for all the properties they tried to set. This is really hairy because // it gets into name spaces. But if we ever try to implement this for real, // we'll have to do this. So might as well start now. // During testing I found by mistake that it's actually OK to send // an empty multistatus return, so I don't actually need all of this stuff. // The big problem is that the properties are typically not in the dav namespace // we build a hash table of namespaces, with the prefix we're going to use // since D: is used for dav, we start with E:, actually D+1 DocumentBuilder documentBuilder = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); documentBuilder = factory.newDocumentBuilder(); } catch (Exception e) { resp.sendError(SakaidavStatus.SC_METHOD_FAILURE); return; } int contentLength = req.getContentLength(); // a list of the properties with the new prefix List<String> props = new ArrayList<String>(); // hash of namespace, prefix Hashtable<String, String> spaces = new Hashtable<String, String>(); // read the xml document if (contentLength > MAX_XML_STREAM_LENGTH) { resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); return; } else if (contentLength > 0) { byte[] byteContent = new byte[contentLength]; InputStream inputStream = req.getInputStream(); int lenRead = 0; try { while (lenRead < contentLength) { int read = inputStream.read(byteContent, lenRead, contentLength - lenRead); if (read <= 0) break; lenRead += read; } } catch (Exception ignore) { } // Parse the input XML to see what they really want if (lenRead > 0) try { // if we got here, "is" is the xml document InputStream is = new ByteArrayInputStream(byteContent, 0, lenRead); Document document = documentBuilder.parse(new InputSource(is)); // Get the root element of the document Element rootElement = document.getDocumentElement(); // find all the property nodes NodeList childList = rootElement.getElementsByTagNameNS("DAV:", "prop"); int nextChar = 1; for (int i = 0; i < childList.getLength(); i++) { // this should be a prop node Node currentNode = childList.item(i); // this should be the actual property NodeList names = currentNode.getChildNodes(); // this should be the name for (int j = 0; j < names.getLength(); j++) { String namespace = names.item(j).getNamespaceURI(); String prefix = spaces.get(namespace); // see if we know about this namespace. If not add it and // generate a prefix if (prefix == null) { prefix = "" + Character.toChars('D' + nextChar)[0]; spaces.put(namespace, prefix); } props.add(prefix + ":" + names.item(j).getLocalName()); } } } catch (Exception ignore) { } } resp.setStatus(SakaidavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); Writer writer = resp.getWriter(); writer.write("<D:multistatus xmlns:D=\"DAV:\""); // dump all the name spaces and their prefix for (String namespace : spaces.keySet()) writer.write(" xmlns:" + spaces.get(namespace) + "=\"" + namespace + "\""); writer.write("><D:response><D:href>" + javax.servlet.http.HttpUtils.getRequestURL(req) + "</D:href>"); // now output properties, claiming we did it for (String pname : props) { writer.write("<D:propstat><D:prop><" + pname + "/></D:prop><D:status>HTTP/1.1 201 OK</D:status></D:propstat>"); } writer.write("</D:response></D:multistatus>"); writer.close(); }
From source file:org.sakaiproject.lessonbuildertool.cc.PrintHandler.java
public void setCCItemXml(Element the_xml, Element resource, AbstractParser parser, CartridgeLoader loader, boolean nopage) { if (log.isDebugEnabled()) { String pageTitle = ""; if (pages.size() >= 1) pageTitle = pages.get(pages.size() - 1).getTitle(); log.debug("\nadd item to page " + pageTitle + " xml: " + the_xml + " title " + (the_xml == null ? "Question Pool" : the_xml.getChildText(CC_ITEM_TITLE, ns.getNs())) + " type " + resource.getAttributeValue(TYPE) + " href " + resource.getAttributeValue(HREF)); }// w w w.jav a 2s . c o m String type = ns.normType(resource.getAttributeValue(TYPE)); boolean isBank = type.equals(QUESTION_BANK); // first question: is this the resource we want to use, or is there are preferable variant? Element variant = resource.getChild(VARIANT, ns.cpx_ns()); Set<String> seen = new HashSet<String>(); while (variant != null) { String variantId = variant.getAttributeValue(IDENTIFIERREF); // prevent loop. If we've seen it, exit if (seen.contains(variantId)) break; seen.add(variantId); variant = null; // to stop loop unless we find a valid next variant Element variantResource = null; if (variantId != null) { Element resourcesNode = manifestXml.getChild(RESOURCES, ns.cc_ns()); if (resourcesNode != null) { List<Element> resources = resourcesNode.getChildren(RESOURCE, ns.cc_ns()); if (resources != null) { for (Element e : resources) { if (variantId.equals(e.getAttributeValue(IDENTIFIER))) { variantResource = e; break; } } } } if (variantResource == null) { // should be impossible. means there was a variant pointing to a non-existent resource } else { // we now have the variant resource. Only use it if we recognize the type String variantType = ns.normType(variantResource.getAttributeValue(TYPE)); // if we recognize the type, use the variant. By definition the variant is preferred, so we'll use // it if we recognize it. if (!UNKNOWN.equals(variantType)) { log.debug("Using variant {} of type {} for resource {}", variantResource, variantType, resource); type = variantType; resource = variantResource; } else { log.debug("NOT using variant {} of type {} for resource {}", variantResource, variantType, resource); } // next step for loop. want to check next one even if the source was unusable variant = variantResource.getChild(VARIANT, ns.cpx_ns()); } } } boolean hide = false; Set<String> roles = new HashSet<String>(); // version 1 and higher are different formats, hence a slightly weird test Iterator mdroles = resource.getDescendants(new ElementFilter("intendedEndUserRole", ns.lom_ns())); if (mdroles != null) { while (mdroles.hasNext()) { Element role = (Element) mdroles.next(); Iterator values = role.getDescendants(new ElementFilter("value", ns.lom_ns())); if (values != null) { while (values.hasNext()) { Element value = (Element) values.next(); String roleName = value.getTextTrim(); if (!"Learner".equals(roleName)) { // roles currently only implemented for visible objects. We may want to fix that. if (!hide && !isBank) { usesRole = true; } } if ("Mentor".equals(roleName)) { roles.add(getGroupForRole("Mentor")); } if ("Instructor".equals(roleName)) { roles.add(getGroupForRole("Instructor")); } } } } } if (nopage) hide = true; // for question banks we don't need a current page, as we don't put banks on a page if (pages.size() == 0 && !isBank && !nopage) startCCFolder(null); int top = pages.size() - 1; SimplePage page = (isBank || nopage) ? null : pages.get(top); Integer seq = (isBank || nopage) ? 0 : sequences.get(top); String title = null; if (the_xml == null) title = "Question Pool"; else title = the_xml.getChildText(CC_ITEM_TITLE, ns.getNs()); // metadata is used for special Sakai data boolean inline = false; String mmDisplayType = null; Element metadata = null; if (the_xml != null) metadata = the_xml.getChild(CC_ITEM_METADATA, ns.cc_ns()); if (metadata != null) { metadata = metadata.getChild(LOM_LOM, ns.lom_ns()); } if (metadata != null) { metadata = metadata.getChild(LOM_GENERAL, ns.lom_ns()); } if (metadata != null) { metadata = metadata.getChild(LOM_STRUCTURE, ns.lom_ns()); } if (metadata != null) { List<Element> properties = metadata.getChildren(); Iterator<Element> propertiesIt = properties.iterator(); while (propertiesIt.hasNext()) { Element nameElt = propertiesIt.next(); if (!propertiesIt.hasNext()) break; Element valueElt = propertiesIt.next(); if (!"source".equals(nameElt.getName())) { log.info("first item in structure not source " + nameElt.getName()); break; } if (!"value".equals(valueElt.getName())) { log.info("second item in structure not source " + valueElt.getName()); break; } String name = nameElt.getText(); String value = valueElt.getText(); if (("inline.lessonbuilder.sakaiproject.org".equals(name) && "true".equals(value))) inline = true; else if ("mmDisplayType.lessonbuilder.sakaiproject.org".equals(name)) mmDisplayType = value; } } boolean forceInline = ServerConfigurationService.getBoolean("lessonbuilder.cc.import.forceinline", false); try { if ((type.equals(CC_WEBCONTENT) || (type.equals(UNKNOWN))) && !hide) { // note: when this code is called the actual sakai resource hasn't been created yet String href = resource.getAttributeValue(HREF); // for unknown item types, may have a file with an HREF but no HREF in the actual resource // of course someone might define an extension resource without that. if (href == null) { Element fileElement = resource.getChild(FILE, ns.cc_ns()); href = fileElement.getAttributeValue(HREF); } String sakaiId = baseName + href; String extension = Validator.getFileExtension(sakaiId); String mime = ContentTypeImageService.getContentType(extension); String intendedUse = resource.getAttributeValue(INTENDEDUSE); SimplePageItem item = simplePageToolDao.makeItem(page.getPageId(), seq, SimplePageItem.RESOURCE, sakaiId, title); item.setHtml(mime); item.setSameWindow(true); title = the_xml.getChildText(CC_ITEM_TITLE, ns.cc_ns()); boolean nofile = false; //Only text type files can be inlined if ((inline || forceInline) && mime != null && mime.startsWith("text/")) { StringBuilder html = new StringBuilder(); String htmlString = null; // type 3 is a link, so it's handled below // get contents of file for types where we don't need a file in contents if (mmDisplayType == null || "1".equals(mmDisplayType)) { nofile = true; // read the file containing the HTML String fileName = getFileName(resource); InputStream fileStream = null; if (fileName != null) fileStream = utils.getFile(fileName); if (fileStream != null) { byte[] buffer = new byte[8096]; int n = 0; while ((n = fileStream.read(buffer, 0, 8096)) >= 0) { if (n > 0) html.append(new String(buffer, 0, n, "UTF-8")); } } htmlString = html.toString(); // remove stuff the exporter added int off = htmlString.indexOf("<body>"); if (off > 0) htmlString = htmlString.substring(off + 7); off = htmlString.lastIndexOf("</body>"); if (off > 0) htmlString = htmlString.substring(0, off); htmlString = fixupInlineReferences(htmlString); } // inline can be multimedia or text. If mmdisplaytype set, it's multimedia if (mmDisplayType != null) { // 1 -- embed code, 2 -- av type, 3 -- oembed, 4 -- iframe // 3 is output as a link, so it's handled below item.setType(SimplePageItem.MULTIMEDIA); if ("1".equals(mmDisplayType)) { item.setAttribute("multimediaEmbedCode", htmlString); } item.setAttribute("multimediaDisplayType", mmDisplayType); } else { // must be text item item.setType(SimplePageItem.TEXT); item.setHtml(htmlString); } } if (intendedUse != null) { intendedUse = intendedUse.toLowerCase(); if (intendedUse.equals("lessonplan")) item.setDescription( simplePageBean.getMessageLocator().getMessage("simplepage.import_cc_lessonplan")); else if (intendedUse.equals("syllabus")) item.setDescription( simplePageBean.getMessageLocator().getMessage("simplepage.import_cc_syllabus")); else if (assigntool != null && intendedUse.equals("assignment")) { String fileName = getFileName(resource); if (itemsAdded.get(fileName) == null) { // itemsAdded.put(fileName, SimplePageItem.DUMMY); // don't add the same test more than once AssignmentInterface a = (AssignmentInterface) assigntool; // file hasn't been written yet to contenthosting. A2 requires it to be there addFile(href); String assignmentId = a.importObject(title, sakaiId, mime, false); // sakaiid for assignment if (assignmentId != null) { item = simplePageToolDao.makeItem(page.getPageId(), seq, SimplePageItem.ASSIGNMENT, assignmentId, title); sakaiId = assignmentId; } } } } simplePageBean.saveItem(item); if (roles.size() > 0) { // has to be written already or we can't set groups // file hasn't been written yet to contenthosting. setitemgroups requires it to be there addFile(href); simplePageBean.setItemGroups(item, roles.toArray(new String[0])); } sequences.set(top, seq + 1); } else if (type.equals(CC_WEBCONTENT) || type.equals(UNKNOWN)) { // i.e. hidden. if it's an assignment have to load it String intendedUse = resource.getAttributeValue(INTENDEDUSE); if (assigntool != null && intendedUse != null && intendedUse.equals("assignment")) { String fileName = getFileName(resource); if (itemsAdded.get(fileName) == null) { itemsAdded.put(fileName, SimplePageItem.DUMMY); // don't add the same test more than once String sakaiId = baseName + resource.getAttributeValue(HREF); String extension = Validator.getFileExtension(sakaiId); String mime = ContentTypeImageService.getContentType(extension); AssignmentInterface a = (AssignmentInterface) assigntool; // file hasn't been written yet to contenthosting. A2 requires it to be there addFile(resource.getAttributeValue(HREF)); // in this case there's no item to take a title from String atitle = simplePageBean.getMessageLocator() .getMessage("simplepage.importcc-assigntitle") .replace("{}", (assignmentNumber++).toString()); String assignmentId = a.importObject(atitle, sakaiId, mime, true); // sakaiid for assignment } } } else if (type.equals(WEBLINK)) { Element linkXml = null; String filename = getFileName(resource); if (filename != null) { linkXml = parser.getXML(loader, filename); } else { linkXml = resource.getChild(WEBLINK, ns.link_ns()); filename = resource.getAttributeValue(ID) + XML; } Namespace linkNs = ns.link_ns(); Element urlElement = linkXml.getChild(URL, linkNs); String url = urlElement.getAttributeValue(HREF); // the name must end in XML, so we can just turn it into URL filename = filename.substring(0, filename.length() - 3) + "url"; String sakaiId = baseName + filename; if (!inline && !filesAdded.contains(filename)) { // we store the URL as a text/url resource ContentResourceEdit edit = ContentHostingService.addResource(sakaiId); edit.setContentType("text/url"); edit.setResourceType("org.sakaiproject.content.types.urlResource"); edit.setContent(url.getBytes("UTF-8")); edit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DISPLAY_NAME, Validator.escapeResourceName(filename)); ContentHostingService.commitResource(edit, NotificationService.NOTI_NONE); filesAdded.add(filename); } if (inline && "3".equals(mmDisplayType)) { // inline can be either oembed or youtube. Handle oembed here SimplePageItem item = simplePageToolDao.makeItem(page.getPageId(), seq, SimplePageItem.MULTIMEDIA, sakaiId, title); item.setAttribute("multimediaUrl", url); item.setAttribute("multimediaDisplayType", "3"); simplePageBean.saveItem(item); } else if (!hide) { // now create the Sakai item SimplePageItem item = simplePageToolDao.makeItem(page.getPageId(), seq, SimplePageItem.RESOURCE, sakaiId, title); if (inline) { // should just be youtube. null displaytype is right for that item.setType(SimplePageItem.MULTIMEDIA); } else { item.setHtml(simplePageBean.getTypeOfUrl(url)); // checks the web site to see what it actually is item.setSameWindow(true); } simplePageBean.saveItem(item); if (roles.size() > 0) simplePageBean.setItemGroups(item, roles.toArray(new String[0])); sequences.set(top, seq + 1); } } else if (type.equals(TOPIC)) { if (topictool != null) { Element topicXml = null; String filename = getFileName(resource); if (filename != null) { topicXml = parser.getXML(loader, filename); } else { topicXml = resource.getChild(TOPIC, ns.topic_ns()); } Namespace topicNs = ns.topic_ns(); String topicTitle = topicXml.getChildText(TITLE, topicNs); if (topicTitle == null) topicTitle = simplePageBean.getMessageLocator().getMessage("simplepage.cc-defaulttopic"); String text = topicXml.getChildText(TEXT, topicNs); boolean texthtml = false; if (text != null) { Element textNode = topicXml.getChild(TEXT, topicNs); String textformat = textNode.getAttributeValue(TEXTTYPE); if (TEXTHTML.equalsIgnoreCase(textformat)) texthtml = true; } String base = baseUrl; if (filename != null) { base = baseUrl + filename; int slash = base.lastIndexOf("/"); if (slash >= 0) base = base.substring(0, slash + 1); // include trailing slash } // collection id rather than URL String baseDir = baseName; if (filename != null) { baseDir = baseName + filename; int slash = baseDir.lastIndexOf("/"); if (slash >= 0) baseDir = baseDir.substring(0, slash + 1); // include trailing slash } if (texthtml) { text = text.replaceAll("\\$IMS-CC-FILEBASE\\$", base); } // I'm going to assume that URLs in the CC files are legal, but if // I add to them I nneed to URLencode what I add // filebase will be directory name for discussion.xml, since attachments are relative to that String filebase = ""; if (filename != null) { filebase = filename; int slash = filebase.lastIndexOf("/"); if (slash >= 0) filebase = filebase.substring(0, slash + 1); // include trailing slash } Element attachmentlist = topicXml.getChild(ATTACHMENTS, topicNs); List<Element> attachments = new ArrayList<Element>(); if (attachmentlist != null) attachments = attachmentlist.getChildren(); List<String> attachmentHrefs = new ArrayList<String>(); for (Element a : attachments) { // file has to be there for the forum attachment handling to work addFile(removeDotDot(filebase + a.getAttributeValue(HREF))); attachmentHrefs.add(a.getAttributeValue(HREF)); } ForumInterface f = (ForumInterface) topictool; if (nopage) title = simplePageBean.getMessageLocator().getMessage("simplepage.cc-defaultforum"); log.debug("about to call forum import base " + base); // title is for the cartridge. That will be used as the forum // if already added, don't do it again String sakaiId = itemsAdded.get(filename); if (sakaiId == null) { if (f != null) sakaiId = f.importObject(title, topicTitle, text, texthtml, base, baseDir, siteId, attachmentHrefs, hide); if (sakaiId != null) itemsAdded.put(filename, sakaiId); } if (!hide) { log.debug("about to add formum item"); SimplePageItem item = simplePageToolDao.makeItem(page.getPageId(), seq, SimplePageItem.FORUM, sakaiId, title); simplePageBean.saveItem(item); if (roles.size() > 0) simplePageBean.setItemGroups(item, roles.toArray(new String[0])); sequences.set(top, seq + 1); log.debug("finished with forum item"); } } } else if (type.equals(ASSESSMENT) || type.equals(QUESTION_BANK)) { if (quiztool != null) { String fileName = getFileName(resource); String sakaiId = null; String base = baseUrl; org.w3c.dom.Document quizDoc = null; InputStream instream = null; // not already added if (fileName == null || itemsAdded.get(fileName) == null) { File qtitemp = File.createTempFile("ccqti", "txt"); PrintWriter outwriter = new PrintWriter(qtitemp); // assessment in file if (fileName != null) { itemsAdded.put(fileName, SimplePageItem.DUMMY); // don't add the same test more than once instream = utils.getFile(fileName); // I'm going to assume that URLs in the CC files are legal, but if // I add to them I nneed to URLencode what I add base = baseUrl + fileName; int slash = base.lastIndexOf("/"); if (slash >= 0) base = base.substring(0, slash + 1); // include trailing slash // assessment inline } else { Element quizXml = (Element) resource.getChild(QUESTIONS, ns.qticc_ns()).clone(); // we work in jdom. Qti parser needs w3c quizDoc = new DOMOutputter().output(new org.jdom.Document(quizXml)); } QtiImport imp = new QtiImport(); try { boolean thisUsesPattern = imp.mainproc(instream, outwriter, isBank, base, siteId, simplePageBean, quizDoc); if (thisUsesPattern) usesPatternMatch = true; if (imp.getUsesCurriculum()) usesCurriculum = true; } catch (Exception e) { e.printStackTrace(); } outwriter.close(); InputStream inputStream = new FileInputStream(qtitemp); try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); builderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); builderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder(); org.w3c.dom.Document document = documentBuilder.parse(inputStream); QuizEntity q = (QuizEntity) quiztool; sakaiId = q.importObject(document, isBank, siteId, hide); if (sakaiId == null) sakaiId = SimplePageItem.DUMMY; } catch (Exception e) { log.info("CC import error creating or parsing QTI file " + fileName + " " + e); simplePageBean.setErrKey("simplepage.create.object.failed", e.toString()); } inputStream.close(); qtitemp.delete(); } // question banks don't appear on the page if (!isBank && !hide) { SimplePageItem item = simplePageToolDao.makeItem(page.getPageId(), seq, SimplePageItem.ASSESSMENT, (sakaiId == null ? SimplePageItem.DUMMY : sakaiId), title); simplePageBean.saveItem(item); if (roles.size() > 0) simplePageBean.setItemGroups(item, roles.toArray(new String[0])); sequences.set(top, seq + 1); } } } else if (type.equals(QUESTION_BANK)) { ; // handled elsewhere // current code seems to assume that BLTI tool is part of the page so skip if no page } else if (type.equals(BLTI)) { if (!nopage) { String filename = getFileName(resource); Element ltiXml = null; if (filename != null) ltiXml = parser.getXML(loader, filename); else { ltiXml = resource.getChild(CART_LTI_LINK, ns.lticc_ns()); } XMLOutputter outputter = new XMLOutputter(); String strXml = outputter.outputString(ltiXml); Namespace bltiNs = ns.blti_ns(); String bltiTitle = ltiXml.getChildText(TITLE, bltiNs); Element customElement = ltiXml.getChild("custom", bltiNs); List<Element> customs = new ArrayList<Element>(); if (customElement != null) customs = customElement.getChildren(); StringBuffer sb = new StringBuffer(); String custom = null; for (Element a : customs) { String key = a.getAttributeValue("name"); String value = a.getText(); if (key == null) continue; key = key.trim(); if (value == null) continue; sb.append(key.trim()); sb.append("="); sb.append(value.trim()); sb.append("\n"); } if (sb.length() > 0) custom = sb.toString(); String launchUrl = ltiXml.getChildTextTrim("secure_launch_url", bltiNs); if (launchUrl == null) launchUrl = ltiXml.getChildTextTrim("launch_url", bltiNs); String sakaiId = null; if (bltitool != null) { sakaiId = ((BltiInterface) bltitool).doImportTool(launchUrl, bltiTitle, strXml, custom); } if (!hide) { if (sakaiId != null) { log.debug("Adding LTI content item " + sakaiId); SimplePageItem item = simplePageToolDao.makeItem(page.getPageId(), seq, SimplePageItem.BLTI, sakaiId, title); item.setHeight(""); // default depends upon format, so it's supplied at runtime simplePageBean.saveItem(item); if (roles.size() > 0) simplePageBean.setItemGroups(item, roles.toArray(new String[0])); sequences.set(top, seq + 1); } else { log.info("LTI Import Failed.."); } } } } else if (type.equals(ASSIGNMENT)) { Element assignXml = null; String filename = getFileName(resource); if (filename != null) { assignXml = parser.getXML(loader, filename); } else { assignXml = resource.getChild(ASSIGNMENT, ns.assign_ns()); } Namespace assignNs = ns.assign_ns(); // filebase will be directory name for discussion.xml, since attachments are relative to that String filebase = ""; if (filename != null) { filebase = filename; int slash = filebase.lastIndexOf("/"); if (slash >= 0) filebase = filebase.substring(0, slash + 1); // include trailing slash } String base = baseUrl; if (filename != null) { base = baseUrl + filename; int slash = base.lastIndexOf("/"); if (slash >= 0) base = base.substring(0, slash + 1); // include trailing slash } // collection id rather than URL String baseDir = baseName; if (filename != null) { baseDir = baseName + filename; int slash = baseDir.lastIndexOf("/"); if (slash >= 0) baseDir = baseDir.substring(0, slash + 1); // include trailing slash } // let importobject handle most of this, but we have to // process the attachments to make sure they're present Element attachmentlist = assignXml.getChild(ATTACHMENTS, assignNs); List<Element> attachments = new ArrayList<Element>(); if (attachmentlist != null) attachments = attachmentlist.getChildren(); List<String> attachmentHrefs = new ArrayList<String>(); // note that we ignore the role attribute. No obvious way to implement it. for (Element a : attachments) { // file has to be there addFile(removeDotDot(filebase + a.getAttributeValue(HREF))); attachmentHrefs.add(a.getAttributeValue(HREF)); } // need to prevent duplicates, as we're likely to see the same resource more than once. // Remember that we've produced this resource ID. String resourceId = resource.getAttributeValue(IDENTIFIER); String assignmentId = assignsAdded.get(resourceId); if (assignmentId == null) { AssignmentInterface a = (AssignmentInterface) assigntool; assignmentId = a.importObject(assignXml, assignNs, base, baseDir, attachmentHrefs, hide); // sakaiid for assignment if (assignmentId != null) assignsAdded.put(resourceId, assignmentId); } if (assignmentId != null && !hide) { SimplePageItem item = simplePageToolDao.makeItem(page.getPageId(), seq, SimplePageItem.ASSIGNMENT, assignmentId, title); simplePageBean.saveItem(item); if (roles.size() > 0) simplePageBean.setItemGroups(item, roles.toArray(new String[0])); sequences.set(top, seq + 1); } } else if (((type.equals(CC_WEBCONTENT) || (type.equals(UNKNOWN))) && hide) || type.equals(LAR)) { // handled elsewhere } if (type.equals(UNKNOWN)) { badTypes.add(resource.getAttributeValue(TYPE)); log.debug("unknown type: " + resource.getAttributeValue(TYPE)); } } catch (Exception e) { e.printStackTrace(); log.debug("Exception ", e); } }
From source file:org.sakaiproject.site.util.SiteSetupQuestionFileParser.java
/** * Parse an XML resource/*from w w w.j a v a 2 s .com*/ * @param filename The filename (or URI) to parse * @return DOM Document (null if parse fails) */ protected static Document parseXmlFromStream(InputStream stream) { try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true); builderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); builderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder(); if (documentBuilder != null) { return documentBuilder.parse(stream); } } catch (Exception exception) { m_log.warn("XML parse on \"" + stream + "\" failed: " + exception); } return null; }
From source file:org.sakaiproject.tool.assessment.qti.util.XmlUtil.java
private static void setDocumentBuilderFactoryFeatures(DocumentBuilderFactory builderFactory) throws ParserConfigurationException { builderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); builderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); }
From source file:org.sakaiproject.webservices.TestsAndQuizzes.java
/** * createAsessmentFromExport - WS Endpoint, exposing the SamLite createImportedAssessment() * * @param String sessionid the id of a valid admin session * @param String siteid the enterprise/sakai id of the site to be archived * @param String siteproperty the property that holds the enterprise site id * @param String xmlstring the IMS QTI document containing the assessment * @return boolean returns true if assessment created successfully, false if assessment is null * //www. ja v a 2s . co m * @throws AxisFault WS TestsAndQuizzes.createAssessmentFromXml(): returned a null QTI Document * WS TestsAndQuizzes.createAssessmentFromXml(): " + e.getMessage * */ @WebMethod @Path("/createAssessmentFromExport") @Produces("text/plain") @GET public boolean createAssessmentFromExport( @WebParam(name = "sessionid", partName = "sessionid") @QueryParam("sessionid") String sessionid, @WebParam(name = "siteid", partName = "siteid") @QueryParam("siteid") String siteid, @WebParam(name = "siteproperty", partName = "siteproperty") @QueryParam("siteproperty") String siteproperty, @WebParam(name = "xmlstring", partName = "xmlstring") @QueryParam("xmlstring") String xmlstring) { Session session = establishSession(sessionid); Document document = null; InputStream inputStream = null; try { byte[] bytes = xmlstring.getBytes(); inputStream = new ByteArrayInputStream(bytes); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); builderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); builderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); builderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder(); document = documentBuilder.parse(inputStream); } catch (Exception e) { LOG.error("WS TestsAndQuizzes.createAssessmentFromXml(): " + e.getMessage(), e); throw new RuntimeException("WS TestsAndQuizzes.createAssessmentFromXml(): " + e.getMessage()); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { } } if (document == null) { throw new RuntimeException( "WS TestsAndQuizzes.createAssessmentFromXml(): returned a null QTI Document"); } return createAssessment(siteid, siteproperty, null, null, null, document); }