Java Code Examples for com.thoughtworks.xstream.io.xml.PrettyPrintWriter

The following examples show how to use com.thoughtworks.xstream.io.xml.PrettyPrintWriter. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: jeewx-boot   Source File: MessageUtil.java    License: Apache License 2.0 6 votes vote down vote up
public HierarchicalStreamWriter createWriter(Writer out) {
    return new PrettyPrintWriter(out) {
        // 对所有xml节点的转换都增加CDATA标记
        boolean cdata = true;

        @SuppressWarnings("unchecked")
        public void startNode(String name, Class clazz) {
            super.startNode(name, clazz);
        }

        protected void writeText(QuickWriter writer, String text) {
            if (cdata) {
                    writer.write("<![CDATA[");
                    writer.write(text);
                    writer.write("]]>");
            } else {
                    writer.write(text);
            }
        }
    };
}
 
Example 2
Source Project: WeChatEnterprise   Source File: WXMessageUtil.java    License: Apache License 2.0 6 votes vote down vote up
public HierarchicalStreamWriter createWriter(Writer out) {
	return new PrettyPrintWriter(out) {
		// 对所有xml节点的转换都增加CDATA标记
		boolean cdata = true;

		public void startNode(String name, Class clazz) {
			super.startNode(name, clazz);
		}

		protected void writeText(QuickWriter writer, String text) {
			if (cdata) {
				writer.write("<![CDATA[");
				writer.write(text);
				writer.write("]]>");
			} else {
				writer.write(text);
			}
		}
	};
}
 
Example 3
public HierarchicalStreamWriter createWriter(Writer out) {
	return new PrettyPrintWriter(out) {
		boolean CDATA = true;
		
		@SuppressWarnings("rawtypes")
		public void startNode(String name, Class clazz) {
			super.startNode(name, clazz);
		}
		protected void writeText(QuickWriter writer, String text) {
			if (CDATA) {
				writer.write("<![CDATA[");
				writer.write(text);
				writer.write("]]>");
			} else {
				writer.write(text);
			}
		}
	};
}
 
Example 4
Source Project: wechat-core   Source File: MessageUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 扩展xstream,使其支持CDATA块
 */
private static XStream newXStreamInstance() {
    return new XStream(new XppDriver() {
        @Override
        public HierarchicalStreamWriter createWriter(Writer out) {
            return new PrettyPrintWriter(out) {
                // 对所有xml节点的转换都增加CDATA标记
                boolean cdata = true;

                @Override
                protected void writeText(QuickWriter writer, String text) {
                    if (this.cdata) {
                        writer.write("<![CDATA[");
                        writer.write(text);
                        writer.write("]]>");
                    } else {
                        writer.write(text);
                    }
                }
            };
        }
    });
}
 
Example 5
Source Project: jeewx   Source File: MessageUtil.java    License: Apache License 2.0 6 votes vote down vote up
public HierarchicalStreamWriter createWriter(Writer out) {
    return new PrettyPrintWriter(out) {
        // 对所有xml节点的转换都增加CDATA标记
        boolean cdata = true;

        @SuppressWarnings("unchecked")
        public void startNode(String name, Class clazz) {
            super.startNode(name, clazz);
        }

        protected void writeText(QuickWriter writer, String text) {
            if (cdata) {
                    writer.write("<![CDATA[");
                    writer.write(text);
                    writer.write("]]>");
            } else {
                    writer.write(text);
            }
        }
    };
}
 
Example 6
Source Project: jeewx   Source File: MessageUtil.java    License: Apache License 2.0 6 votes vote down vote up
public HierarchicalStreamWriter createWriter(Writer out) {
    return new PrettyPrintWriter(out) {
        // 对所有xml节点的转换都增加CDATA标记
        boolean cdata = true;

        @SuppressWarnings("unchecked")
        public void startNode(String name, Class clazz) {
            super.startNode(name, clazz);
        }

        protected void writeText(QuickWriter writer, String text) {
            if (cdata) {
                    writer.write("<![CDATA[");
                    writer.write(text);
                    writer.write("]]>");
            } else {
                    writer.write(text);
            }
        }
    };
}
 
Example 7
Source Project: mamute   Source File: QuestionRssEntryFactory.java    License: Apache License 2.0 6 votes vote down vote up
private XStream buildXstream() {
	return new XStream(new XppDriver() {
		public HierarchicalStreamWriter createWriter(Writer out) {
			return new PrettyPrintWriter(out) {
				List<String> cdataFields = asList("title", "author");
				boolean cdata = false;
				
				public void startNode(String name, Class clazz) {
					super.startNode(name, clazz);
					cdata = cdataFields.contains(name);
				}
				protected void writeText(QuickWriter writer, String text) {
					if (cdata) {
						writer.write("<![CDATA[");
						writer.write(text);
						writer.write("]]>");
					} else {
						writer.write(text);
					}
				}
			};
		}
	});
}
 
Example 8
Source Project: olat   Source File: GlossaryItemManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * writes glossary to xml-file prepend doc-book dtd: <!DOCTYPE glossary PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
 * "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd">
 * 
 * @param glossaryFile
 * @param glossaryItemArr
 */
private void saveToFile(VFSLeaf glossaryFile, ArrayList<GlossaryItem> glossaryItemArr) {
    // cdata-tags should be used instead of strings, overwrite writer.
    XStream xstream = new XStream(new XppDriver() {
        @Override
        public HierarchicalStreamWriter createWriter(Writer out) {
            return new PrettyPrintWriter(out) {
                @Override
                protected void writeText(QuickWriter writer, String text) {
                    if (text.contains("<") || text.contains(">") || text.contains("&")) {
                        writer.write("<![CDATA[");
                        writer.write(text);
                        writer.write("]]>");
                    } else {
                        writer.write(text);
                    }
                }
            };
        }
    });

    xstream.alias(XML_GLOSSARY_ITEM_NAME, GlossaryItem.class);
    glossaryItemArr = removeEmptyGlossaryItems(glossaryItemArr);
    XStreamHelper.writeObject(xstream, glossaryFile, glossaryItemArr);
}
 
Example 9
Source Project: olat   Source File: GlossaryItemManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * writes glossary to xml-file prepend doc-book dtd: <!DOCTYPE glossary PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
 * "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd">
 * 
 * @param glossaryFile
 * @param glossaryItemArr
 */
private void saveToFile(VFSLeaf glossaryFile, ArrayList<GlossaryItem> glossaryItemArr) {
    // cdata-tags should be used instead of strings, overwrite writer.
    XStream xstream = new XStream(new XppDriver() {
        @Override
        public HierarchicalStreamWriter createWriter(Writer out) {
            return new PrettyPrintWriter(out) {
                @Override
                protected void writeText(QuickWriter writer, String text) {
                    if (text.contains("<") || text.contains(">") || text.contains("&")) {
                        writer.write("<![CDATA[");
                        writer.write(text);
                        writer.write("]]>");
                    } else {
                        writer.write(text);
                    }
                }
            };
        }
    });

    xstream.alias(XML_GLOSSARY_ITEM_NAME, GlossaryItem.class);
    glossaryItemArr = removeEmptyGlossaryItems(glossaryItemArr);
    XStreamHelper.writeObject(xstream, glossaryFile, glossaryItemArr);
}
 
Example 10
Source Project: javalite   Source File: CDATAXppDriver.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public HierarchicalStreamWriter createWriter(Writer out) {
    return new PrettyPrintWriter(out) {
        boolean cdata;
        @Override
        public void startNode(String name, Class clazz) {
            super.startNode(name, clazz);
            cdata = CharSequence.class.isAssignableFrom(clazz);
        }
        @Override
        protected void writeText(QuickWriter writer, String text) {
            if(cdata) {
                writer.write("<![CDATA[");
                writer.write(text);
                writer.write("]]>");
            } else {
                writer.write(text);
            }
        }
    };
}
 
Example 11
Source Project: weixin-java-tools   Source File: XStreamInitializer.java    License: Apache License 2.0 5 votes vote down vote up
public static XStream getInstance() {
  XStream xstream = new XStream(new PureJavaReflectionProvider(), new XppDriver() {

    @Override
    public HierarchicalStreamWriter createWriter(Writer out) {
      return new PrettyPrintWriter(out, getNameCoder()) {
        protected String PREFIX_CDATA = "<![CDATA[";
        protected String SUFFIX_CDATA = "]]>";
        protected String PREFIX_MEDIA_ID = "<MediaId>";
        protected String SUFFIX_MEDIA_ID = "</MediaId>";

        @Override
        protected void writeText(QuickWriter writer, String text) {
          if (text.startsWith(this.PREFIX_CDATA) && text.endsWith(this.SUFFIX_CDATA)) {
            writer.write(text);
          } else if (text.startsWith(this.PREFIX_MEDIA_ID) && text.endsWith(this.SUFFIX_MEDIA_ID)) {
            writer.write(text);
          } else {
            super.writeText(writer, text);
          }

        }

        @Override
        public String encodeNode(String name) {
          //防止将_转换成__
          return name;
        }
      };
    }
  });

  xstream.ignoreUnknownElements();
  xstream.setMode(XStream.NO_REFERENCES);
  xstream.addPermission(NullPermission.NULL);
  xstream.addPermission(PrimitiveTypePermission.PRIMITIVES);
  xstream.setClassLoader(Thread.currentThread().getContextClassLoader());
  return xstream;
}
 
Example 12
public void parse(File inputDir, File outputFile)
        throws Exception
{
    Map<String, RFDDebate> debates = new TreeMap<>();

    for (File f : FileUtils.listFiles(inputDir, new String[] { "html" }, false)) {
        try {
            String html = FileUtils.readFileToString(f);
            // first identify debate
            RFDDebate debate = extractRFDDebate(html);

            // only for debates we have explicit stances
            String url = debate.getDebateUrl().split("/")[5];
            if (urlStances.containsKey(url)) {
                // assign possible stances
                assignStances(debate);

                if (!debates.containsKey(debate.getDebateUrl())) {
                    debates.put(debate.getDebateUrl(), debate);
                }

                RFDArticle RFDArticle = extractRFDArticle(html);
                debates.get(debate.getDebateUrl()).getArticleList().add(RFDArticle);
            }
        }
        catch (Exception e) {
            System.err.println("Error: " + f);
            throw e;
        }
    }

    // save to xStream
    OutputStreamWriter writer = new OutputStreamWriter(
            new FileOutputStream(outputFile), "utf-8");
    writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
    XStreamTools.getXStream().marshal(
            new ArrayList<>(debates.values()), new PrettyPrintWriter(writer));
    IOUtils.closeQuietly(writer);
}
 
Example 13
public static String serializeToXML(Debate debate)
{
    StringWriter sw = new StringWriter();
    sw.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
    getXStream().marshal(debate, new PrettyPrintWriter(new PrintWriter(sw)));

    return sw.toString();
}
 
Example 14
@Override
public void writeNode(ZigBeeNodeDao node) {
    XStream stream = openStream();
    File file = getFile(node.getIeeeAddress());

    try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))) {
        stream.marshal(node, new PrettyPrintWriter(writer));
        logger.info("{}: ZigBee saving network state complete.", node.getIeeeAddress());
    } catch (Exception e) {
        logger.error("{}: Error writing network state: ", node.getIeeeAddress(), e);
    }
}
 
Example 15
Source Project: Digital   Source File: Circuit.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Stores the circuit in the given file
 *
 * @param out the writer
 * @throws IOException IOException
 */
public void save(OutputStream out) throws IOException {
    try (Writer w = new OutputStreamWriter(out, StandardCharsets.UTF_8)) {
        XStream xStream = Circuit.getxStream();
        w.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        xStream.marshal(this, new PrettyPrintWriter(w));
    }
}
 
Example 16
Source Project: Digital   Source File: TruthTable.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Writes the table to the given file.
 *
 * @param filename the file
 * @throws IOException IOException
 */
public void save(File filename) throws IOException {
    XStream xStream = getxStream();
    try (Writer out = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8)) {
        out.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        xStream.marshal(this, new PrettyPrintWriter(out));
    }
}
 
Example 17
Source Project: Digital   Source File: FSM.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Stores the circuit in the given file
 *
 * @param out the writer
 * @throws IOException IOException
 */
public void save(OutputStream out) throws IOException {
    try (Writer w = new OutputStreamWriter(out, StandardCharsets.UTF_8)) {
        XStream xStream = getxStream();
        w.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        xStream.marshal(this, new PrettyPrintWriter(w));
        modified = false;
        if (modifiedListener != null)
            modifiedListener.modifiedChanged(modified);
    }
}
 
Example 18
Source Project: Digital   Source File: SettingsBase.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void attributeChanged() {
    XStream xStream = Circuit.getxStream();
    try (Writer out = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8)) {
        out.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        xStream.marshal(attributes, new PrettyPrintWriter(out));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 19
Source Project: Digital   Source File: CircuitTransferable.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a new instance
 *
 * @param data the data to copy
 */
CircuitTransferable(ArrayList<Movable> data) {
    XStream xStream = Circuit.getxStream();
    try (StringWriter out = new StringWriter()) {
        out.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        xStream.marshal(data, new PrettyPrintWriter(out));
        this.data = out.toString();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 20
Source Project: Digital   Source File: Resources.java    License: GNU General Public License v3.0 5 votes vote down vote up
void save(OutputStream out) throws IOException {
    XStream xStream = getxStream();
    try (Writer w = new OutputStreamWriter(out, StandardCharsets.UTF_8)) {
        w.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        xStream.marshal(resourceMap, new PrettyPrintWriter(w));
    }
}
 
Example 21
Source Project: weChatRobot   Source File: XmlUtil.java    License: MIT License 5 votes vote down vote up
@Override
public HierarchicalStreamWriter createWriter(Writer out) {
    return new PrettyPrintWriter(out) {
        @Override
        protected void writeText(QuickWriter writer, String text) {
            //对所有xml节点的转换都增加CDATA标记
            writer.write("<![CDATA[");
            writer.write(text);
            writer.write("]]>");
        }
    };
}
 
Example 22
Source Project: audit4j-core   Source File: XMLConfigProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * 
 * 
 */
@Override
public void generateConfig(T config, String filePath) throws ConfigurationException {
    XStream xstream = new XStream(new StaxDriver());
    xstream.alias("configuration", clazz);
    BufferedOutputStream stdout = null;
    try {
        stdout = new BufferedOutputStream(new FileOutputStream(filePath));
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    xstream.marshal(config, new PrettyPrintWriter(new OutputStreamWriter(stdout)));
}
 
Example 23
Source Project: weixin-java-tools   Source File: XStreamInitializer.java    License: Apache License 2.0 5 votes vote down vote up
public static XStream getInstance() {
  XStream xstream = new XStream(new XppDriver() {

    @Override
    public HierarchicalStreamWriter createWriter(Writer out) {
      return new PrettyPrintWriter(out, getNameCoder()) {
        protected String PREFIX_CDATA = "<![CDATA[";
        protected String SUFFIX_CDATA = "]]>";
        protected String PREFIX_MEDIA_ID = "<MediaId>";
        protected String SUFFIX_MEDIA_ID = "</MediaId>";
        @Override
        protected void writeText(QuickWriter writer, String text) {
          if (text.startsWith(PREFIX_CDATA) && text.endsWith(SUFFIX_CDATA)) {
            writer.write(text);
          } else if (text.startsWith(PREFIX_MEDIA_ID) && text.endsWith(SUFFIX_MEDIA_ID)) {
            writer.write(text);
          } else {
            super.writeText(writer, text);
          }

        }
      };
    }
  });
  xstream.ignoreUnknownElements();
  xstream.setMode(XStream.NO_REFERENCES);
  xstream.addPermission(NullPermission.NULL);
  xstream.addPermission(PrimitiveTypePermission.PRIMITIVES);
  return xstream;
}
 
Example 24
Source Project: vraptor4   Source File: XStreamXMLSerialization.java    License: Apache License 2.0 5 votes vote down vote up
protected HierarchicalStreamWriter getWriter() {
	try {
		PrintWriter writer = response.getWriter();
		return indented ? new PrettyPrintWriter(writer) : new CompactWriter(writer);
	} catch (IOException e) {
		throw new ResultException("Unable to serialize data", e);
	}
}
 
Example 25
Source Project: oval   Source File: XIncludeAwareDOMDriver.java    License: Eclipse Public License 2.0 4 votes vote down vote up
@Override
public HierarchicalStreamWriter createWriter(final Writer out) {
   return new PrettyPrintWriter(out, NAME_CODER);
}
 
Example 26
/**
 * @param writer
 * @param includeHistory
 * @param session
 * @throws DataAccessException
 * @throws HibernateException
 */
private void writeObjects(final Writer writer, final boolean includeHistory, final Session session, final boolean preserveIds)
    throws DataAccessException, HibernateException
    {
  // Container für die Objekte
  final List<Object> all = new ArrayList<Object>();
  final XStream stream = initXStream(session, true);
  final XStream defaultXStream = initXStream(session, false);

  session.flush();
  // Alles laden
  final List<Class< ? >> entities = new ArrayList<Class< ? >>();
  entities.addAll(HibernateEntities.instance().getOrderedEntities());
  entities.addAll(HibernateEntities.instance().getOrderedHistoryEntities());
  for (final Class< ? > entityClass : entities) {
    final String entitySimpleName = entityClass.getSimpleName();
    final String entityType = entityClass.getName();
    if (includeHistory == false && entityType.startsWith("de.micromata.hibernate.history.") == true) {
      // Skip history entries.
      continue;
    }
    List< ? > list = session.createQuery("select o from " + entityType + " o").setReadOnly(true).list();
    list = (List< ? >) CollectionUtils.select(list, PredicateUtils.uniquePredicate());
    final int size = list.size();
    log.info("Writing " + size + " objects");
    for (final Iterator< ? > it = list.iterator(); it.hasNext();) {
      final Object obj = it.next();
      if (log.isDebugEnabled()) {
        log.debug("loaded object " + obj);
      }
      Hibernate.initialize(obj);
      final Class< ? > targetClass = HibernateProxyHelper.getClassWithoutInitializingProxy(obj);
      final ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(targetClass);
      if (classMetadata == null) {
        log.fatal("Can't init " + obj + " of type " + targetClass);
        continue;
      }
      // initalisierung des Objekts...
      defaultXStream.marshal(obj, new CompactWriter(new NullWriter()));

      if (preserveIds == false) {
        // Nun kann die ID gelöscht werden
        classMetadata.setIdentifier(obj, null, EntityMode.POJO);
      }
      if (log.isDebugEnabled()) {
        log.debug("loading evicted object " + obj);
      }
      if (this.ignoreFromTopLevelListing.contains(targetClass) == false) {
        all.add(obj);
      }
    }
  }
  // und schreiben
  try {
    writer.write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n");
  } catch (final IOException ex) {
    // ignore, will fail on stream.marshal()
  }
  log.info("Wrote " + all.size() + " objects");
  final MarshallingStrategy marshallingStrategy = new ProxyIdRefMarshallingStrategy();
  stream.setMarshallingStrategy(marshallingStrategy);
  stream.marshal(all, new PrettyPrintWriter(writer));
    }
 
Example 27
Source Project: weblaf   Source File: XmlDriver.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Override
public HierarchicalStreamWriter createWriter ( final Writer out )
{
    return new PrettyPrintWriter ( out, getNameCoder () );
}
 
Example 28
public HierarchicalStreamWriter createWriter(Writer out) {
	return new PrettyPrintWriter(out);
}
 
Example 29
Source Project: vraptor4   Source File: XStreamSerializer.java    License: Apache License 2.0 4 votes vote down vote up
public XStreamSerializer(XStream xstream, Writer writer) {
	this(xstream, new PrettyPrintWriter(writer));
}