Arbeitsstand Anfang Februar

git-svn-id: https://brutex.net/svn/xservices/trunk@114 e7e49efb-446e-492e-b9ec-fcafc1997a86
tag-20130205r
Brian Rosenberger 2013-02-05 14:43:54 +00:00
parent 71980e0cb2
commit f2a2f39d1a
8 changed files with 668 additions and 197 deletions

View File

@ -19,11 +19,11 @@ import java.io.File;
import javax.jws.WebMethod; import javax.jws.WebMethod;
import javax.jws.WebParam; import javax.jws.WebParam;
import javax.jws.WebService; import javax.jws.WebService;
import net.brutex.xservices.types.ArchiveResource;
import net.brutex.xservices.types.CompressionType; import net.brutex.xservices.types.CompressionType;
import net.brutex.xservices.types.FileResource;
import net.brutex.xservices.types.ResourceInterface;
import net.brutex.xservices.types.ReturnCode; import net.brutex.xservices.types.ReturnCode;
import net.brutex.xservices.types.ant.ArchiveResource;
import net.brutex.xservices.types.ant.FileResource;
import net.brutex.xservices.types.ant.ResourceInterface;
import net.brutex.xservices.util.BrutexNamespaces; import net.brutex.xservices.util.BrutexNamespaces;
import net.brutex.xservices.util.RunTask; import net.brutex.xservices.util.RunTask;
import net.brutex.xservices.util.UnRarTask; import net.brutex.xservices.util.UnRarTask;

View File

@ -18,48 +18,44 @@ package net.brutex.xservices.ws.impl;
import java.math.BigInteger; import java.math.BigInteger;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimeZone; import java.util.TimeZone;
import javax.jws.WebService; import javax.jws.WebService;
import net.brutex.xservices.types.DateFormatType; import net.brutex.xservices.types.DateFormatType;
import net.brutex.xservices.types.DateInfoExtendedType;
import net.brutex.xservices.types.DateInfoType;
import net.brutex.xservices.types.DateTimeUnits; import net.brutex.xservices.types.DateTimeUnits;
import net.brutex.xservices.types.TimeZoneType;
import net.brutex.xservices.util.BrutexNamespaces; import net.brutex.xservices.util.BrutexNamespaces;
import net.brutex.xservices.ws.DateService; import net.brutex.xservices.ws.DateService;
import net.brutex.xservices.ws.XServicesFault; import net.brutex.xservices.ws.XServicesFault;
/** /**
* @author Brian Rosenberger * @author Brian Rosenberger
* *
*/ */
@WebService( @WebService(targetNamespace = BrutexNamespaces.WS_XSERVICES, endpointInterface = "net.brutex.xservices.ws.DateService", serviceName = DateService.SERVICE_NAME)
targetNamespace = BrutexNamespaces.WS_XSERVICES,
endpointInterface = "net.brutex.xservices.ws.DateService",
serviceName = DateService.SERVICE_NAME
)
public class DateServiceImpl implements DateService { public class DateServiceImpl implements DateService {
private static String ERR_INVALIDFORMAT = "Invalid format pattern."; private static String ERR_INVALIDFORMAT = "Invalid format pattern.";
private static String ERR_INVALIDTIMEZONE = "Invalid timezone."; private static String ERR_INVALIDTIMEZONE = "Invalid timezone.";
public GregorianCalendar getDate(String timezone) throws XServicesFault { public DateInfoType getDate() throws XServicesFault {
if (! isValidTimezone(timezone) ) { GregorianCalendar c = new GregorianCalendar();
String valid_ids = ""; DateInfoType dateinfo = new DateInfoType(c, TimeZone.getDefault());
String[] tid = TimeZone.getAvailableIDs(); return dateinfo;
for (String s : tid) {
valid_ids += s + "\n";
}
throw new XServicesFault("Please supply a valid timezone id or none. Valid timezones are:\n" + valid_ids,
new Exception( ));
}
if (timezone == null || timezone.length()<1 ) timezone = "GMT0";
GregorianCalendar c = new GregorianCalendar(TimeZone.getTimeZone(timezone));
return c;
} }
public DateInfoExtendedType getDateExtended() throws XServicesFault {
GregorianCalendar c = new GregorianCalendar();
DateInfoExtendedType dateinfo = new DateInfoExtendedType(c,
TimeZone.getDefault());
return dateinfo;
}
public BigInteger getTimestamp() { public BigInteger getTimestamp() {
Date d = new Date(); Date d = new Date();
@ -73,44 +69,49 @@ public class DateServiceImpl implements DateService {
return new BigInteger(Long.toString(l)); return new BigInteger(Long.toString(l));
} }
public String getInTimezone(Date date, String timezone)
public GregorianCalendar getInTimezone(GregorianCalendar cal, throws XServicesFault {
String timezone) throws XServicesFault { if (!isValidTimezone(timezone))
if(! isValidTimezone(timezone)) throw new XServicesFault(ERR_INVALIDTIMEZONE); throw new XServicesFault(ERR_INVALIDTIMEZONE);
GregorianCalendar c = new GregorianCalendar(TimeZone.getTimeZone(timezone)); TimeZone targetzone = TimeZone.getTimeZone(timezone);
c.setTimeInMillis(cal.getTimeInMillis()); String targetstring = DateFormatType.ISO8601.format(date, null, targetzone);
return c; return targetstring;
} }
public String formatDate(Date cal, DateFormatType format)
public String formatDate(GregorianCalendar cal, DateFormatType format) throws XServicesFault { throws XServicesFault {
return formatDateAdvanced(cal, format.format()); return format.format(cal, null, null);
} }
public String formatDateAdvanced(Date cal, String format)
public String formatDateAdvanced(GregorianCalendar cal, String format)
throws XServicesFault { throws XServicesFault {
String result = null; String result = null;
try {
SimpleDateFormat f = new SimpleDateFormat(format); SimpleDateFormat f = new SimpleDateFormat(format);
result = f.format(cal.getTime()); result = f.format(cal);
} catch (IllegalArgumentException e) {
throw new XServicesFault(ERR_INVALIDFORMAT + e.getMessage());
}
return result; return result;
} }
public Date parseDate(String s, DateFormatType format, String timezone)
public GregorianCalendar parseDate(String s, DateFormatType format, String timezone) throws XServicesFault { throws XServicesFault {
return parseDateAdvanced(s, format.format(), timezone); if (timezone == null | timezone.equals(""))
timezone = TimeZone.getDefault().getID();
if (!isValidTimezone(timezone))
throw new XServicesFault(ERR_INVALIDTIMEZONE);
try {
return format.parse(s, null, TimeZone.getTimeZone(timezone));
} catch (ParseException e) {
throw new XServicesFault(e);
}
} }
public GregorianCalendar parseDateAdvanced(String s, String format,
public GregorianCalendar parseDateAdvanced(String s, String format, String timezone) throws XServicesFault { String timezone) throws XServicesFault {
SimpleDateFormat f = null; SimpleDateFormat f = null;
Date date = null; Date date = null;
if(timezone==null | timezone.equals("")) timezone = TimeZone.getDefault().getID(); if (timezone == null | timezone.equals(""))
if(! isValidTimezone(timezone)) throw new XServicesFault(ERR_INVALIDTIMEZONE); timezone = TimeZone.getDefault().getID();
if (!isValidTimezone(timezone))
throw new XServicesFault(ERR_INVALIDTIMEZONE);
try { try {
f = new SimpleDateFormat(format); f = new SimpleDateFormat(format);
@ -126,17 +127,15 @@ public class DateServiceImpl implements DateService {
return cal; return cal;
} }
public BigInteger dateTimeDiff(Date fromCal, Date toCal)
public BigInteger dateTimeDiff(GregorianCalendar fromCal, throws XServicesFault {
GregorianCalendar toCal) throws XServicesFault { long diff = toCal.getTime() - fromCal.getTime();
long diff = toCal.getTimeInMillis() - fromCal.getTimeInMillis();
BigInteger d = new BigInteger(String.valueOf(diff), 10); BigInteger d = new BigInteger(String.valueOf(diff), 10);
return d; return d;
} }
public BigInteger dateTimeDiff2(Date fromCal, Date toCal, DateTimeUnits unit)
public BigInteger dateTimeDiff2(GregorianCalendar fromCal, throws XServicesFault {
GregorianCalendar toCal, DateTimeUnits unit) throws XServicesFault {
BigInteger d = dateTimeDiff(fromCal, toCal); BigInteger d = dateTimeDiff(fromCal, toCal);
switch (unit) { switch (unit) {
case SECONDS: case SECONDS:
@ -150,13 +149,16 @@ public class DateServiceImpl implements DateService {
break; break;
case DAYS: case DAYS:
d = d.divide(new BigInteger("86400000")); d = d.divide(new BigInteger("86400000"));
break;
case YEARS:
d = d.divide(new BigInteger("31536000000"));
break;
} }
return d; return d;
} }
public GregorianCalendar dateAdd(GregorianCalendar cal, BigInteger value,
public GregorianCalendar dateAdd(GregorianCalendar cal, BigInteger value, DateTimeUnits unit) DateTimeUnits unit) throws XServicesFault {
throws XServicesFault {
switch (unit) { switch (unit) {
case SECONDS: case SECONDS:
cal.add(GregorianCalendar.SECOND, value.intValue()); cal.add(GregorianCalendar.SECOND, value.intValue());
@ -170,6 +172,9 @@ public class DateServiceImpl implements DateService {
case DAYS: case DAYS:
cal.add(GregorianCalendar.DAY_OF_MONTH, value.intValue()); cal.add(GregorianCalendar.DAY_OF_MONTH, value.intValue());
break; break;
case YEARS:
cal.add(GregorianCalendar.YEAR, value.intValue());
break;
default: default:
cal.add(GregorianCalendar.MILLISECOND, value.intValue()); cal.add(GregorianCalendar.MILLISECOND, value.intValue());
} }
@ -187,4 +192,11 @@ public class DateServiceImpl implements DateService {
return yes; return yes;
} }
public List<TimeZoneType> getTimezones() {
List<TimeZoneType> output = new ArrayList<TimeZoneType>();
for (String s : TimeZone.getAvailableIDs()) {
output.add(new TimeZoneType(TimeZone.getTimeZone(s)));
}
return output;
}
} }

View File

@ -27,12 +27,12 @@ import javax.jws.WebMethod;
import javax.jws.WebParam; import javax.jws.WebParam;
import javax.jws.WebService; import javax.jws.WebService;
import net.brutex.xservices.types.ArchiveResource;
import net.brutex.xservices.types.AttachmentType;
import net.brutex.xservices.types.FileResource;
import net.brutex.xservices.types.FileSetResource;
import net.brutex.xservices.types.ReplacePattern; import net.brutex.xservices.types.ReplacePattern;
import net.brutex.xservices.types.ReturnCode; import net.brutex.xservices.types.ReturnCode;
import net.brutex.xservices.types.ant.ArchiveResource;
import net.brutex.xservices.types.ant.AttachmentType;
import net.brutex.xservices.types.ant.FileResource;
import net.brutex.xservices.types.ant.FileSetResource;
import net.brutex.xservices.util.BrutexNamespaces; import net.brutex.xservices.util.BrutexNamespaces;
import net.brutex.xservices.util.RunTask; import net.brutex.xservices.util.RunTask;
import net.brutex.xservices.ws.FileService; import net.brutex.xservices.ws.FileService;
@ -284,7 +284,7 @@ public class FileServiceImpl implements FileService {
*/ */
public ReturnCode echo2file(String message, String file, String encoding, public ReturnCode echo2file(String message, String file, String encoding,
boolean append) throws XServicesFault { boolean append, boolean create) throws XServicesFault {
Echo echo = new Echo(); Echo echo = new Echo();
echo.setTaskName("toFile"); echo.setTaskName("toFile");
@ -292,9 +292,10 @@ public class FileServiceImpl implements FileService {
echo.addText(message); echo.addText(message);
echo.setEncoding(encoding); echo.setEncoding(encoding);
File f = new File(file); File f = new File(file);
try {
if (!f.canWrite())
try {
if(!f.exists() && create) f.createNewFile();
if (!f.canWrite())
throw new XServicesFault("Cannot write to file: " throw new XServicesFault("Cannot write to file: "
+ f.getCanonicalPath()); + f.getCanonicalPath());
@ -305,7 +306,7 @@ public class FileServiceImpl implements FileService {
} catch (BuildException e) { } catch (BuildException e) {
throw new XServicesFault("Error in echo2file.", e); throw new XServicesFault("Error in echo2file.", e);
} catch (IOException e) { } catch (IOException e) {
throw new XServicesFault("Cannot write to file.", e); throw new XServicesFault("Cannot write to file." + e.getMessage(), e);
} }
} }

View File

@ -0,0 +1,44 @@
/*
* Copyright 2013 Brian Rosenberger (Brutex Network)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.brutex.xservices.ws.impl;
import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Messages
{
private static final String BUNDLE_NAME = "net.brutex.xservices.ws.impl.messages";
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("net.brutex.xservices.ws.impl.messages");
public static String getString(String key)
{
try
{
return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) {
}
return '!' + key + '!';
}
public static String getString(String key, Object[] params)
{
try {
return MessageFormat.format(RESOURCE_BUNDLE.getString(key), params); } catch (MissingResourceException e) {
}
return '!' + key + '!';
}
}

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2010 Brian Rosenberger (Brutex Network) * Copyright 2013 Brian Rosenberger (Brutex Network)
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -18,12 +18,15 @@ package net.brutex.xservices.ws.impl;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.Properties; import java.util.Properties;
import java.util.UUID;
import javax.jws.WebService; import javax.jws.WebService;
import net.brutex.xservices.types.FileSetResource;
import net.brutex.xservices.types.HostConnection; import net.brutex.xservices.types.HostConnection;
import net.brutex.xservices.types.HostinfoType;
import net.brutex.xservices.types.MailMimeType; import net.brutex.xservices.types.MailMimeType;
import net.brutex.xservices.types.ReturnCode; import net.brutex.xservices.types.ReturnCode;
import net.brutex.xservices.types.RuntimeInfoType;
import net.brutex.xservices.types.ant.FileSetResource;
import net.brutex.xservices.util.BrutexNamespaces; import net.brutex.xservices.util.BrutexNamespaces;
import net.brutex.xservices.util.RunTask; import net.brutex.xservices.util.RunTask;
import net.brutex.xservices.ws.MiscService; import net.brutex.xservices.ws.MiscService;
@ -35,66 +38,64 @@ import org.apache.tools.ant.taskdefs.Sleep;
import org.apache.tools.ant.taskdefs.email.EmailTask; import org.apache.tools.ant.taskdefs.email.EmailTask;
/** /**
* Implements the web service
* *
* @author Brian Rosenberger, bru@brutex.de * @author Brian Rosenberger, bru@brutex.de
*/ */
@WSDLDocumentationCollection({ @WebService(targetNamespace="http://ws.xservices.brutex.net", endpointInterface="net.brutex.xservices.ws.MiscService", serviceName="MiscService")
@WSDLDocumentation("My portType documentation"), public class MiscServiceImpl
@WSDLDocumentation(value = "My top level documentation", placement = WSDLDocumentation.Placement.TOP), implements MiscService
@WSDLDocumentation(value = "My binding doc", placement = WSDLDocumentation.Placement.BINDING) }) {
@WebService( public HostinfoType getHostinfo(String hostname)
targetNamespace = BrutexNamespaces.WS_XSERVICES, {
endpointInterface = "net.brutex.xservices.ws.MiscService", HostInfo info = new HostInfo();
serviceName = "MiscService" info.setTaskName("HostInfo");
) RunTask runner = new RunTask(info);
public class MiscServiceImpl implements MiscService { info.setHost(hostname);
@WSDLDocumentation(value = "Get information about a host.") ReturnCode ret = runner.postTask();
public ReturnCode getHostinfo(String hostname) { HostinfoType infotype = new HostinfoType(
return antGetHostinfo(hostname, null); ret.getProperty("NAME"),
ret.getProperty("DOMAIN"),
ret.getProperty("ADDR4"),
ret.getProperty("ADDR6"));
return infotype;
} }
@WSDLDocumentation(value = "Get XService information.")
public ReturnCode getInfo() { public ReturnCode getInfo() {
ReturnCode r = new ReturnCode(); ReturnCode r = new ReturnCode();
r.returnCode = 0; r.returnCode = 0;
// Get all system properties
Properties props = System.getProperties(); Properties props = System.getProperties();
// Enumerate all system properties Enumeration e = props.propertyNames();
Enumeration<String> e = (Enumeration<String>) props.propertyNames(); while (e.hasMoreElements())
for (; e.hasMoreElements(); ) { {
// Get property name
String propName = (String)e.nextElement(); String propName = (String)e.nextElement();
// Get property value
String propValue = (String)props.get(propName); String propValue = (String)props.get(propName);
r.stdOut = r.stdOut + propName + ": " + propValue + "\n"; r.stdOut = (r.stdOut + propName + ": " + propValue + "\n");
} }
return r; return r;
} }
public ReturnCode sendMailSimple(HostConnection mailhost, String from, String tolist, String subject, String message)
public ReturnCode sendMailSimple(HostConnection mailhost, String from, {
String tolist, String subject, String message) {
return sendMail(from, from, tolist, "", "", subject, message, return sendMail(from, from, tolist, "", "", subject, message,
"text/plain", null, mailhost.hostname, mailhost.port, "text/plain", null, mailhost.hostname, mailhost.port,
mailhost.user, mailhost.password, "utf-8", false, false); mailhost.user, mailhost.password, "utf-8", false, false);
} }
public ReturnCode sendMailSimpleWithAttachment(HostConnection mailhost, public ReturnCode sendMailSimpleWithAttachment(HostConnection mailhost, String from, String tolist, String subject, String message, FileSetResource res)
String from, String tolist, String subject, String message, {
FileSetResource res) {
return sendMail(from, from, tolist, "", "", subject, message, return sendMail(from, from, tolist, "", "", subject, message,
"text/plain", res, mailhost.hostname, mailhost.port, "text/plain", res, mailhost.hostname, mailhost.port,
mailhost.user, mailhost.password, "utf-8", false, false); mailhost.user, mailhost.password, "utf-8", false, false);
} }
public ReturnCode sendMail(HostConnection mailhost, String from, public ReturnCode sendMail(HostConnection mailhost, String from, String tolist, String cclist, String bcclist, String subject, MailMimeType mimetype, String charset, String message, FileSetResource res, boolean ssl, boolean tls)
String tolist, String cclist, String bcclist, String subject, {
MailMimeType mimetype, String charset, String message,
FileSetResource res, boolean ssl, boolean tls) {
return sendMail(from, from, tolist, cclist, bcclist, subject, message, return sendMail(from, from, tolist, cclist, bcclist, subject, message,
mimetype.value(), res, mailhost.hostname, mailhost.port, mimetype.value(), res, mailhost.hostname, mailhost.port,
mailhost.user, mailhost.password, charset, tls, ssl); mailhost.user, mailhost.password, charset, tls, ssl);
@ -104,20 +105,12 @@ public class MiscServiceImpl implements MiscService {
return sleep(0, minutes, seconds, 0); return sleep(0, minutes, seconds, 0);
} }
private ReturnCode antGetHostinfo(String hostname, String prefix) { public String generateUUID() {
HostInfo info = new HostInfo(); return UUID.randomUUID().toString();
info.setTaskName("HostInfo");
RunTask runner = new RunTask(info);
info.setHost(hostname);
// info.setPrefix(prefix);
return runner.postTask();
} }
private ReturnCode sendMail(String from, String replyto, String tolist, private ReturnCode sendMail(String from, String replyto, String tolist, String cclist, String bcclist, String subject, String message, String messagemimetype, FileSetResource attachments, String mailhost, int mailport, String user, String password, String charset, boolean tls, boolean ssl)
String cclist, String bcclist, String subject, String message, {
String messagemimetype, FileSetResource attachments,
String mailhost, int mailport, String user, String password,
String charset, boolean tls, boolean ssl) {
EmailTask mail = new EmailTask(); EmailTask mail = new EmailTask();
mail.setTaskName("Mail"); mail.setTaskName("Mail");
RunTask runner = new RunTask(mail); RunTask runner = new RunTask(mail);
@ -142,8 +135,8 @@ public class MiscServiceImpl implements MiscService {
return runner.postTask(); return runner.postTask();
} }
private ReturnCode sleep(int hours, int minutes, int seconds, private ReturnCode sleep(int hours, int minutes, int seconds, int milliseconds)
int milliseconds) { {
Sleep sleep = new Sleep(); Sleep sleep = new Sleep();
sleep.setTaskName("Sleep"); sleep.setTaskName("Sleep");
RunTask runner = new RunTask(sleep); RunTask runner = new RunTask(sleep);
@ -153,4 +146,8 @@ public class MiscServiceImpl implements MiscService {
sleep.setMilliseconds(milliseconds); sleep.setMilliseconds(milliseconds);
return runner.postTask(); return runner.postTask();
} }
public RuntimeInfoType getMemory() {
return new RuntimeInfoType();
}
} }

View File

@ -34,13 +34,11 @@ public class StorageServiceImpl implements StorageService {
public String storeText(String text) throws XServicesFault { public String storeText(String text) throws XServicesFault {
// TODO Auto-generated method stub // TODO Auto-generated method stub
System.err.println("storeText is not yet implemented");
return null; return null;
} }
public String storeBinary(AttachmentType binary) throws XServicesFault { public String storeBinary(AttachmentType binary) throws XServicesFault {
// TODO Auto-generated method stub // TODO Auto-generated method stub
System.err.println("storeBinary is not yet implemented");
return null; return null;
} }
@ -52,7 +50,7 @@ public class StorageServiceImpl implements StorageService {
public void deliverCollection(CollectionType collection, public void deliverCollection(CollectionType collection,
TargetNodeType targetnode, boolean isFiring) throws XServicesFault { TargetNodeType targetnode, boolean isFiring) throws XServicesFault {
// TODO Auto-generated method stub // TODO Auto-generated method stub
System.err.println("deliverCollection is not yet implemented");
} }
} }

View File

@ -0,0 +1,408 @@
/*
* Copyright 2013 Brian Rosenberger (Brutex Network)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.brutex.xservices.ws.impl;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import javax.jws.WebService;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import net.brutex.xservices.types.NamespaceListType;
import net.brutex.xservices.types.NamespaceType;
import net.brutex.xservices.types.ant.FileResource;
import net.brutex.xservices.ws.XServicesFault;
import net.brutex.xservices.ws.XmlService;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMCloneOptions;
import org.apache.axiom.om.OMContainer;
import org.apache.axiom.om.OMDocument;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNode;
import org.apache.axiom.om.OMText;
import org.apache.axiom.om.OMXMLBuilderFactory;
import org.apache.axiom.om.xpath.AXIOMXPath;
import org.apache.log4j.Logger;
import org.jaxen.JaxenException;
import org.jaxen.SimpleNamespaceContext;
/**
* @author Brian Rosenberger, bru(at)brutex.de
*
*/
@WebService(targetNamespace = "http://ws.xservices.brutex.net", endpointInterface = "net.brutex.xservices.ws.XmlService", serviceName = "XmlService")
public class XmlServiceImpl implements XmlService {
final Logger logger = Logger.getLogger(XmlServiceImpl.class);
public String insertNodesFromFile(FileResource res, NamespaceListType nsList, String xpath, String xmlFragment) throws XServicesFault {
try {
AXIOMXPath axp = new AXIOMXPath(xpath);
InputStream is = res.getAntResource(null).getInputStream();
OMDocument sourcedoc = OMXMLBuilderFactory.createOMBuilder(is)
.getDocument();
OMDocument fragdoc = null;
if ((xmlFragment != null) && (new String(xmlFragment).length() > 0)) {
fragdoc = OMXMLBuilderFactory.createOMBuilder(
new StringReader("<XS>" + xmlFragment + "</XS>"))
.getDocument();
} else {
throw new XServicesFault("No xmldata to insert.");
}
// Initialize XPath context
SimpleNamespaceContext context = new SimpleNamespaceContext();
for (NamespaceType ns : nsList.getNamespaces()) {
context.addNamespace(ns.getPrefix(), ns.getUri().toString());
this.logger.debug(Messages.getString("XmlService.0")
+ ns.getPrefix() + "=\"" + ns.getUri().toString()
+ "\"'");
}
axp.setNamespaceContext(context);
axp.addNamespaces(fragdoc.getOMDocumentElement());
OMDocument document = insertNodes(sourcedoc, axp, fragdoc);
StringWriter sw = new StringWriter();
XMLOutputFactory xof = XMLOutputFactory.newInstance();
XMLStreamWriter writer = xof.createXMLStreamWriter(sw);
document.serialize(writer);
this.logger.trace(sw.getBuffer().toString());
return sw.getBuffer().toString();
} catch (JaxenException e) {
e.printStackTrace();
throw new XServicesFault(e);
} catch (IOException e) {
e.printStackTrace();
throw new XServicesFault(e);
} catch (XMLStreamException e) {
e.printStackTrace();
throw new XServicesFault(e);
}
}
public String replaceNodesFromFile(FileResource res, NamespaceListType nsList, String xpath, String replace) throws XServicesFault {
try {
AXIOMXPath axp = new AXIOMXPath(xpath);
InputStream is = res.getAntResource(null).getInputStream();
XMLStreamReader reader = OMXMLBuilderFactory.createOMBuilder(is)
.getDocument().getXMLStreamReader(false);
StringWriter sw = new StringWriter();
OMAbstractFactory.getOMFactory();
while (reader.hasNext()) {
if (reader.getEventType() == 1) {
OMElement element = OMXMLBuilderFactory
.createStAXOMBuilder(reader).getDocumentElement();
element.build();
SimpleNamespaceContext context = new SimpleNamespaceContext();
for (NamespaceType ns : nsList.getNamespaces()) {
context.addNamespace(ns.getPrefix(), ns.getUri()
.toString());
this.logger.debug(Messages.getString(
"XmlService.adding_namespace",
new Object[] { ns.getPrefix(),
ns.getUri().toString() }));
}
axp.setNamespaceContext(context);
axp.addNamespaces(element);
OMDocument xfrag = OMXMLBuilderFactory.createOMBuilder(
new StringReader("<XS>" + replace + "</XS>"))
.getDocument();
xfrag.build();
List list = axp.selectNodes(element);
for (Iterator localIterator2 = list.iterator(); localIterator2
.hasNext();) {
Object o = localIterator2.next();
if (!(o instanceof OMNode))
throw new XServicesFault(
"You must match a node to be replaced, but you matched something differen (attribute, etc.");
OMNode node = (OMNode) o;
Iterator<?> children = xfrag.getOMDocumentElement()
.getChildren();
while (children.hasNext()) {
OMNode container = (OMNode) children.next();
node.insertSiblingAfter((OMNode) container
.clone(new OMCloneOptions()));
}
node.detach();
// node.insertSiblingAfter(AXIOMUtil.stringToOM(replace));
}
XMLOutputFactory xof = XMLOutputFactory.newInstance();
XMLStreamWriter writer = xof.createXMLStreamWriter(sw);
element.serialize(writer);
sw.flush();
} else {
reader.next();
}
}
this.logger.trace(sw.getBuffer().toString());
return sw.getBuffer().toString();
} catch (JaxenException e) {
e.printStackTrace();
throw new XServicesFault(e);
} catch (IOException e) {
e.printStackTrace();
throw new XServicesFault(e);
} catch (XMLStreamException e) {
e.printStackTrace();
throw new XServicesFault(e);
}
}
public String replaceNodes(String source, NamespaceListType nsList, String xpath, String xmlFragment) throws XServicesFault {
try {
AXIOMXPath axp = new AXIOMXPath(xpath);
InputStream is = new ByteArrayInputStream(source.getBytes());
OMDocument sourcedoc = OMXMLBuilderFactory.createOMBuilder(is)
.getDocument();
OMDocument fragdoc = null;
if ((xmlFragment != null) && (new String(xmlFragment).length() > 0)) {
fragdoc = OMXMLBuilderFactory.createOMBuilder(
new StringReader("<XS>" + xmlFragment + "</XS>"))
.getDocument();
} else {
throw new XServicesFault("No xmldata to insert.");
}
// Initialize XPath context
SimpleNamespaceContext context = new SimpleNamespaceContext();
for (NamespaceType ns : nsList.getNamespaces()) {
context.addNamespace(ns.getPrefix(), ns.getUri().toString());
this.logger.debug(Messages.getString("XmlService.0")
+ ns.getPrefix() + "=\"" + ns.getUri().toString()
+ "\"'");
}
axp.setNamespaceContext(context);
axp.addNamespaces(fragdoc.getOMDocumentElement());
OMDocument document = replaceNodes(sourcedoc, axp, fragdoc);
StringWriter sw = new StringWriter();
XMLOutputFactory xof = XMLOutputFactory.newInstance();
XMLStreamWriter writer = xof.createXMLStreamWriter(sw);
document.serialize(writer);
this.logger.trace(sw.getBuffer().toString());
return sw.getBuffer().toString();
} catch (JaxenException e) {
e.printStackTrace();
throw new XServicesFault(e);
} catch (XMLStreamException e) {
e.printStackTrace();
throw new XServicesFault(e);
}
}
public String insertNodes(String source, NamespaceListType nsList, String xpath, String xmlFragment) throws XServicesFault {
try {
AXIOMXPath axp = new AXIOMXPath(xpath);
InputStream is = new ByteArrayInputStream(source.getBytes());
OMDocument sourcedoc = OMXMLBuilderFactory.createOMBuilder(is)
.getDocument();
OMDocument fragdoc = null;
if ((xmlFragment != null) && (new String(xmlFragment).length() > 0)) {
fragdoc = OMXMLBuilderFactory.createOMBuilder(
new StringReader("<XS>" + xmlFragment + "</XS>"))
.getDocument();
} else {
throw new XServicesFault("No xmldata to insert.");
}
// Initialize XPath context
SimpleNamespaceContext context = new SimpleNamespaceContext();
for (NamespaceType ns : nsList.getNamespaces()) {
context.addNamespace(ns.getPrefix(), ns.getUri().toString());
this.logger.debug(Messages.getString("XmlService.0")
+ ns.getPrefix() + "=\"" + ns.getUri().toString()
+ "\"'");
}
axp.setNamespaceContext(context);
axp.addNamespaces(fragdoc.getOMDocumentElement());
OMDocument document = insertNodes(sourcedoc, axp, fragdoc);
StringWriter sw = new StringWriter();
XMLOutputFactory xof = XMLOutputFactory.newInstance();
XMLStreamWriter writer = xof.createXMLStreamWriter(sw);
document.serialize(writer);
this.logger.trace(sw.getBuffer().toString());
return sw.getBuffer().toString();
} catch (JaxenException e) {
e.printStackTrace();
throw new XServicesFault(e);
} catch (XMLStreamException e) {
e.printStackTrace();
throw new XServicesFault(e);
}
}
public String wrapInCDATA(String data) throws XServicesFault {
String result ="";
String[] tokens = data.split("\\]\\]>", -1);
for(int i=0; i<tokens.length; i++) {
result += tokens[i];
if (i+1 < tokens.length ) result += "]]]]><![CDATA[>";
}
result = "<![CDATA[" + result + "]]>";
return result;
}
private OMDocument insertNodes(OMDocument xmldocument, AXIOMXPath axp,OMDocument xmlfragment) throws XServicesFault {
List<?> olist = null;
try {
olist = axp.selectNodes(xmldocument.getOMDocumentElement());
this.logger.debug("XPath '" + axp.toString() + "' has "
+ olist.size() + " matches.");
this.logger.trace("XPath root expression is: '" + axp.debug()
+ "'.");
} catch (JaxenException e) {
throw new XServicesFault(e.getMessage(), e);
}
if (olist.size() == 0)
throw new XServicesFault(Messages.getString("XmlService.no_match",
new Object[] { axp.toString() }));
// Prepare children to insert
xmlfragment.build();
// Determine what has been matched
OMContainer match = null;
for (Object o : olist) {
Iterator<?> children = xmlfragment.getOMDocumentElement()
.getChildren();
if ((o instanceof OMNode)) {
OMNode node = (OMNode) o;
switch (node.getType()) {
case OMNode.ELEMENT_NODE:
if ((o instanceof OMElement))
match = (OMElement) o;
if ((o instanceof OMDocument))
match = ((OMDocument) o).getOMDocumentElement();
this.logger.debug(Messages.getString("XmlService.8"));
break;
case OMNode.TEXT_NODE:
match = ((OMText) o).getParent();
this.logger.debug(Messages.getString("XmlService.9"));
break;
case OMNode.COMMENT_NODE:
// match = node.getParent();
match = (OMContainer) node;
this.logger.debug(Messages.getString("XmlService.10"));
break;
default:
this.logger.error("XPath matched "
+ o.getClass().getCanonicalName() + " Node Type:"
+ node.getType());
this.logger.error(Messages.getString("XmlService.11"));
throw new XServicesFault(
Messages.getString("XmlService.12"));
}
} else {
this.logger.error("XPath matched "
+ o.getClass().getCanonicalName());
this.logger.error(Messages.getString("XmlService.11"));
throw new XServicesFault(Messages.getString("XmlService.12"));
}
while (children.hasNext()) {
OMNode container = (OMNode) children.next();
match.addChild((OMNode) container.clone(new OMCloneOptions()));
}
}
xmldocument.build();
return xmldocument;
}
private OMDocument replaceNodes(OMDocument xmldocument, AXIOMXPath axp, OMDocument xmlfragment) throws XServicesFault {
List<?> olist = null;
try {
olist = axp.selectNodes(xmldocument.getOMDocumentElement());
this.logger.debug("XPath '" + axp.toString() + "' has "
+ olist.size() + " matches.");
this.logger.trace("XPath root expression is: '" + axp.debug()
+ "'.");
} catch (JaxenException e) {
throw new XServicesFault(e.getMessage(), e);
}
if (olist.size() == 0)
throw new XServicesFault(Messages.getString("XmlService.no_match",
new Object[] { axp.toString() }));
// Prepare children to insert
xmlfragment.build();
// Determine what has been matched
OMNode match = null;
for (Object o : olist) {
Iterator<?> children = xmlfragment.getOMDocumentElement()
.getChildren();
if ((o instanceof OMNode)) {
OMNode node = (OMNode) o;
switch (node.getType()) {
case OMNode.ELEMENT_NODE:
if ((o instanceof OMElement))
match = (OMElement) o;
if ((o instanceof OMDocument))
match = ((OMDocument) o).getOMDocumentElement();
this.logger.debug(Messages.getString("XmlService.8"));
break;
default:
this.logger.error("XPath matched "
+ o.getClass().getCanonicalName() + " Node Type:"
+ node.getType());
this.logger.error(Messages.getString("XmlService.11"));
throw new XServicesFault(
Messages.getString("XmlService.12"));
}
} else {
this.logger.error("XPath matched "
+ o.getClass().getCanonicalName());
this.logger.error(Messages.getString("XmlService.11"));
throw new XServicesFault(Messages.getString("XmlService.12"));
}
while (children.hasNext()) {
OMNode container = (OMNode) children.next();
match.insertSiblingAfter((OMNode) container.clone(new OMCloneOptions()));
}
match.detach();
}
xmldocument.build();
return xmldocument;
}
}

View File

@ -0,0 +1,11 @@
XmlService.0=Adding name space to XPath context: 'xmlns:
XmlService.10=XPath did match a comment node
XmlService.11=XPath did match a not supported node
XmlService.12=XPath did match a not supported node
XmlService.13=XPath did not match a node.
XmlService.14=XPath did not match a node.
XmlService.adding_namespace=Adding name space to XPath context: 'xmlns:{0}="{1}"
XmlService.8=XPath did match an element node
XmlService.9=XPath did match a text node
XmlService.no_match=XPath "{0}" did not match anything.
XmlService.null_or_empty=Nothing to append!