use of org.jdom2.Content in project JMRI by JMRI.
the class BlockValueFile method writeBlockValues.
/*
* Writes out block values to a file in the user's preferences directory
* If there are no defined Blocks, no file is written.
* If none of the defined Blocks have values, no file is written.
*/
public void writeBlockValues() throws java.io.IOException {
log.debug("entered writeBlockValues");
List<String> blocks = blockManager.getSystemNameList();
if (blocks.size() > 0) {
// there are blocks defined, create root element
root = new Element("block_values");
doc = newDocument(root, dtdLocation + "block-values.dtd");
boolean valuesFound = false;
// add XSLT processing instruction
// <?xml-stylesheet type="text/xsl" href="XSLT/block-values.xsl"?>
java.util.Map<String, String> m = new java.util.HashMap<String, String>();
m.put("type", "text/xsl");
m.put("href", xsltLocation + "blockValues.xsl");
org.jdom2.ProcessingInstruction p = new org.jdom2.ProcessingInstruction("xml-stylesheet", m);
doc.addContent(0, p);
// save block values in xml format
Element values = new Element("blockvalues");
for (int i = 0; i < blocks.size(); i++) {
String sname = blocks.get(i);
Block b = blockManager.getBySystemName(sname);
if (b != null) {
Object o = b.getValue();
if (o != null) {
// block has value, save it
Element val = new Element("block");
val.setAttribute("systemname", sname);
if (o instanceof jmri.jmrit.roster.RosterEntry) {
val.setAttribute("value", ((jmri.jmrit.roster.RosterEntry) o).getId());
val.setAttribute("valueClass", "jmri.jmrit.roster.RosterEntry");
} else {
val.setAttribute("value", o.toString());
}
int v = b.getDirection();
if (v != jmri.Path.NONE) {
val.setAttribute("dir", "" + v);
}
values.addContent(val);
valuesFound = true;
}
} else {
log.error("Block " + sname + " was not found.");
}
}
root.addContent(values);
// write out the file if values were found
if (valuesFound) {
try {
if (!checkFile(defaultFileName)) {
// file does not exist, create it
File file = new File(defaultFileName);
if (// create and check result
!file.createNewFile()) {
log.error("createNewFile failed");
}
}
// write content to file
writeXML(findFile(defaultFileName), doc);
} catch (java.io.IOException ioe) {
log.error("IO Exception " + ioe);
throw (ioe);
}
}
}
}
use of org.jdom2.Content in project JMRI by JMRI.
the class PanelEditorXml method load.
/**
* Create a PanelEditor object, then register and fill it, then pop it in a
* JFrame
*
* @param shared Top level Element to unpack.
* @return true if successful
*/
@Override
public boolean load(Element shared, Element perNode) {
boolean result = true;
// find coordinates
int x = 0;
int y = 0;
int height = 400;
int width = 300;
try {
x = shared.getAttribute("x").getIntValue();
y = shared.getAttribute("y").getIntValue();
height = shared.getAttribute("height").getIntValue();
width = shared.getAttribute("width").getIntValue();
} catch (org.jdom2.DataConversionException e) {
log.error("failed to convert PanelEditor's attribute");
result = false;
}
// find the name
String name = "Panel";
if (shared.getAttribute("name") != null) {
name = shared.getAttribute("name").getValue();
}
// confirm that panel hasn't already been loaded
if (jmri.jmrit.display.PanelMenu.instance().isPanelNameUsed(name)) {
log.warn("File contains a panel with the same name (" + name + ") as an existing panel");
result = false;
}
PanelEditor panel = new PanelEditor(name);
//panel.makeFrame(name);
jmri.jmrit.display.PanelMenu.instance().addEditorPanel(panel);
panel.getTargetFrame().setLocation(x, y);
panel.getTargetFrame().setSize(width, height);
panel.setTitle();
// Load editor option flags. This has to be done before the content
// items are loaded, to preserve the individual item settings
Attribute a;
boolean value = true;
if ((a = shared.getAttribute("editable")) != null && a.getValue().equals("no")) {
value = false;
}
panel.setAllEditable(value);
value = true;
if ((a = shared.getAttribute("positionable")) != null && a.getValue().equals("no")) {
value = false;
}
panel.setAllPositionable(value);
/*
value = false;
if ((a = element.getAttribute("showcoordinates"))!=null && a.getValue().equals("yes"))
value = true;
panel.setShowCoordinates(value);
*/
value = true;
if ((a = shared.getAttribute("showtooltips")) != null && a.getValue().equals("no")) {
value = false;
}
panel.setAllShowTooltip(value);
value = true;
if ((a = shared.getAttribute("controlling")) != null && a.getValue().equals("no")) {
value = false;
}
panel.setAllControlling(value);
value = false;
if ((a = shared.getAttribute("hide")) != null && a.getValue().equals("yes")) {
value = true;
}
panel.setShowHidden(value);
value = true;
if ((a = shared.getAttribute("panelmenu")) != null && a.getValue().equals("no")) {
value = false;
}
panel.setPanelMenuVisible(value);
String state = "both";
if ((a = shared.getAttribute("scrollable")) != null) {
state = a.getValue();
}
panel.setScroll(state);
// set color if needed
try {
int red = shared.getAttribute("redBackground").getIntValue();
int blue = shared.getAttribute("blueBackground").getIntValue();
int green = shared.getAttribute("greenBackground").getIntValue();
panel.setBackgroundColor(new Color(red, green, blue));
} catch (org.jdom2.DataConversionException e) {
log.warn("Could not parse color attributes!");
} catch (NullPointerException e) {
// considered normal if the attributes are not present
}
//set the (global) editor display widgets to their flag settings
panel.initView();
// load the contents with their individual option settings
List<Element> items = shared.getChildren();
for (int i = 0; i < items.size(); i++) {
// get the class, hence the adapter object to do loading
Element item = items.get(i);
String adapterName = item.getAttribute("class").getValue();
log.debug("load via " + adapterName);
try {
XmlAdapter adapter = (XmlAdapter) Class.forName(adapterName).newInstance();
// and do it
adapter.load(item, panel);
if (!panel.loadOK()) {
result = false;
}
} catch (Exception e) {
log.error("Exception while loading " + item.getName() + ":" + e);
result = false;
e.printStackTrace();
}
}
// dispose of url correction data
panel.disposeLoadData();
// display the results, with the editor in back
panel.pack();
panel.setAllEditable(panel.isEditable());
// we don't pack the target frame here, because size was specified
// TODO: Work out why, when calling this method, panel size is increased
// vertically (at least on MS Windows)
// always show the panel
panel.getTargetFrame().setVisible(true);
// register the resulting panel for later configuration
ConfigureManager cm = InstanceManager.getNullableDefault(jmri.ConfigureManager.class);
if (cm != null) {
cm.registerUser(panel);
}
// reset the size and position, in case the display caused it to change
panel.getTargetFrame().setLocation(x, y);
panel.getTargetFrame().setSize(width, height);
return result;
}
use of org.jdom2.Content in project JMRI by JMRI.
the class RosterEntry method updateFile.
/**
* Write the contents of this RosterEntry back to a file, preserving all
* existing decoder CV content.
* <p>
* This writes the file back in place, with the same decoder-specific
* content.
*/
public void updateFile() {
LocoFile df = new LocoFile();
String fullFilename = LocoFile.getFileLocation() + getFileName();
// read in the content
try {
mRootElement = df.rootFromName(fullFilename);
} catch (JDOMException | IOException e) {
log.error("Exception while loading loco XML file: " + getFileName() + " exception: " + e);
}
try {
File f = new File(fullFilename);
// do backup
df.makeBackupFile(LocoFile.getFileLocation() + getFileName());
// and finally write the file
df.writeFile(f, mRootElement, this.store());
} catch (Exception e) {
log.error("error during locomotive file output", e);
try {
JOptionPane.showMessageDialog(null, ResourceBundle.getBundle("jmri.jmrit.roster.JmritRosterBundle").getString("ErrorSavingText") + "\n" + e.getMessage(), ResourceBundle.getBundle("jmri.jmrit.roster.JmritRosterBundle").getString("ErrorSavingTitle"), JOptionPane.ERROR_MESSAGE);
} catch (HeadlessException he) {
// silently ignore inability to display dialog
}
}
}
use of org.jdom2.Content in project jspwiki by apache.
the class JSPWikiMarkupParser method handleHyperlinks.
/**
* Gobbles up all hyperlinks that are encased in square brackets.
*/
private Element handleHyperlinks(String linktext, int pos) {
ResourceBundle rb = Preferences.getBundle(m_context, InternationalizationManager.CORE_BUNDLE);
StringBuilder sb = new StringBuilder(linktext.length() + 80);
if (m_linkParsingOperations.isAccessRule(linktext)) {
return handleAccessRule(linktext);
}
if (m_linkParsingOperations.isMetadata(linktext)) {
return handleMetadata(linktext);
}
if (m_linkParsingOperations.isPluginLink(linktext)) {
try {
PluginContent pluginContent = PluginContent.parsePluginLine(m_context, linktext, pos);
//
if (pluginContent != null) {
addElement(pluginContent);
pluginContent.executeParse(m_context);
}
} catch (PluginException e) {
log.info(m_context.getRealPage().getWiki() + " : " + m_context.getRealPage().getName() + " - Failed to insert plugin: " + e.getMessage());
// log.info( "Root cause:",e.getRootThrowable() );
if (!m_wysiwygEditorMode) {
ResourceBundle rbPlugin = Preferences.getBundle(m_context, WikiPlugin.CORE_PLUGINS_RESOURCEBUNDLE);
return addElement(makeError(MessageFormat.format(rbPlugin.getString("plugin.error.insertionfailed"), m_context.getRealPage().getWiki(), m_context.getRealPage().getName(), e.getMessage())));
}
}
return m_currentElement;
}
try {
LinkParser.Link link = m_linkParser.parse(linktext);
linktext = link.getText();
String linkref = link.getReference();
//
if (m_linkParsingOperations.isVariableLink(linktext)) {
Content el = new VariableContent(linktext);
addElement(el);
} else if (m_linkParsingOperations.isExternalLink(linkref)) {
// It's an external link, out of this Wiki
callMutatorChain(m_externalLinkMutatorChain, linkref);
if (m_linkParsingOperations.isImageLink(linkref)) {
handleImageLink(linkref, linktext, link.hasReference());
} else {
makeLink(EXTERNAL, linkref, linktext, null, link.getAttributes());
addElement(outlinkImage());
}
} else if (link.isInterwikiLink()) {
// It's an interwiki link
// InterWiki links also get added to external link chain
// after the links have been resolved.
// FIXME: There is an interesting issue here: We probably should
// URLEncode the wikiPage, but we can't since some of the
// Wikis use slashes (/), which won't survive URLEncoding.
// Besides, we don't know which character set the other Wiki
// is using, so you'll have to write the entire name as it appears
// in the URL. Bugger.
String extWiki = link.getExternalWiki();
String wikiPage = link.getExternalWikiPage();
if (m_wysiwygEditorMode) {
makeLink(INTERWIKI, extWiki + ":" + wikiPage, linktext, null, link.getAttributes());
} else {
String urlReference = m_engine.getInterWikiURL(extWiki);
if (urlReference != null) {
urlReference = TextUtil.replaceString(urlReference, "%s", wikiPage);
urlReference = callMutatorChain(m_externalLinkMutatorChain, urlReference);
if (m_linkParsingOperations.isImageLink(urlReference)) {
handleImageLink(urlReference, linktext, link.hasReference());
} else {
makeLink(INTERWIKI, urlReference, linktext, null, link.getAttributes());
}
if (m_linkParsingOperations.isExternalLink(urlReference)) {
addElement(outlinkImage());
}
} else {
Object[] args = { extWiki };
addElement(makeError(MessageFormat.format(rb.getString("markupparser.error.nointerwikiref"), args)));
}
}
} else if (linkref.startsWith("#")) {
// It defines a local footnote
makeLink(LOCAL, linkref, linktext, null, link.getAttributes());
} else if (TextUtil.isNumber(linkref)) {
// It defines a reference to a local footnote
makeLink(LOCALREF, linkref, linktext, null, link.getAttributes());
} else {
int hashMark = -1;
//
// Internal wiki link, but is it an attachment link?
//
String attachment = m_engine.getAttachmentManager().getAttachmentInfoName(m_context, linkref);
if (attachment != null) {
callMutatorChain(m_attachmentLinkMutatorChain, attachment);
if (m_linkParsingOperations.isImageLink(linkref)) {
attachment = m_context.getURL(WikiContext.ATTACH, attachment);
sb.append(handleImageLink(attachment, linktext, link.hasReference()));
} else {
makeLink(ATTACHMENT, attachment, linktext, null, link.getAttributes());
}
} else if ((hashMark = linkref.indexOf('#')) != -1) {
// It's an internal Wiki link, but to a named section
String namedSection = linkref.substring(hashMark + 1);
linkref = linkref.substring(0, hashMark);
linkref = MarkupParser.cleanLink(linkref);
callMutatorChain(m_localLinkMutatorChain, linkref);
String matchedLink = m_linkParsingOperations.linkIfExists(linkref);
if (matchedLink != null) {
String sectref = "section-" + m_engine.encodeName(matchedLink + "-" + wikifyLink(namedSection));
sectref = sectref.replace('%', '_');
makeLink(READ, matchedLink, linktext, sectref, link.getAttributes());
} else {
makeLink(EDIT, linkref, linktext, null, link.getAttributes());
}
} else {
// It's an internal Wiki link
linkref = MarkupParser.cleanLink(linkref);
callMutatorChain(m_localLinkMutatorChain, linkref);
String matchedLink = m_linkParsingOperations.linkIfExists(linkref);
if (matchedLink != null) {
makeLink(READ, matchedLink, linktext, null, link.getAttributes());
} else {
makeLink(EDIT, linkref, linktext, null, link.getAttributes());
}
}
}
} catch (ParseException e) {
log.info("Parser failure: ", e);
Object[] args = { e.getMessage() };
addElement(makeError(MessageFormat.format(rb.getString("markupparser.error.parserfailure"), args)));
}
return m_currentElement;
}
use of org.jdom2.Content in project jspwiki by apache.
the class JSPWikiMarkupParser method paragraphify.
/**
* Checks out that the first paragraph is correctly installed.
*
* @param rootElement
*/
private void paragraphify(Element rootElement) {
//
// Add the paragraph tag to the first paragraph
//
List<Content> kids = rootElement.getContent();
if (rootElement.getChild("p") != null) {
ArrayList<Content> ls = new ArrayList<Content>();
int idxOfFirstContent = 0;
int count = 0;
for (Iterator<Content> i = kids.iterator(); i.hasNext(); count++) {
Content c = i.next();
if (c instanceof Element) {
String name = ((Element) c).getName();
if (isBlockLevel(name))
break;
}
if (!(c instanceof ProcessingInstruction)) {
ls.add(c);
if (idxOfFirstContent == 0)
idxOfFirstContent = count;
}
}
//
if (ls.size() > 0) {
Element newel = new Element("p");
for (Iterator<Content> i = ls.iterator(); i.hasNext(); ) {
Content c = i.next();
c.detach();
newel.addContent(c);
}
//
if (newel.getTextTrim().length() > 0 || !newel.getChildren().isEmpty())
rootElement.addContent(idxOfFirstContent, newel);
}
}
}
Aggregations