use of org.w3c.dom.ls.LSParser in project languagetool by languagetool-org.
the class PatternRuleXmlCreator method getDocument.
private Document getDocument(InputStream is) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
LSParser parser = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
// we need to ignore whitespace here so the nodeToString() method will be able to indent it properly:
parser.setFilter(new IgnoreWhitespaceFilter());
LSInput domInput = impl.createLSInput();
domInput.setByteStream(is);
return parser.parse(domInput);
}
use of org.w3c.dom.ls.LSParser in project titan.EclipsePlug-ins by eclipse.
the class TITANProjectExporter method saveAll.
/**
* Saves all project information of "project" into the tpd file given output
* file "projectFile" Prerequisites: project and projectFile are set properly
*
* @return true if the save was successful
*/
public boolean saveAll() {
if (project == null) {
ErrorReporter.logError("Invalid project");
return false;
}
if (projectFile == null || projectFile.trim().length() == 0) {
return false;
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
ErrorReporter.logExceptionStackTrace(e);
return false;
}
DOMImplementation impl = builder.getDOMImplementation();
final Document document = impl.createDocument(null, "TITAN_Project_File_Information", null);
Element root = document.getDocumentElement();
root.setAttribute("version", "1.0");
boolean result = saveProjectInformation(root, project, packAllProjectsIntoOne, !packAllProjectsIntoOne);
if (!result) {
return false;
}
ProjectFileHandler.indentNode(document, document.getDocumentElement(), 1);
System.setProperty(DOMImplementationRegistry.PROPERTY, ProjectFormatConstants.DOM_IMPLEMENTATION_SOURCE);
DOMImplementationRegistry registry = null;
try {
registry = DOMImplementationRegistry.newInstance();
} catch (ClassNotFoundException ce) {
ErrorReporter.logExceptionStackTrace(ce);
return false;
} catch (InstantiationException ie) {
ErrorReporter.logExceptionStackTrace(ie);
return false;
} catch (IllegalAccessException iae) {
ErrorReporter.logExceptionStackTrace(iae);
return false;
}
// Specifying "LS 3.0" in the features list ensures that the
// DOMImplementation
// object implements the load and save features of the DOM 3.0
// specification.
DOMImplementation domImpl = registry.getDOMImplementation(ProjectFormatConstants.LOAD_SAVE_VERSION);
DOMImplementationLS domImplLS = (DOMImplementationLS) domImpl;
// If the mode is MODE_SYNCHRONOUS, the parse and parseURI
// methods of the LSParser
// object return the org.w3c.dom.Document object. If the mode is
// MODE_ASYNCHRONOUS,
// the parse and parseURI methods return null.
LSParser parser = domImplLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, ProjectFormatConstants.XML_SCHEMA);
DOMConfiguration config = parser.getDomConfig();
DOMErrorHandlerImpl errorHandler = new DOMErrorHandlerImpl();
config.setParameter("error-handler", errorHandler);
config.setParameter("validate", Boolean.TRUE);
config.setParameter("schema-type", ProjectFormatConstants.XML_SCHEMA);
config.setParameter("validate-if-schema", Boolean.TRUE);
LSSerializer dom3Writer = domImplLS.createLSSerializer();
LSOutput output = domImplLS.createLSOutput();
IPath projectFilePath = Path.fromOSString(projectFile);
URI projectFileURI = URIUtil.toURI(projectFilePath);
try {
StringWriter sw = new StringWriter();
output.setCharacterStream(sw);
output.setEncoding("UTF-8");
dom3Writer.write(document, output);
String temporaloutput = sw.getBuffer().toString();
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(projectFile));
bufferedWriter.write(temporaloutput);
bufferedWriter.flush();
bufferedWriter.close();
IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(projectFileURI);
for (final IFile file : files) {
file.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
}
} catch (IOException e) {
ErrorReporter.logExceptionStackTrace(e);
} catch (final CoreException e) {
ErrorReporter.logExceptionStackTrace(e);
}
ProjectBuildPropertyData.setLoadLocation(project, projectFileURI.getPath().toString());
ProjectBuildPropertyData.setProjectAlreadyExported(project, true);
return true;
}
use of org.w3c.dom.ls.LSParser in project cuba by cuba-platform.
the class XMLConverter method parseCommitRequest.
@Override
public CommitRequest parseCommitRequest(String content) {
try {
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS lsImpl = (DOMImplementationLS) registry.getDOMImplementation("LS");
LSParser requestConfigParser = lsImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
// Set options on the parser
DOMConfiguration config = requestConfigParser.getDomConfig();
config.setParameter("validate", Boolean.TRUE);
config.setParameter("element-content-whitespace", Boolean.FALSE);
config.setParameter("comments", Boolean.FALSE);
requestConfigParser.setFilter(new LSParserFilter() {
@Override
public short startElement(Element elementArg) {
return LSParserFilter.FILTER_ACCEPT;
}
@Override
public short acceptNode(Node nodeArg) {
return StringUtils.isBlank(nodeArg.getTextContent()) ? LSParserFilter.FILTER_REJECT : LSParserFilter.FILTER_ACCEPT;
}
@Override
public int getWhatToShow() {
return NodeFilter.SHOW_TEXT;
}
});
LSInput lsInput = lsImpl.createLSInput();
lsInput.setStringData(content);
Document commitRequestDoc = requestConfigParser.parse(lsInput);
Node rootNode = commitRequestDoc.getFirstChild();
if (!"CommitRequest".equals(rootNode.getNodeName()))
throw new IllegalArgumentException("Not a CommitRequest xml passed: " + rootNode.getNodeName());
CommitRequest result = new CommitRequest();
NodeList children = rootNode.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
String childNodeName = child.getNodeName();
if ("commitInstances".equals(childNodeName)) {
NodeList entitiesNodeList = child.getChildNodes();
Set<String> commitIds = new HashSet<>(entitiesNodeList.getLength());
for (int j = 0; j < entitiesNodeList.getLength(); j++) {
Node idNode = entitiesNodeList.item(j).getAttributes().getNamedItem("id");
if (idNode == null)
continue;
String id = idNode.getTextContent();
if (id.startsWith("NEW-"))
id = id.substring(id.indexOf('-') + 1);
commitIds.add(id);
}
result.setCommitIds(commitIds);
result.setCommitInstances(parseNodeList(result, entitiesNodeList));
} else if ("removeInstances".equals(childNodeName)) {
NodeList entitiesNodeList = child.getChildNodes();
List removeInstances = parseNodeList(result, entitiesNodeList);
result.setRemoveInstances(removeInstances);
} else if ("softDeletion".equals(childNodeName)) {
result.setSoftDeletion(Boolean.parseBoolean(child.getTextContent()));
}
}
return result;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
use of org.w3c.dom.ls.LSParser in project syncope by apache.
the class MavenUtils method createSettingsWithProxy.
public static File createSettingsWithProxy(final String path, final String proxyHost, final String proxyPort, final String proxyUser, final String proxyPassword) throws Exception {
final File settingsXML = new File(System.getProperty(MAVEN_HOME_PROPERTY) + (System.getProperty(MAVEN_HOME_PROPERTY).endsWith("/") ? "conf/settings.xml" : "/conf/settings.xml"));
final File tempSettingsXML = new File(path + (path.endsWith("/") ? "settings_temp.xml" : "/settings_temp.xml"));
if (settingsXML.canRead() && !tempSettingsXML.exists()) {
tempSettingsXML.createNewFile();
DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance();
DOMImplementationLS domImpl = (DOMImplementationLS) reg.getDOMImplementation("LS");
LSInput lsinput = domImpl.createLSInput();
lsinput.setByteStream(new FileInputStream(settingsXML));
LSParser parser = domImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
// parse settings.xml
final Document settings = parser.parse(lsinput);
final Element proxies = (Element) settings.getDocumentElement().getElementsByTagName("proxies").item(0);
final Element proxy = settings.createElement("proxy");
final Element id = settings.createElement("id");
final Element active = settings.createElement("active");
final Element protocol = settings.createElement("protocol");
final Element host = settings.createElement("host");
final Element port = settings.createElement("port");
final Element nonProxyHosts = settings.createElement("nonProxyHosts");
id.appendChild(settings.createTextNode("optional"));
active.appendChild(settings.createTextNode("true"));
protocol.appendChild(settings.createTextNode("http"));
host.appendChild(settings.createTextNode(proxyHost));
port.appendChild(settings.createTextNode(proxyPort));
proxy.appendChild(id);
proxy.appendChild(active);
proxy.appendChild(protocol);
// create username and password tags only if required
if (proxyUser != null && !proxyUser.isEmpty() && proxyPassword != null) {
final Element username = settings.createElement("username");
final Element password = settings.createElement("password");
username.appendChild(settings.createTextNode(proxyUser));
password.appendChild(settings.createTextNode(proxyPassword));
proxy.appendChild(username);
proxy.appendChild(password);
}
proxy.appendChild(host);
proxy.appendChild(port);
proxy.appendChild(nonProxyHosts);
proxies.appendChild(proxy);
FileSystemUtils.writeXML(settings, Files.newOutputStream(tempSettingsXML.toPath()));
}
return tempSettingsXML;
}
use of org.w3c.dom.ls.LSParser in project syncope by apache.
the class CamelRouteLoader method loadRoutes.
private void loadRoutes(final String domain, final DataSource dataSource, final Resource resource, final AnyTypeKind anyTypeKind) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
boolean shouldLoadRoutes = jdbcTemplate.queryForList(String.format("SELECT * FROM %s WHERE ANYTYPEKIND = ?", CamelRoute.class.getSimpleName()), new Object[] { anyTypeKind.name() }).isEmpty();
if (shouldLoadRoutes) {
try {
TransformerFactory tf = null;
DOMImplementationLS domImpl = null;
NodeList routeNodes;
if (IS_JBOSS) {
tf = TransformerFactory.newInstance();
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
tf.setURIResolver((href, base) -> null);
Document doc = StaxUtils.read(resource.getInputStream());
routeNodes = doc.getDocumentElement().getElementsByTagName("route");
} else {
DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance();
domImpl = (DOMImplementationLS) reg.getDOMImplementation("LS");
LSInput lsinput = domImpl.createLSInput();
lsinput.setByteStream(resource.getInputStream());
LSParser parser = domImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
routeNodes = parser.parse(lsinput).getDocumentElement().getElementsByTagName("route");
}
for (int s = 0; s < routeNodes.getLength(); s++) {
Node routeElement = routeNodes.item(s);
String routeContent = IS_JBOSS ? nodeToString(routeNodes.item(s), tf) : nodeToString(routeNodes.item(s), domImpl);
String routeId = ((Element) routeElement).getAttribute("id");
jdbcTemplate.update(String.format("INSERT INTO %s(ID, ANYTYPEKIND, CONTENT) VALUES (?, ?, ?)", CamelRoute.class.getSimpleName()), new Object[] { routeId, anyTypeKind.name(), routeContent });
LOG.info("[{}] Route successfully loaded: {}", domain, routeId);
}
} catch (Exception e) {
LOG.error("[{}] Route load failed", domain, e);
}
}
}
Aggregations