下面列出了javax.persistence.Embeddable#org.dom4j.Element 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void spanElementCustomizable() throws Exception {
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {"foo", "bar", "baz"});
this.tag.setElement("element");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element spanElement = (Element) document.getRootElement().elements().get(0);
assertEquals("element", spanElement.getName());
}
public static void storeMap(Element parentElement, Map<String, String> map) {
if (map == null) {
return;
}
Element mapElem = parentElement.addElement("map");
for (Map.Entry<String, String> entry : map.entrySet()) {
Element entryElem = mapElem.addElement("entry");
entryElem.addAttribute("key", entry.getKey());
Element valueElem = entryElem.addElement("value");
if (entry.getValue() != null) {
String value = StringEscapeUtils.escapeXml11(entry.getValue());
valueElem.setText(value);
}
}
}
/** Creates a specific Msg */
@Override
public Msg parseMsgFromXml(ParseFromXmlContext context, Element root, Runner runner) throws Exception
{
Msg msg = super.parseMsgFromXml(context, root, runner);
String channelName = root.attributeValue("channel");
if (existsChannel(channelName))
{
ChannelImap channel = (ChannelImap) getChannel(channelName);
// code imported from channel. we must now set the transaction ID BEFORE
// sending the request (modifications on the generic stack)
msg.setTransactionId(channel.getTransactionId());
if(channel.isServer())//pour un server (envoi d'une reponse)
{
channel.checkTransationResponse(msg, channel.getChannel().getRemoteHost() + channel.getChannel().getRemotePort());
}
else//pour un client (envoi d'une requete)
{
msg = (MsgImap) channel.checkTransationRequest(msg, channel.getChannel().getLocalHost() + channel.getChannel().getLocalPort());
}
}
return msg;
}
public static void removeStringValue(File file, String key) throws IOException, DocumentException {
if (!file.exists()) {
return;
}
Document document = XmlHelper.readXml(file);// Read the XML file
Element root = document.getRootElement();// Get the root node
List<? extends Node> nodes = root.selectNodes("//string");
for (Node node : nodes) {
Element element = (Element)node;
String name = element.attributeValue("name");
if (key.equals(name)) {
element.getParent().remove(element);
break;
}
}
// sLogger.warn("[resxmlediter] add " + key + " to " + file.getAbsolutePath());
XmlHelper.saveDocument(document, file);
}
/**
* Copy a string attribute from an XML element to an annotation descriptor. The name of the annotation attribute is
* explicitely given.
*
* @param annotation annotation where to copy to the attribute.
* @param element XML element from where to copy the attribute.
* @param annotationAttributeName name of the annotation attribute where to copy.
* @param attributeName name of the XML attribute to copy.
* @param mandatory whether the attribute is mandatory.
*/
private static void copyStringAttribute(
final AnnotationDescriptor annotation, final Element element,
final String annotationAttributeName, final String attributeName, boolean mandatory) {
String attribute = element.attributeValue( attributeName );
if ( attribute != null ) {
annotation.setValue( annotationAttributeName, attribute );
}
else {
if ( mandatory ) {
throw new AnnotationException(
element.getName() + "." + attributeName + " is mandatory in XML overriding. " + SCHEMA_VALIDATION
);
}
}
}
public DepartmentalInstructor importInstructor(Element element) {
String deptCode = element.attributeValue("deptCode");
String puid = element.attributeValue("puid");
DepartmentalInstructor instructor = (DepartmentalInstructor) hibSession.
createQuery("select id from DepartmentalInstructor id where id.department.deptCode=:deptCode and id.department.sessionId=:sessionId and id.puid=:puid").
setString("deptCode", deptCode).
setLong("sessionId", iSession.getUniqueId().longValue()).
setString("puid",puid).
uniqueResult();
if (instructor==null) {
sLog.error("Unable to find instructor "+puid+" for department "+deptCode);
return null;
}
sLog.info("Processing instructor "+instructor.getLastName()+" (puid:"+puid+")");
importPreferences(instructor, element);
hibSession.update(instructor);
hibSession.flush();
hibSession.refresh(instructor);
return instructor;
}
@Override
public boolean validate(final File unzippedDir) {
// with VFS FIXME:pb:c: remove casts to LocalFileImpl and LocalFolderImpl if no longer needed.
final VFSContainer vfsUnzippedRoot = new LocalFolderImpl(unzippedDir);
final VFSItem vfsQTI = vfsUnzippedRoot.resolve("qti.xml");
// getDocument(..) ensures that InputStream is closed in every case.
final Document doc = QTIHelper.getDocument((LocalFileImpl) vfsQTI);
// if doc is null an error loading the document occured
if (doc == null) {
return false;
}
final List metas = doc.selectNodes("questestinterop/assessment/qtimetadata/qtimetadatafield");
for (final Iterator iter = metas.iterator(); iter.hasNext();) {
final Element el_metafield = (Element) iter.next();
final Element el_label = (Element) el_metafield.selectSingleNode("fieldlabel");
final String label = el_label.getText();
if (label.equals(AssessmentInstance.QMD_LABEL_TYPE)) { // type meta
final Element el_entry = (Element) el_metafield.selectSingleNode("fieldentry");
final String entry = el_entry.getText();
return entry.equals(AssessmentInstance.QMD_ENTRY_TYPE_SURVEY);
}
}
return false;
}
@Test
public void withMultiValueUnchecked() throws Exception {
this.tag.setPath("stringArray");
this.tag.setValue("abc");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("stringArray", checkboxElement.attribute("name").getValue());
assertNull(checkboxElement.attribute("checked"));
assertEquals("abc", checkboxElement.attribute("value").getValue());
}
/**
* 消息类型
* 1:text 文本消息
* 2:image 图片消息
* 3:voice 语音消息
* 4:video 视频消息
* shortvideo 小视频消息
* 5:location 地址位置消息
* 6:link 链接消息
* 7:event 事件
*/
private static InMsg doParse(String xml) throws DocumentException {
Document doc = DocumentHelper.parseText(xml);
Element root = doc.getRootElement();
String toUserName = root.elementText("ToUserName");
String fromUserName = root.elementText("FromUserName");
Integer createTime = Integer.parseInt(root.elementText("CreateTime"));
String msgType = root.elementText("MsgType");
if ("text".equals(msgType))
return parseInTextMsg(root, toUserName, fromUserName, createTime, msgType);
if ("image".equals(msgType))
return parseInImageMsg(root, toUserName, fromUserName, createTime, msgType);
if ("voice".equals(msgType))
return parseInVoiceMsgAndInSpeechRecognitionResults(root, toUserName, fromUserName, createTime, msgType);
if ("video".equals(msgType))
return parseInVideoMsg(root, toUserName, fromUserName, createTime, msgType);
if ("shortvideo".equals(msgType)) //支持小视频
return parseInShortVideoMsg(root, toUserName, fromUserName, createTime, msgType);
if ("location".equals(msgType))
return parseInLocationMsg(root, toUserName, fromUserName, createTime, msgType);
if ("link".equals(msgType))
return parseInLinkMsg(root, toUserName, fromUserName, createTime, msgType);
if ("event".equals(msgType))
return parseInEvent(root, toUserName, fromUserName, createTime, msgType);
throw new RuntimeException("无法识别的消息类型 " + msgType + ",请查阅微信公众平台开发文档");
}
/**
* Tests adding, removing IQ listeners and handling IQ stanzas.
*/
@Test
public void handlePackets() {
// IQ packets
IQ iq = new IQ();
Element element = new DefaultElement("pubsub", Namespace.get(testNamespace));
iq.setChildElement(element);
agent.processUpstreamEvent(jid1, iq);
assertThat(testXmppIqListener.handledIqs, hasSize(1));
agent.processUpstreamEvent(jid2, iq);
assertThat(testXmppIqListener.handledIqs, hasSize(2));
// Message packets
Packet message = new Message();
agent.processUpstreamEvent(jid1, message);
assertThat(testXmppMessageListener.handledMessages, hasSize(1));
agent.processUpstreamEvent(jid2, message);
assertThat(testXmppMessageListener.handledMessages, hasSize(2));
Packet presence = new Presence();
agent.processUpstreamEvent(jid1, presence);
assertThat(testXmppPresenceListener.handledPresenceStanzas, hasSize(1));
agent.processUpstreamEvent(jid2, presence);
assertThat(testXmppPresenceListener.handledPresenceStanzas, hasSize(2));
}
CBSAssignment(CBSConstraint constraint, Element element) {
iConstraint = constraint;
iExamId = Long.valueOf(element.attributeValue("exam"));
iExamName = element.attributeValue("name");
iExamPref = element.attributeValue("pref");
iRoomIds = new Vector();
iRoomNames = new Vector();
iRoomPrefs = new Vector();
for (Iterator i=element.elementIterator("room");i.hasNext();) {
Element r = (Element)i.next();
iRoomIds.addElement(Integer.valueOf(r.attributeValue("id")));
iRoomNames.addElement(r.attributeValue("name"));
iRoomPrefs.addElement(Integer.valueOf(r.attributeValue("pref")));
}
iPeriodId = Long.valueOf(element.attributeValue("period"));
iPeriodName = element.attributeValue("periodName");
iPeriodPref = Integer.parseInt(element.attributeValue("periodPref"));
incCounter(Integer.parseInt(element.attributeValue("cnt")));
}
static void serializeObject(Object value, Element element) {
element.addAttribute("type", value.getClass().getName());
if (value instanceof Collection<?>) {
Collection<?> collection = (Collection<?>) value;
Iterator<?> iterator = collection.iterator();
while (iterator.hasNext()) {
Object val = iterator.next();
Element valElement = element.addElement("entry");
serializeObject(val, valElement);
}
} else {
element.addText(value.toString());
}
}
private static ColumnResult buildColumnResult(
Element columnResultElement,
XMLContext.Default defaults,
ClassLoaderAccess classLoaderAccess) {
// AnnotationDescriptor columnResultDescriptor = new AnnotationDescriptor( ColumnResult.class );
// copyStringAttribute( columnResultDescriptor, columnResultElement, "name", true );
// return AnnotationFactory.create( columnResultDescriptor );
AnnotationDescriptor columnResultDescriptor = new AnnotationDescriptor( ColumnResult.class );
copyStringAttribute( columnResultDescriptor, columnResultElement, "name", true );
final String columnTypeName = columnResultElement.attributeValue( "class" );
if ( StringHelper.isNotEmpty( columnTypeName ) ) {
columnResultDescriptor.setValue( "type", resolveClassReference( columnTypeName, defaults, classLoaderAccess ) );
}
return AnnotationFactory.create( columnResultDescriptor );
}
private static WeixinInMsg doParse(String xml) throws DocumentException {
Document doc = DocumentHelper.parseText(xml);
Element root = doc.getRootElement();
String toUserName = root.elementText("ToUserName");
String fromUserName = root.elementText("FromUserName");
long createTime = Long.parseLong(root.elementText("CreateTime"));
String msgType = root.elementText("MsgType");
if("text".equals(msgType)){
return parseInTextMsg(root, toUserName, fromUserName, createTime, msgType);
}
if("image".equals(msgType)){
return parseInImageMsg(root, toUserName, fromUserName, createTime, msgType);
}
if("location".equals(msgType)){
return parseInLocationMsg(root, toUserName, fromUserName, createTime, msgType);
}
if("link".equals(msgType)){
return parseInLinkMsg(root, toUserName, fromUserName, createTime, msgType);
}
if("event".equals(msgType)){
return parseInEventMsg(root, toUserName, fromUserName, createTime, msgType);
}
throw new RuntimeException("未知的消息类型" + msgType + ", 请查阅微信公众平台开发者文档https://mp.weixin.qq.com/wiki");
}
/**
* Feedback, solution and hints in case of failure
*
* @param resprocessingXML
*/
private void buildRespconditionKprim_fail(final Element resprocessingXML) {
final Element respcondition_fail = resprocessingXML.addElement("respcondition");
respcondition_fail.addAttribute("title", "Fail");
respcondition_fail.addAttribute("continue", "Yes");
final Element conditionvar = respcondition_fail.addElement("conditionvar");
final Element not = conditionvar.addElement("not");
final Element and = not.addElement("and");
for (final Iterator i = getResponses().iterator(); i.hasNext();) {
final ChoiceResponse choice = (ChoiceResponse) i.next();
Element varequal;
varequal = and.addElement("varequal");
varequal.addAttribute("respident", getIdent());
varequal.addAttribute("case", "Yes");
if (choice.isCorrect()) {
varequal.addText(choice.getIdent() + ":correct");
} else { // incorrect answers
varequal.addText(choice.getIdent() + ":wrong");
}
}
QTIEditHelperEBL.addFeedbackFail(respcondition_fail);
QTIEditHelperEBL.addFeedbackHint(respcondition_fail);
QTIEditHelperEBL.addFeedbackSolution(respcondition_fail);
}
@Override
protected void setStatus(Element traceEventElement) {
String status = "";
Element element = traceEventElement.element("InteractionBytes");
if (element != null) {
status = element.getText();
status += "(b)";
}
setStatus(status);
}
private int readInt(Element e, QName attributeName, int defaultValue) throws MapException {
String s = e.attributeValue(attributeName);
if (s == null) {
return defaultValue;
}
try {
return Integer.parseInt(s);
}
catch (NumberFormatException ex) {
throw new MapException("Attribute " + attributeName + " is not an integer: " + e);
}
}
/**
* 设置或添加属性
* @param element
* @param name
* @param value
*/
public static void setAttribute(Element element, String name, String value) {
Attribute attribute = element.attribute(name);
if (attribute != null) {
attribute.setValue(value);
} else {
element.addAttribute(name, value);
}
}
/**
* Get the dataform that describes the publish options from the request, or null if no such form was included.
*
* @param iq The publish request (cannot be null).
* @return A publish options data form (possibly null).
*/
public static DataForm getPublishOptions( IQ iq )
{
final Element publishOptionsElement = iq.getChildElement().element( "publish-options" );
if ( publishOptionsElement == null )
{
return null;
}
final Element x = publishOptionsElement.element( QName.get( DataForm.ELEMENT_NAME, DataForm.NAMESPACE ) );
if ( x == null )
{
return null;
}
final DataForm result = new DataForm( x );
if ( result.getType() != DataForm.Type.submit )
{
return null;
}
final FormField formType = result.getField( "FORM_TYPE" );
if ( formType == null || !"http://jabber.org/protocol/pubsub#publish-options".equals( formType.getFirstValue() ) )
{
return null;
}
return result;
}
@Test
public void withMultiValueWithEditor() throws Exception {
this.tag.setPath("stringArray");
this.tag.setValue(" foo");
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
MyStringTrimmerEditor editor = new MyStringTrimmerEditor();
bindingResult.getPropertyEditorRegistry().registerCustomEditor(String.class, editor);
getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
assertEquals(1, editor.count);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("stringArray", checkboxElement.attribute("name").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
assertEquals(" foo", checkboxElement.attribute("value").getValue());
}
private TableGenerator getTableGenerator(Element tree, XMLContext.Default defaults) {
Element element = tree != null ? tree.element( annotationToXml.get( TableGenerator.class ) ) : null;
if ( element != null ) {
return buildTableGeneratorAnnotation( element, defaults );
}
else if ( defaults.canUseJavaAnnotations() && isPhysicalAnnotationPresent( TableGenerator.class ) ) {
TableGenerator tableAnn = getPhysicalAnnotation( TableGenerator.class );
if ( StringHelper.isNotEmpty( defaults.getSchema() )
|| StringHelper.isNotEmpty( defaults.getCatalog() ) ) {
AnnotationDescriptor annotation = new AnnotationDescriptor( TableGenerator.class );
annotation.setValue( "name", tableAnn.name() );
annotation.setValue( "table", tableAnn.table() );
annotation.setValue( "catalog", tableAnn.table() );
if ( StringHelper.isEmpty( (String) annotation.valueOf( "catalog" ) )
&& StringHelper.isNotEmpty( defaults.getCatalog() ) ) {
annotation.setValue( "catalog", defaults.getCatalog() );
}
annotation.setValue( "schema", tableAnn.table() );
if ( StringHelper.isEmpty( (String) annotation.valueOf( "schema" ) )
&& StringHelper.isNotEmpty( defaults.getSchema() ) ) {
annotation.setValue( "catalog", defaults.getSchema() );
}
annotation.setValue( "pkColumnName", tableAnn.pkColumnName() );
annotation.setValue( "valueColumnName", tableAnn.valueColumnName() );
annotation.setValue( "pkColumnValue", tableAnn.pkColumnValue() );
annotation.setValue( "initialValue", tableAnn.initialValue() );
annotation.setValue( "allocationSize", tableAnn.allocationSize() );
annotation.setValue( "uniqueConstraints", tableAnn.uniqueConstraints() );
return AnnotationFactory.create( annotation );
}
else {
return tableAnn;
}
}
else {
return null;
}
}
@SuppressWarnings("unchecked")
private void initializeCreditUnitTypeData(Element rootElement) throws Exception {
for (CourseCreditUnitType creditUnitType : CourseCreditUnitType.getCourseCreditUnitTypeList()) {
creditUnitTypesByRef.put(creditUnitType.getReference(), creditUnitType);
}
Element creditUnitTypesElement = rootElement.element(PointInTimeDataExport.sCreditUnitTypesElementName);
for(Element creditUnitTypeElement : (List<Element>) creditUnitTypesElement.elements()){
elementCreditUnitType(creditUnitTypeElement);
}
}
protected void exportArrHours(Element classElement, Class_ clazz, Session session) {
exportDatePattern(classElement, clazz.effectiveDatePattern(), session);
Element arrangeTimeEl = classElement.addElement("arrangeTime");
if (clazz.getSchedulingSubpart().getMinutesPerWk()!=null && clazz.getSchedulingSubpart().getMinutesPerWk()>0)
arrangeTimeEl.addAttribute("minPerWeek", clazz.getSchedulingSubpart().getMinutesPerWk().toString());
exportRequiredRooms(classElement, clazz, session);
}
public void save(Element element) {
element.addAttribute("class",String.valueOf(iClassId));
element.addAttribute("name", iName);
if (iPref!=null)
element.addAttribute("pref", iPref);
for (CBSValue v: iValues)
v.save(element.addElement("val"));
}
/**
* Sets the value of the specified property. If the property doesn't
* currently exist, it will be automatically created.
*
* @param element the element to set the property on
* @param name the name of the property to set.
* @param value the new value for the property.
*/
public static void setProperty(Element element, String name, String value) {
if (name == null || name.length() == 0) return;
if (value == null) value = "";
String[] propName = parsePropertyName(name);
// Search for this property by traversing down the XML heirarchy.
int i = propName[0].equals(element.getName()) ? 1 : 0;
for (; i < propName.length - 1; i++) {
// If we don't find this part of the property in the XML heirarchy
// we add it as a new node
if (element.element(propName[i]) == null) {
element.addElement(propName[i]);
}
element = element.element(propName[i]);
}
String lastName = propName[propName.length - 1];
int attributeIndex = lastName.indexOf(':');
if (attributeIndex >= 0) {
String eleName = lastName.substring(0, attributeIndex);
String attName = lastName.substring(attributeIndex + 1);
// If we don't find this part of the property in the XML heirarchy
// we add it as a new node
if (element.element(eleName) == null) {
element.addElement(eleName);
}
element.element(eleName).addAttribute(attName, value);
}
else {
// If we don't find this part of the property in the XML heirarchy
// we add it as a new node
if (element.element(lastName) == null) {
element.addElement(lastName);
}
// Set the value of the property in this node.
element.element(lastName).setText(value);
}
}
public static Object convert(@Comments("xml content") String content,
@Comments("xml structure with javabean class") Class<?> cls)
throws DocumentException, IllegalAccessException, InvocationTargetException, InstantiationException {
if (null == cls) return null;
parseFieldsAttribute(cls);
//将xml格式的字符串转换成Document对象
Document doc = DocumentHelper.parseText(content);
//获取根节点
Element root = doc.getRootElement();
return mergerXmlNodeAndField(root, configClasssAttr);
}
Element addXMLElement(final Element parent)
{
final Element el = parent.addElement("task").addAttribute("id", String.valueOf(this.getId()))
.addAttribute("name", this.task.getTitle());
if (this.childs != null) {
for (final TaskNode node : this.childs) {
node.addXMLElement(el);
}
}
return el;
}
@Test
public void multipleForCollection() throws Exception {
this.bean.setSomeList(new ArrayList());
this.tag.setPath("someList");
this.tag.setItems(Country.getCountries());
this.tag.setItemValue("isoCode");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
assertEquals(2, rootElement.elements().size());
Element selectElement = rootElement.element("select");
assertEquals("select", selectElement.getName());
assertEquals("someList", selectElement.attribute("name").getValue());
assertEquals("multiple", selectElement.attribute("multiple").getValue());
List children = selectElement.elements();
assertEquals("Incorrect number of children", 4, children.size());
Element inputElement = rootElement.element("input");
assertNotNull(inputElement);
}
@SuppressWarnings("unchecked")
private void elementClassEvent(Element classEventElement, PitClass pc) throws Exception {
PitClassEvent pce = new PitClassEvent();
pce.setPitClass(pc);
pc.addTopitClassEvents(pce);
pce.setEventName(getRequiredStringAttribute(classEventElement, PointInTimeDataExport.sNameAttribute, PointInTimeDataExport.sClassEventElementName));
pce.setUniqueId((Long) getHibSession().save(pce));
for(Element classMeetingElement : (List<Element>) classEventElement.elements()){
elementClassMeeting(classMeetingElement, pce);
}
}
private void parseConnector(Element tmp,ZipOutputStream out,String type,String folderName) throws Exception{
String id = tmp.attributeValue("id");
String packageName = tmp.attributeValue("package");
String connectorXmlName = "";
if(type.equals("flowConnector")){
connectorXmlName = "FlowConnector.xml";
}else if(type.equals("actorConnector")){
connectorXmlName = "ActorConnector.xml";
}else{
throw new FoxBPMException("不支持的连接器类型:"+type);
}
String xmlFileName = packageName + "/" + connectorXmlName;
String pngFileName = packageName + "/" + id + ".png";
String xmlEntryName = folderName + "/" + id + "/" + connectorXmlName;
String pngEntryName = folderName + "/" + id + "/" + id + ".png";
InputStream xmlInputStream = ReflectUtil.getResourceAsStream(xmlFileName);
if(xmlInputStream == null){
log.error("文件:{}不存在,跳过处理,该连接器可能不可用!" ,xmlFileName);
return;
}else{
generZip(xmlInputStream,xmlEntryName,out);
}
InputStream pngInputStream = ReflectUtil.getResourceAsStream(pngFileName);
if(pngInputStream == null){
pngFileName = packageName + "/" + id + ".jpg";
pngInputStream = ReflectUtil.getResourceAsStream(pngFileName);
}
if(pngInputStream == null){
log.error("文件:{}不存在,跳过处理,该连接器可能不可用!" ,pngFileName);
}else{
generZip(pngInputStream,pngEntryName,out);
}
}