public Object serialize(Object o, Object context, SerializationFilter filter) { Map map = (Map) o; Element m; if (myMapAnnotation == null || myMapAnnotation.surroundWithTag()) { m = new Element(Constants.MAP); } else { m = (Element) context; } final Set keySet = map.keySet(); final Object[] keys = ArrayUtil.toObjectArray(keySet); if (myMapAnnotation == null || myMapAnnotation.sortBeforeSave()) { Arrays.sort(keys, KEY_COMPARATOR); } for (Object k : keys) { Object v = map.get(k); Element entry = new Element(getEntryAttributeName()); m.addContent(entry); Object kNode = myKeyBinding.serialize(k, entry, filter); if (kNode instanceof Text) { Text text = (Text) kNode; entry.setAttribute(getKeyAttributeValue(), text.getText()); } else { if (myMapAnnotation != null && !myMapAnnotation.surroundKeyWithTag()) { entry.addContent((Content) kNode); } else { Element key = new Element(getKeyAttributeValue()); entry.addContent(key); key.addContent((Content) kNode); } } Object vNode = myValueBinding.serialize(v, entry, filter); if (vNode instanceof Text) { Text text = (Text) vNode; entry.setAttribute(getValueAttributeName(), text.getText()); } else { if (myMapAnnotation != null && !myMapAnnotation.surroundValueWithTag()) { entry.addContent((Element) vNode); } else { Element value = new Element(getValueAttributeName()); entry.addContent(value); value.addContent((Content) vNode); } } } return m; }
/** * Set the text content from a XML node. * * @param t inner text element of XML <msg></msg> element. */ public void xmltext(final Text t) { /* if trim is required, split the text and trim each line */ if (trim) { final String[] lines = t.getText().split(System.lineSeparator()); for (String s : lines) { this.append(s.trim() + System.lineSeparator()); } } else { this.append(t.getText()); } }
/** * Displays information about all nodes in a result set. * * @param nodelist the result list of an XPath expression evaluation */ public static void display_node_list(List nodelist) { int size = nodelist.size(); for (Object obj : nodelist) { String value = null; if (obj instanceof Element) { Element elem = (Element) obj; String details = String.format( "%d children, %d attrs", elem.getChildren().size(), elem.getAttributes().size()); value = String.format("%s (%s)", elem.getQualifiedName(), details); } else if (obj instanceof Attribute) { Attribute attr = (Attribute) obj; value = String.format("@%s=\'%s\'", attr.getQualifiedName(), attr.getValue()); } else if (obj instanceof Text) { Text text = (Text) obj; value = String.format("\"%s\"", text.getText()); } else if (obj instanceof String) { String s = (String) obj; value = String.format("\"%s\"", s); } else if (obj instanceof Boolean) { Boolean b = (Boolean) obj; value = String.format("%s", b.toString()); } else if (obj instanceof Double) { Double d = (Double) obj; value = String.format("%s", d.toString()); } else { value = "Unsupported dynamic type"; } // if-else System.out.printf(" (%s) %s\n", obj.getClass().getName(), value); } // for System.out.printf("Result: %d nodes\n", size); } // display_node_list()
/** * Returns formatted text. * * @param text * @return the text */ public String evaluate(Text text) { return text.getText(); }
@SuppressWarnings("unchecked") private List<StageRepository> parseStageRepositories( final Document doc, final String profileXpath, final Boolean findOpen, boolean filterUser) throws RESTLightClientException { // System.out.println( new XMLOutputter().outputString( doc ) ); XPath profileXp = newXPath(profileXpath); List<Element> profiles; try { profiles = profileXp.selectNodes(doc.getRootElement()); } catch (JDOMException e) { throw new RESTLightClientException( "XPath selection failed: '" + profileXpath + "' (Root node: " + doc.getRootElement().getName() + ").", e); } List<StageRepository> result = new ArrayList<StageRepository>(); if (profiles != null) { XPath openRepoIdXPath = newXPath(OPEN_STAGE_REPOS_XPATH); XPath closedRepoIdXPath = newXPath(CLOSED_STAGE_REPOS_XPATH); for (Element profile : profiles) { // System.out.println( new XMLOutputter().outputString( profile ) ); String profileId = profile.getChild(PROFILE_ID_ELEMENT).getText(); String profileName = profile.getChild(PROFILE_NAME_ELEMENT).getText(); Map<String, StageRepository> matchingRepoStubs = new LinkedHashMap<String, StageRepository>(); if (!Boolean.FALSE.equals(findOpen)) { try { List<Text> repoIds = openRepoIdXPath.selectNodes(profile); if (repoIds != null && !repoIds.isEmpty()) { for (Text txt : repoIds) { matchingRepoStubs.put( profileId + "/" + txt.getText(), new StageRepository(profileId, txt.getText(), findOpen) .setProfileName(profileName)); } } } catch (JDOMException e) { throw new RESTLightClientException( "XPath selection failed: '" + OPEN_STAGE_REPOS_XPATH + "' (Node: " + profile.getName() + ").", e); } } if (!Boolean.TRUE.equals(findOpen)) { try { List<Text> repoIds = closedRepoIdXPath.selectNodes(profile); if (repoIds != null && !repoIds.isEmpty()) { for (Text txt : repoIds) { matchingRepoStubs.put( profileId + "/" + txt.getText(), new StageRepository(profileId, txt.getText(), findOpen) .setProfileName(profileName)); } } } catch (JDOMException e) { throw new RESTLightClientException( "XPath selection failed: '" + CLOSED_STAGE_REPOS_XPATH + "' (Node: " + profile.getName() + ").", e); } } if (!matchingRepoStubs.isEmpty()) { parseStageRepositoryDetails(profileId, matchingRepoStubs, filterUser); result.addAll(matchingRepoStubs.values()); } } } return result; }
public void fromJDOM(Element element) { super.fromJDOM(element); for (Object attribute : element.getAttributes()) { String tag = ((Attribute) attribute).getName(); String value = ((Attribute) attribute).getValue(); if (AssessmentElementFactory.IDENTIFIER.equals(tag)) { fID = value; } else if (AssessmentElementFactory.SHUFFLE.equals(tag)) { fShuffle = "true".equalsIgnoreCase(value); } } for (Object o : element.getChildren()) { Element child = (Element) o; String tag = child.getName(); // String value = child.getText(); if (tag.equals(AssessmentElementFactory.GAP_TEXT)) { GapText aGapText = new GapText(fAssessmentItem, this); aGapText.fromJDOM((Element) child); fGapTextList.addElement(aGapText); } else if (tag.equals(AssessmentElementFactory.P)) { List grandChildren = child.getContent(); Iterator iterator = grandChildren.iterator(); Text textString = new Text(""); while (iterator.hasNext()) { Object grandChild = iterator.next(); if (grandChild instanceof Element) { Element e = (Element) grandChild; if (e.getName().equals(AssessmentElementFactory.GAP)) { Gap aGap = new Gap(fAssessmentItem, this); aGap.fromJDOM((Element) grandChild); aGap.setStart(textString.getText().length() + 1); InterpretationValue aInterpretationValue = getResponseDeclaration().getCorrectResponse(); for (int i = 0; i < aInterpretationValue.size(); i++) { String valueData = aInterpretationValue.getValueAt(i).getData(); int index = valueData.indexOf(" "); if (index != -1) { String targetID = valueData.substring(index + 1); if (targetID.equals(aGap.getId())) { String sourceID = valueData.substring(0, index); GapText aGapText = getGapTextByID(sourceID); aGap.setData(aGapText.getData()); aGap.setMatchedGapText(aGapText); aGap.setLength(aGapText.getData().length()); if (!aGapText.getData().equals("")) { textString.append(" " + aGapText.getData()); } else { System.out.println("correct choice is an empty string"); } fGapList.addElement(aGap); } } } } } else if (grandChild instanceof Text) { textString.append((Text) grandChild); } } data = textString.getText(); } } }
private static void sendXQueryResponse(HttpServletResponse res, Object o) throws IOException { // Make sure to leave the status code alone. It defaults to 200, but sometimes // callers of this method will have set it to a custom code. res.setContentType("x-marklogic/xquery; charset=UTF-8"); // res.setContentType("text/plain"); Writer writer = res.getWriter(); // care to handle errors later? if (o == null) { writer.write("()"); } else if (o instanceof byte[]) { writer.write("binary {'"); writer.write(hexEncode((byte[]) o)); writer.write("'}"); } else if (o instanceof Object[]) { Object[] arr = (Object[]) o; writer.write("("); for (int i = 0; i < arr.length; i++) { sendXQueryResponse(res, arr[i]); if (i + 1 < arr.length) writer.write(", "); } writer.write(")"); } else if (o instanceof String) { writer.write("'"); writer.write(escapeSingleQuotes(o.toString())); writer.write("'"); } else if (o instanceof Integer) { writer.write("xs:int("); writer.write(o.toString()); writer.write(")"); } else if (o instanceof Long) { writer.write("xs:integer("); writer.write(o.toString()); writer.write(")"); } else if (o instanceof Float) { Float flt = (Float) o; writer.write("xs:float("); if (flt.equals(Float.POSITIVE_INFINITY)) { writer.write("'INF'"); } else if (flt.equals(Float.NEGATIVE_INFINITY)) { writer.write("'-INF'"); } else if (flt.equals(Float.NaN)) { writer.write("fn:number(())"); // poor man's way to write NaN } else { writer.write(o.toString()); } writer.write(")"); } else if (o instanceof Double) { Double dbl = (Double) o; writer.write("xs:double("); if (dbl.equals(Double.POSITIVE_INFINITY)) { writer.write("'INF'"); } else if (dbl.equals(Double.NEGATIVE_INFINITY)) { writer.write("'-INF'"); } else if (dbl.equals(Double.NaN)) { writer.write("fn:number(())"); // poor man's way to write NaN } else { writer.write(o.toString()); } writer.write(")"); } else if (o instanceof Boolean) { writer.write("xs:boolean('"); writer.write(o.toString()); writer.write("')"); } else if (o instanceof BigDecimal) { writer.write("xs:decimal("); writer.write(o.toString()); writer.write(")"); } else if (o instanceof Date) { // We want something like: 2006-04-30T01:28:30.499-07:00 // We format to get: 2006-04-30T01:28:30.499-0700 // Then we add in the colon writer.write("xs:dateTime('"); String d = dateFormat.format((Date) o); writer.write(d.substring(0, d.length() - 2)); writer.write(":"); writer.write(d.substring(d.length() - 2)); writer.write("')"); } else if (o instanceof XMLGregorianCalendar) { XMLGregorianCalendar greg = (XMLGregorianCalendar) o; QName type = greg.getXMLSchemaType(); if (type.equals(DatatypeConstants.DATETIME)) { writer.write("xs:dateTime('"); } else if (type.equals(DatatypeConstants.DATE)) { writer.write("xs:date('"); } else if (type.equals(DatatypeConstants.TIME)) { writer.write("xs:time('"); } else if (type.equals(DatatypeConstants.GYEARMONTH)) { writer.write("xs:gYearMonth('"); } else if (type.equals(DatatypeConstants.GMONTHDAY)) { writer.write("xs:gMonthDay('"); } else if (type.equals(DatatypeConstants.GYEAR)) { writer.write("xs:gYear('"); } else if (type.equals(DatatypeConstants.GMONTH)) { writer.write("xs:gMonth('"); } else if (type.equals(DatatypeConstants.GDAY)) { writer.write("xs:gDay('"); } writer.write(greg.toXMLFormat()); writer.write("')"); } else if (o instanceof Duration) { Duration dur = (Duration) o; /* // The following fails on Xerces QName type = dur.getXMLSchemaType(); if (type.equals(DatatypeConstants.DURATION)) { writer.write("xs:duration('"); } else if (type.equals(DatatypeConstants.DURATION_DAYTIME)) { writer.write("xdt:dayTimeDuration('"); } else if (type.equals(DatatypeConstants.DURATION_YEARMONTH)) { writer.write("xdt:yearMonthDuration('"); } */ // If no years or months, must be DURATION_DAYTIME if (dur.getYears() == 0 && dur.getMonths() == 0) { writer.write("xdt:dayTimeDuration('"); } // If has years or months but nothing else, must be DURATION_YEARMONTH else if (dur.getDays() == 0 && dur.getHours() == 0 && dur.getMinutes() == 0 && dur.getSeconds() == 0) { writer.write("xdt:yearMonthDuration('"); } else { writer.write("xs:duration('"); } writer.write(dur.toString()); writer.write("')"); } else if (o instanceof org.jdom.Element) { org.jdom.Element elt = (org.jdom.Element) o; writer.write("xdmp:unquote('"); // Because "<" in XQuery is the same as "<" I need to double escape any ampersands writer.write( new org.jdom.output.XMLOutputter() .outputString(elt) .replaceAll("&", "&") .replaceAll("'", "''")); writer.write("')/*"); // make sure to return the root elt } else if (o instanceof org.jdom.Document) { org.jdom.Document doc = (org.jdom.Document) o; writer.write("xdmp:unquote('"); writer.write( new org.jdom.output.XMLOutputter() .outputString(doc) .replaceAll("&", "&") .replaceAll("'", "''")); writer.write("')"); } else if (o instanceof org.jdom.Text) { org.jdom.Text text = (org.jdom.Text) o; writer.write("text {'"); writer.write(escapeSingleQuotes(text.getText())); writer.write("'}"); } else if (o instanceof org.jdom.Attribute) { // <fake xmlns:pref="http://uri.com" pref:attrname="attrvalue"/>/@*:attrname // <fake xmlns="http://uri.com" attrname="attrvalue"/>/@*:attrname org.jdom.Attribute attr = (org.jdom.Attribute) o; writer.write("<fake xmlns"); if ("".equals(attr.getNamespacePrefix())) { writer.write("=\""); } else { writer.write(":" + attr.getNamespacePrefix() + "=\""); } writer.write(attr.getNamespaceURI()); writer.write("\" "); writer.write(attr.getQualifiedName()); writer.write("=\""); writer.write(escapeSingleQuotes(attr.getValue())); writer.write("\"/>/@*:"); writer.write(attr.getName()); } else if (o instanceof org.jdom.Comment) { org.jdom.Comment com = (org.jdom.Comment) o; writer.write("comment {'"); writer.write(escapeSingleQuotes(com.getText())); writer.write("'}"); } else if (o instanceof org.jdom.ProcessingInstruction) { org.jdom.ProcessingInstruction pi = (org.jdom.ProcessingInstruction) o; writer.write("processing-instruction "); writer.write(pi.getTarget()); writer.write(" {'"); writer.write(escapeSingleQuotes(pi.getData())); writer.write("'}"); } else if (o instanceof QName) { QName q = (QName) o; writer.write("fn:expanded-QName('"); writer.write(escapeSingleQuotes(q.getNamespaceURI())); writer.write("','"); writer.write(q.getLocalPart()); writer.write("')"); } else { writer.write( "error('XQuery tried to retrieve unsupported type: " + o.getClass().getName() + "')"); } writer.flush(); }