📄 xml.java
字号:
/* Encoding */
String encoding = null;
switch (m.getEncoding())
{
case ENC7BIT:
encoding = "7";
break;
case ENC8BIT:
encoding = "8";
break;
case ENCUCS2:
encoding = "U";
break;
case ENCCUSTOM:
encoding = "C";
break;
}
if (encoding != null)
{
message.setAttributeNS(null, "encoding", encoding);
}
/* Compose message */
originatorNode = xmldoc.createTextNode(m.getOriginator());
originatorElement = xmldoc.createElementNS(null, "originator");
originatorElement.appendChild(originatorNode);
textNode = xmldoc.createTextNode(m.getText());
textElement = xmldoc.createElementNS(null, "text");
textElement.appendChild(textNode);
timeNode = xmldoc.createTextNode(getDateAsISO8601(m.getDate()));
timeElement = xmldoc.createElementNS(null, "receive_date");
timeElement.appendChild(timeNode);
message.appendChild(originatorElement);
message.appendChild(textElement);
message.appendChild(timeElement);
xmldoc.appendChild(message);
}
/*
* (non-Javadoc)
*
* @see org.smslib.smsserver.AInterface#getMessagesToSend()
*/
@Override
public Collection<OutboundMessage> getMessagesToSend() throws Exception
{
Collection<OutboundMessage> messageList = new ArrayList<OutboundMessage>();
File[] outFiles = this.outDirectory.listFiles(new FileFilter()
{
public boolean accept(File f)
{
/* Read only unprocessed files with an .xml suffix */
return (f.getAbsolutePath().endsWith(".xml") && !getMessageCache().containsValue(f));
}
});
for (int i = 0; i < outFiles.length; i++)
{
try
{
/* Process each document and add message to the list */
OutboundMessage msg = readDocument(outFiles[i]);
if (msg == null) { throw new IllegalArgumentException("Missing required fieldes!"); }
messageList.add(msg);
getMessageCache().put(msg.getMessageId(), outFiles[i]);
}
catch (IllegalArgumentException e)
{
getService().getLogger().logWarn("Skipping outgoing file " + outFiles[i].getAbsolutePath() + ": File is not valid: " + e.getLocalizedMessage(), null, null);
File brokenFile = new File(this.outBrokenDirectory, outFiles[i].getName());
if (!outFiles[i].renameTo(brokenFile)) getService().getLogger().logError("Can't move " + outFiles[i] + " to " + brokenFile, null, null);
}
}
return messageList;
}
/*
* (non-Javadoc)
*
* @see org.smslib.smsserver.AInterface#markMessage(org.smslib.OutboundMessage)
*/
@Override
public void markMessage(org.smslib.OutboundMessage msg) throws Exception
{
if (msg == null) { return; }
File f = getMessageCache().get(msg.getMessageId());
File newF = null;
switch (msg.getMessageStatus())
{
case SENT:
newF = new File(this.outSentDirectory, f.getName());
break;
case FAILED:
newF = new File(this.outFailedDirectory, f.getName());
break;
default:
break;
}
if (f.renameTo(newF))
{
getService().getLogger().logInfo(f + " marked.", null, null);
}
else
{
getService().getLogger().logWarn("Can't move " + f + " to " + newF, null, null);
}
getMessageCache().remove(msg.getMessageId());
}
/*
* (non-Javadoc)
*
* @see org.smslib.smsserver.AInterface#MessagesReceived(java.util.List)
*/
@Override
public void MessagesReceived(Collection<InboundMessage> msgList) throws Exception
{
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
for (InboundMessage msg : msgList)
{
/* Check type of an message */
if ((msg.getType() == MessageTypes.INBOUND) || (msg.getType() == MessageTypes.STATUSREPORT))
{
Document xmldoc = db.newDocument();
/* Add inbound message to the xml document */
addMessageToDocument(xmldoc, msg);
/* Serialize xml document */
File outputFile = null;
do
{
String fileName = fileSdf.format(new java.util.Date()) + ".xml";
outputFile = new File(this.inDirectory, fileName);
if (outputFile.exists())
{
Thread.sleep(100);
}
} while (outputFile.exists());
getService().getLogger().logInfo("Writing inbound files to " + outputFile.getName(), null, null);
writeDocument(xmldoc, outputFile);
}
}
}
/**
* Tries to read from the given filename the outbound message
*
* @param file
* The file to read from
* @return Outbound message read form the file
* @throws IllegalArgumentExcpetion
* Is thrown if there's something wrong with the content of the
* file
* @throws IOExcpetion
* Is throws if there's an I/O problem while reading the file
*/
private OutboundMessage readDocument(File file) throws IllegalArgumentException
{
Document xmldoc = null;
try
{
/* Check for valid XML file */
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
dbfac.setValidating(true);
DocumentBuilder db = dbfac.newDocumentBuilder();
db.setErrorHandler(new ErrorHandler()
{
/*
* (non-Javadoc)
*
* @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException)
*/
public void error(SAXParseException arg0)
{
throw new IllegalArgumentException(arg0);
}
/*
* (non-Javadoc)
*
* @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
*/
public void fatalError(SAXParseException arg0)
{
throw new IllegalArgumentException(arg0);
}
/*
* (non-Javadoc)
*
* @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException)
*/
public void warning(SAXParseException arg0)
{
throw new IllegalArgumentException(arg0);
}
});
xmldoc = db.parse(file);
DocumentType outDoctype = xmldoc.getDoctype();
if (!"message".equals(outDoctype.getName())) { throw new IllegalArgumentException("Wrong DOCTYPE - Have to be message!"); }
if (!"smssvr_out.dtd".equals(outDoctype.getSystemId())) { throw new IllegalArgumentException("Wrong SystemId in DOCTYPE - Have to be smssvr_out.dtd!"); }
}
catch (Exception e)
{
throw new IllegalArgumentException(e);
}
/* Search "message" root element */
NodeList rnl = xmldoc.getElementsByTagName("message");
if (rnl == null || rnl.getLength() != 1) { throw new IllegalArgumentException("Wrong root element or root element count!"); }
/* Process all child elements aka "message" */
return readNode(rnl.item(0));
}
/**
* Reads a given node and tries to parse it
*
* @param n
* The node to parse
* @return An outboundmessage if the node was parsable or null
*/
private OutboundMessage readNode(Node n)
{
if ("message".equals(n.getNodeName()))
{
String recipient = null;
String text = null;
String originator = null;
Element e = (Element) n;
NodeList cnl = n.getChildNodes();
/* Read required fields */
for (int i = 0; i < cnl.getLength(); i++)
{
Node en = cnl.item(i);
if ("recipient".equals(cnl.item(i).getNodeName()))
{
recipient = en.getTextContent();
}
else if ("text".equals(cnl.item(i).getNodeName()))
{
text = en.getTextContent();
}
else if ("originator".equals(cnl.item(i).getNodeName()))
{
originator = en.getTextContent();
}
}
/* Create outbound message */
OutboundMessage outMsg = new OutboundMessage(recipient, text);
/* Set required fields */
outMsg.setFrom(originator);
if (!"".equals(e.getAttribute("create_date")))
{
outMsg.setDate(getISO8601AsDate(e.getAttribute("create_date")));
}
if (!"".equals(e.getAttribute("gateway_id")))
{
outMsg.setGatewayId(e.getAttribute("gateway_id"));
}
/* Read optional fields - priority */
String priority = e.getAttribute("priority");
if ("L".equalsIgnoreCase(priority))
{
outMsg.setPriority(-1);
}
else if ("N".equalsIgnoreCase(priority))
{
outMsg.setPriority(0);
}
else if ("H".equalsIgnoreCase(priority))
{
outMsg.setPriority(+1);
}
/* Read optional fields - encoding */
String encoding = e.getAttribute("encoding");
if ("7".equals(encoding))
{
outMsg.setEncoding(MessageEncodings.ENC7BIT);
}
else if ("8".equals(encoding))
{
outMsg.setEncoding(MessageEncodings.ENC8BIT);
}
else
{
outMsg.setEncoding(MessageEncodings.ENCUCS2);
}
/* Read optinal fields - status_report */
if ("1".equals(e.getAttribute("status_report")))
{
outMsg.setStatusReport(true);
}
/* Read optinal fields - flash_sms */
if ("1".equals(e.getAttribute("flash_sms")))
{
outMsg.setFlashSms(true);
}
/* Read optinal fields - src_port */
if (!"".equals(e.getAttribute("src_port")))
{
outMsg.setSrcPort(Integer.parseInt(e.getAttribute("src_port")));
}
/* Read optinal fields - dst_port */
if (!"".equals(e.getAttribute("dst_port")))
{
outMsg.setDstPort(Integer.parseInt(e.getAttribute("dst_port")));
}
return outMsg;
}
return null;
}
/**
* Writes the given document to the geiven filename. <br />
* The DTD smssvr_in.dtd is added, too.
*
* @param doc
* The document to serialize
* @param fileName
* The file in which the document should be serialized
*/
private void writeDocument(Document doc, File fileName) throws IOException, TransformerFactoryConfigurationError, TransformerException
{
FileOutputStream fos = new FileOutputStream(fileName);
Transformer trans = TransformerFactory.newInstance().newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty(OutputKeys.STANDALONE, "yes");
trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "smssvr_in.dtd");
StreamResult result = new StreamResult(fos);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
fos.close();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -