📄 xml.java
字号:
else if (m.getEncoding() == org.smslib.MessageEncodings.ENC8BIT)
{
encoding = "8";
}
else if (m.getEncoding() == org.smslib.MessageEncodings.ENCUCS2)
{
encoding = "U";
}
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#CallReceived(java.lang.String, java.lang.String)
*/
public void CallReceived(String gtwId, String callerId)
{
// This interface does not handle inbound calls.
}
/*
* (non-Javadoc)
*
* @see org.smslib.smsserver.AInterface#getMessagesToSend()
*/
public List getMessagesToSend() throws Exception
{
List messageList = new ArrayList();
File[] outFiles = outDirectory.listFiles(new FileFilter()
{
public boolean accept(File f)
{
/* Read only unprocessed files with an .xml suffix */
return (f.getAbsolutePath().endsWith(".xml") && !processedFiles.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);
processedFiles.put(msg, outFiles[i]);
}
catch (IllegalArgumentException e)
{
logWarn("Skipping outgoing file " + outFiles[i].getAbsolutePath() + ": File is not valid: " + e.getLocalizedMessage());
File brokenFile = new File(outBrokenDirectory, outFiles[i].getName());
if (!outFiles[i].renameTo(brokenFile)) {
System.out.println("Exists: " + outFiles[i].exists());
logError("Can't move " + outFiles[i] + " to " + brokenFile);
}
}
}
return messageList;
}
/*
* (non-Javadoc)
*
* @see org.smslib.smsserver.AInterface#markMessage(org.smslib.OutboundMessage)
*/
public void markMessage(org.smslib.OutboundMessage msg) throws Exception
{
if (msg == null) { return; }
File f = (File) processedFiles.get(msg);
File newF = null;
if (msg.getMessageStatus() == org.smslib.MessageStatuses.SENT)
{
newF = new File(outSentDirectory, f.getName());
}
else if (msg.getMessageStatus() == org.smslib.MessageStatuses.FAILED)
{
newF = new File(outFailedDirectory, f.getName());
}
if (f.renameTo(newF))
{
logInfo(f + " marked.");
}
else
{
logWarn("Can't move " + f + " to " + newF);
}
processedFiles.remove(msg);
}
/*
* (non-Javadoc)
*
* @see org.smslib.smsserver.AInterface#MessagesReceived(java.util.List)
*/
public void MessagesReceived(List msgList) throws Exception
{
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
for (int i = 0; i < msgList.size(); i++)
{
/* Check type of an message */
org.smslib.InboundMessage msg = (org.smslib.InboundMessage) msgList.get(i);
if ((msg.getType() == org.smslib.MessageTypes.INBOUND) || (msg.getType() == org.smslib.MessageTypes.STATUSREPORT))
{
Document xmldoc = db.newDocument();
/* Add inbound message to the xml document */
addMessageToDocument(xmldoc, msg);
/* Serialize xml document */
String fileName = fileSdf.format(new java.util.Date()) + ".xml";
logInfo("Writing inbound files to " + fileName);
writeDocument(xmldoc, new File(inDirectory, fileName));
}
}
}
/**
* 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 IOException, 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) throws SAXException
{
throw new IllegalArgumentException(arg0);
}
/* (non-Javadoc)
* @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
*/
public void fatalError(SAXParseException arg0) throws SAXException
{
throw new IllegalArgumentException(arg0);
}
/* (non-Javadoc)
* @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException)
*/
public void warning(SAXParseException arg0) throws SAXException
{
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 (!"smsvr_out.dtd".equals(outDoctype.getSystemId())) { throw new IllegalArgumentException("Wrong SystemId in DOCTYPE - Have to be smsvr_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);
outMsg.setId(e.getAttribute("id"));
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 optinal fields - priority */
String priority = e.getAttribute("priority");
if ("L".equalsIgnoreCase(priority))
{
outMsg.setPriority(org.smslib.MessagePriorities.LOW);
}
else if ("N".equalsIgnoreCase(priority))
{
outMsg.setPriority(org.smslib.MessagePriorities.NORMAL);
}
else if ("H".equalsIgnoreCase(priority))
{
outMsg.setPriority(org.smslib.MessagePriorities.HIGH);
}
/* Read optinal fields - encoding */
String encoding = e.getAttribute("encoding");
if ("7".equals(encoding))
{
outMsg.setEncoding(org.smslib.MessageEncodings.ENC7BIT);
}
else if ("8".equals(encoding))
{
outMsg.setEncoding(org.smslib.MessageEncodings.ENC8BIT);
}
else
{
outMsg.setEncoding(org.smslib.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;
}
/*
* (non-Javadoc)
*
* @see org.smslib.smsserver.AInterface#start()
*/
public void start() throws Exception
{
}
/*
* (non-Javadoc)
*
* @see org.smslib.smsserver.AInterface#stop()
*/
public void stop() throws Exception
{
}
/**
* 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 + -