From f2a2f39d1ad71f10a28cb53c9d92d75d9245f643 Mon Sep 17 00:00:00 2001 From: Brian Rosenberger Date: Tue, 5 Feb 2013 14:43:54 +0000 Subject: [PATCH] Arbeitsstand Anfang Februar git-svn-id: https://brutex.net/svn/xservices/trunk@114 e7e49efb-446e-492e-b9ec-fcafc1997a86 --- .../xservices/ws/impl/ArchiveServiceImpl.java | 6 +- .../xservices/ws/impl/DateServiceImpl.java | 166 +++---- .../xservices/ws/impl/FileServiceImpl.java | 17 +- .../brutex/xservices/ws/impl/Messages.java | 44 ++ .../xservices/ws/impl/MiscServiceImpl.java | 209 +++++---- .../xservices/ws/impl/StorageServiceImpl.java | 4 +- .../xservices/ws/impl/XmlServiceImpl.java | 408 ++++++++++++++++++ .../xservices/ws/impl/messages.properties | 11 + 8 files changed, 668 insertions(+), 197 deletions(-) create mode 100644 src/java/net/brutex/xservices/ws/impl/Messages.java create mode 100644 src/java/net/brutex/xservices/ws/impl/XmlServiceImpl.java create mode 100644 src/java/net/brutex/xservices/ws/impl/messages.properties diff --git a/src/java/net/brutex/xservices/ws/impl/ArchiveServiceImpl.java b/src/java/net/brutex/xservices/ws/impl/ArchiveServiceImpl.java index 88865d1..4b8f64c 100644 --- a/src/java/net/brutex/xservices/ws/impl/ArchiveServiceImpl.java +++ b/src/java/net/brutex/xservices/ws/impl/ArchiveServiceImpl.java @@ -19,11 +19,11 @@ import java.io.File; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; -import net.brutex.xservices.types.ArchiveResource; 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.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.RunTask; import net.brutex.xservices.util.UnRarTask; diff --git a/src/java/net/brutex/xservices/ws/impl/DateServiceImpl.java b/src/java/net/brutex/xservices/ws/impl/DateServiceImpl.java index c73c5ee..62bff0f 100644 --- a/src/java/net/brutex/xservices/ws/impl/DateServiceImpl.java +++ b/src/java/net/brutex/xservices/ws/impl/DateServiceImpl.java @@ -18,125 +18,124 @@ package net.brutex.xservices.ws.impl; import java.math.BigInteger; import java.text.ParseException; import java.text.SimpleDateFormat; +import java.util.ArrayList; import java.util.Date; import java.util.GregorianCalendar; +import java.util.List; import java.util.TimeZone; import javax.jws.WebService; - 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.TimeZoneType; import net.brutex.xservices.util.BrutexNamespaces; import net.brutex.xservices.ws.DateService; import net.brutex.xservices.ws.XServicesFault; - /** * @author Brian Rosenberger - * + * */ -@WebService( - targetNamespace = BrutexNamespaces.WS_XSERVICES, - endpointInterface = "net.brutex.xservices.ws.DateService", - serviceName = DateService.SERVICE_NAME - ) +@WebService(targetNamespace = BrutexNamespaces.WS_XSERVICES, endpointInterface = "net.brutex.xservices.ws.DateService", serviceName = DateService.SERVICE_NAME) public class DateServiceImpl implements DateService { private static String ERR_INVALIDFORMAT = "Invalid format pattern."; private static String ERR_INVALIDTIMEZONE = "Invalid timezone."; - - public GregorianCalendar getDate(String timezone) throws XServicesFault { - if (! isValidTimezone(timezone) ) { - String valid_ids = ""; - String[] tid = TimeZone.getAvailableIDs(); - 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 DateInfoType getDate() throws XServicesFault { + GregorianCalendar c = new GregorianCalendar(); + DateInfoType dateinfo = new DateInfoType(c, TimeZone.getDefault()); + return dateinfo; + } + + public DateInfoExtendedType getDateExtended() throws XServicesFault { + GregorianCalendar c = new GregorianCalendar(); + DateInfoExtendedType dateinfo = new DateInfoExtendedType(c, + TimeZone.getDefault()); + return dateinfo; } - public BigInteger getTimestamp() { Date d = new Date(); long l = d.getTime(); return new BigInteger(Long.toString(l)); } - + public BigInteger getTimestamp2() { Date d = new Date(); - long l = d.getTime()/1000; + long l = d.getTime() / 1000; return new BigInteger(Long.toString(l)); } - - public GregorianCalendar getInTimezone(GregorianCalendar cal, - String timezone) throws XServicesFault { - if(! isValidTimezone(timezone)) throw new XServicesFault(ERR_INVALIDTIMEZONE); - GregorianCalendar c = new GregorianCalendar(TimeZone.getTimeZone(timezone)); - c.setTimeInMillis(cal.getTimeInMillis()); - return c; - } - - - public String formatDate(GregorianCalendar cal, DateFormatType format) throws XServicesFault { - return formatDateAdvanced(cal, format.format()); - } - - - public String formatDateAdvanced(GregorianCalendar cal, String format) + public String getInTimezone(Date date, String timezone) throws XServicesFault { - String result= null; - try { - SimpleDateFormat f = new SimpleDateFormat(format); - result = f.format(cal.getTime()); - } catch (IllegalArgumentException e) { - throw new XServicesFault(ERR_INVALIDFORMAT + e.getMessage()); - } - return result; - } - - - public GregorianCalendar parseDate(String s, DateFormatType format, String timezone) throws XServicesFault { - return parseDateAdvanced(s, format.format(), timezone); + if (!isValidTimezone(timezone)) + throw new XServicesFault(ERR_INVALIDTIMEZONE); + TimeZone targetzone = TimeZone.getTimeZone(timezone); + String targetstring = DateFormatType.ISO8601.format(date, null, targetzone); + return targetstring; } - - public GregorianCalendar parseDateAdvanced(String s, String format, String timezone) throws XServicesFault { + public String formatDate(Date cal, DateFormatType format) + throws XServicesFault { + return format.format(cal, null, null); + } + + public String formatDateAdvanced(Date cal, String format) + throws XServicesFault { + String result = null; + SimpleDateFormat f = new SimpleDateFormat(format); + result = f.format(cal); + return result; + } + + public Date parseDate(String s, DateFormatType format, String timezone) + throws XServicesFault { + 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, + String timezone) throws XServicesFault { SimpleDateFormat f = null; Date date = null; - if(timezone==null | timezone.equals("")) timezone = TimeZone.getDefault().getID(); - if(! isValidTimezone(timezone)) throw new XServicesFault(ERR_INVALIDTIMEZONE); - + if (timezone == null | timezone.equals("")) + timezone = TimeZone.getDefault().getID(); + if (!isValidTimezone(timezone)) + throw new XServicesFault(ERR_INVALIDTIMEZONE); + try { f = new SimpleDateFormat(format); date = f.parse(s); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { throw new XServicesFault(ERR_INVALIDFORMAT + e.getMessage()); } catch (ParseException e) { - throw new XServicesFault("Cannot parse date: "+ e.getMessage()); + throw new XServicesFault("Cannot parse date: " + e.getMessage()); } GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone(timezone)); cal.setTime(date); return cal; } - - - public BigInteger dateTimeDiff(GregorianCalendar fromCal, - GregorianCalendar toCal) throws XServicesFault { - long diff = toCal.getTimeInMillis() - fromCal.getTimeInMillis(); + + public BigInteger dateTimeDiff(Date fromCal, Date toCal) + throws XServicesFault { + long diff = toCal.getTime() - fromCal.getTime(); BigInteger d = new BigInteger(String.valueOf(diff), 10); return d; } - - - public BigInteger dateTimeDiff2(GregorianCalendar fromCal, - GregorianCalendar toCal, DateTimeUnits unit) throws XServicesFault { + + public BigInteger dateTimeDiff2(Date fromCal, Date toCal, DateTimeUnits unit) + throws XServicesFault { BigInteger d = dateTimeDiff(fromCal, toCal); switch (unit) { case SECONDS: @@ -150,13 +149,16 @@ public class DateServiceImpl implements DateService { break; case DAYS: d = d.divide(new BigInteger("86400000")); + break; + case YEARS: + d = d.divide(new BigInteger("31536000000")); + break; } return d; } - - - public GregorianCalendar dateAdd(GregorianCalendar cal, BigInteger value, DateTimeUnits unit) - throws XServicesFault { + + public GregorianCalendar dateAdd(GregorianCalendar cal, BigInteger value, + DateTimeUnits unit) throws XServicesFault { switch (unit) { case SECONDS: cal.add(GregorianCalendar.SECOND, value.intValue()); @@ -170,16 +172,19 @@ public class DateServiceImpl implements DateService { case DAYS: cal.add(GregorianCalendar.DAY_OF_MONTH, value.intValue()); break; + case YEARS: + cal.add(GregorianCalendar.YEAR, value.intValue()); + break; default: cal.add(GregorianCalendar.MILLISECOND, value.intValue()); } return cal; } - + private boolean isValidTimezone(String id) { boolean yes = false; - for( String s: TimeZone.getAvailableIDs()) { - if(s.equals(id)) { + for (String s : TimeZone.getAvailableIDs()) { + if (s.equals(id)) { yes = true; break; } @@ -187,4 +192,11 @@ public class DateServiceImpl implements DateService { return yes; } + public List getTimezones() { + List output = new ArrayList(); + for (String s : TimeZone.getAvailableIDs()) { + output.add(new TimeZoneType(TimeZone.getTimeZone(s))); + } + return output; + } } diff --git a/src/java/net/brutex/xservices/ws/impl/FileServiceImpl.java b/src/java/net/brutex/xservices/ws/impl/FileServiceImpl.java index 53f4495..5945eb7 100644 --- a/src/java/net/brutex/xservices/ws/impl/FileServiceImpl.java +++ b/src/java/net/brutex/xservices/ws/impl/FileServiceImpl.java @@ -27,12 +27,12 @@ import javax.jws.WebMethod; import javax.jws.WebParam; 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.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.RunTask; import net.brutex.xservices.ws.FileService; @@ -284,7 +284,7 @@ public class FileServiceImpl implements FileService { */ public ReturnCode echo2file(String message, String file, String encoding, - boolean append) throws XServicesFault { + boolean append, boolean create) throws XServicesFault { Echo echo = new Echo(); echo.setTaskName("toFile"); @@ -292,9 +292,10 @@ public class FileServiceImpl implements FileService { echo.addText(message); echo.setEncoding(encoding); 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: " + f.getCanonicalPath()); @@ -305,7 +306,7 @@ public class FileServiceImpl implements FileService { } catch (BuildException e) { throw new XServicesFault("Error in echo2file.", e); } catch (IOException e) { - throw new XServicesFault("Cannot write to file.", e); + throw new XServicesFault("Cannot write to file." + e.getMessage(), e); } } diff --git a/src/java/net/brutex/xservices/ws/impl/Messages.java b/src/java/net/brutex/xservices/ws/impl/Messages.java new file mode 100644 index 0000000..62566b6 --- /dev/null +++ b/src/java/net/brutex/xservices/ws/impl/Messages.java @@ -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 + '!'; + } +} diff --git a/src/java/net/brutex/xservices/ws/impl/MiscServiceImpl.java b/src/java/net/brutex/xservices/ws/impl/MiscServiceImpl.java index 1ffe8cb..88b93ef 100644 --- a/src/java/net/brutex/xservices/ws/impl/MiscServiceImpl.java +++ b/src/java/net/brutex/xservices/ws/impl/MiscServiceImpl.java @@ -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"); * 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.Properties; +import java.util.UUID; import javax.jws.WebService; -import net.brutex.xservices.types.FileSetResource; import net.brutex.xservices.types.HostConnection; +import net.brutex.xservices.types.HostinfoType; import net.brutex.xservices.types.MailMimeType; 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.RunTask; import net.brutex.xservices.ws.MiscService; @@ -35,122 +38,116 @@ import org.apache.tools.ant.taskdefs.Sleep; import org.apache.tools.ant.taskdefs.email.EmailTask; /** + * Implements the web service * * @author Brian Rosenberger, bru@brutex.de */ -@WSDLDocumentationCollection({ - @WSDLDocumentation("My portType documentation"), - @WSDLDocumentation(value = "My top level documentation", placement = WSDLDocumentation.Placement.TOP), - @WSDLDocumentation(value = "My binding doc", placement = WSDLDocumentation.Placement.BINDING) }) -@WebService( - targetNamespace = BrutexNamespaces.WS_XSERVICES, - endpointInterface = "net.brutex.xservices.ws.MiscService", - serviceName = "MiscService" - ) -public class MiscServiceImpl implements MiscService { +@WebService(targetNamespace="http://ws.xservices.brutex.net", endpointInterface="net.brutex.xservices.ws.MiscService", serviceName="MiscService") +public class MiscServiceImpl + implements MiscService +{ + public HostinfoType getHostinfo(String hostname) + { + HostInfo info = new HostInfo(); + info.setTaskName("HostInfo"); + RunTask runner = new RunTask(info); + info.setHost(hostname); - @WSDLDocumentation(value = "Get information about a host.") - public ReturnCode getHostinfo(String hostname) { - return antGetHostinfo(hostname, null); - } - - @WSDLDocumentation(value = "Get XService information.") - public ReturnCode getInfo() { - ReturnCode r = new ReturnCode(); - r.returnCode = 0; - // Get all system properties - Properties props = System.getProperties(); + ReturnCode ret = runner.postTask(); + HostinfoType infotype = new HostinfoType( + ret.getProperty("NAME"), + ret.getProperty("DOMAIN"), + ret.getProperty("ADDR4"), + ret.getProperty("ADDR6")); + return infotype; + } - // Enumerate all system properties - Enumeration e = (Enumeration) props.propertyNames(); - for (; e.hasMoreElements(); ) { - // Get property name - String propName = (String)e.nextElement(); + public ReturnCode getInfo() { + ReturnCode r = new ReturnCode(); + r.returnCode = 0; - // Get property value - String propValue = (String)props.get(propName); - r.stdOut = r.stdOut + propName + ": " + propValue + "\n"; - } + Properties props = System.getProperties(); - return r; - } + Enumeration e = props.propertyNames(); + while (e.hasMoreElements()) + { + String propName = (String)e.nextElement(); + String propValue = (String)props.get(propName); + r.stdOut = (r.stdOut + propName + ": " + propValue + "\n"); + } - public ReturnCode sendMailSimple(HostConnection mailhost, String from, - String tolist, String subject, String message) { - return sendMail(from, from, tolist, "", "", subject, message, - "text/plain", null, mailhost.hostname, mailhost.port, - mailhost.user, mailhost.password, "utf-8", false, false); - } + return r; + } - public ReturnCode sendMailSimpleWithAttachment(HostConnection mailhost, - String from, String tolist, String subject, String message, - FileSetResource res) { - return sendMail(from, from, tolist, "", "", subject, message, - "text/plain", res, mailhost.hostname, mailhost.port, - mailhost.user, mailhost.password, "utf-8", false, false); - } + public ReturnCode sendMailSimple(HostConnection mailhost, String from, String tolist, String subject, String message) + { + return sendMail(from, from, tolist, "", "", subject, message, + "text/plain", null, mailhost.hostname, mailhost.port, + mailhost.user, mailhost.password, "utf-8", false, false); + } - 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) { - return sendMail(from, from, tolist, cclist, bcclist, subject, message, - mimetype.value(), res, mailhost.hostname, mailhost.port, - mailhost.user, mailhost.password, charset, tls, ssl); - } + public ReturnCode sendMailSimpleWithAttachment(HostConnection mailhost, String from, String tolist, String subject, String message, FileSetResource res) + { + return sendMail(from, from, tolist, "", "", subject, message, + "text/plain", res, mailhost.hostname, mailhost.port, + mailhost.user, mailhost.password, "utf-8", false, false); + } - public ReturnCode sleep(int minutes, int seconds) { - return sleep(0, minutes, seconds, 0); - } + 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) + { + return sendMail(from, from, tolist, cclist, bcclist, subject, message, + mimetype.value(), res, mailhost.hostname, mailhost.port, + mailhost.user, mailhost.password, charset, tls, ssl); + } - private ReturnCode antGetHostinfo(String hostname, String prefix) { - HostInfo info = new HostInfo(); - info.setTaskName("HostInfo"); - RunTask runner = new RunTask(info); - info.setHost(hostname); - // info.setPrefix(prefix); - return runner.postTask(); - } + public ReturnCode sleep(int minutes, int seconds) { + return sleep(0, minutes, seconds, 0); + } - 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) { - EmailTask mail = new EmailTask(); - mail.setTaskName("Mail"); - RunTask runner = new RunTask(mail); - mail.setFrom(from); - mail.setReplyTo(replyto); - mail.setToList(tolist); - mail.setCcList(cclist); - mail.setBccList(bcclist); - mail.setSubject(subject); - mail.setMessage(message); - mail.setMessageMimeType(messagemimetype); - if (attachments != null) { - mail.addFileset(attachments.getAntResource(mail.getProject())); - } - mail.setMailhost(mailhost); - mail.setMailport(mailport); - mail.setUser(user); - mail.setPassword(password); - mail.setCharset(charset); - mail.setSSL(ssl); - mail.setEnableStartTLS(tls); - return runner.postTask(); - } + public String generateUUID() { + return UUID.randomUUID().toString(); + } - private ReturnCode sleep(int hours, int minutes, int seconds, - int milliseconds) { - Sleep sleep = new Sleep(); - sleep.setTaskName("Sleep"); - RunTask runner = new RunTask(sleep); - sleep.setHours(hours); - sleep.setMinutes(minutes); - sleep.setSeconds(seconds); - sleep.setMilliseconds(milliseconds); - return runner.postTask(); - } -} + 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) + { + EmailTask mail = new EmailTask(); + mail.setTaskName("Mail"); + RunTask runner = new RunTask(mail); + mail.setFrom(from); + mail.setReplyTo(replyto); + mail.setToList(tolist); + mail.setCcList(cclist); + mail.setBccList(bcclist); + mail.setSubject(subject); + mail.setMessage(message); + mail.setMessageMimeType(messagemimetype); + if (attachments != null) { + mail.addFileset(attachments.getAntResource(mail.getProject())); + } + mail.setMailhost(mailhost); + mail.setMailport(mailport); + mail.setUser(user); + mail.setPassword(password); + mail.setCharset(charset); + mail.setSSL(ssl); + mail.setEnableStartTLS(tls); + return runner.postTask(); + } + + private ReturnCode sleep(int hours, int minutes, int seconds, int milliseconds) + { + Sleep sleep = new Sleep(); + sleep.setTaskName("Sleep"); + RunTask runner = new RunTask(sleep); + sleep.setHours(hours); + sleep.setMinutes(minutes); + sleep.setSeconds(seconds); + sleep.setMilliseconds(milliseconds); + return runner.postTask(); + } + + public RuntimeInfoType getMemory() { + return new RuntimeInfoType(); + } +} \ No newline at end of file diff --git a/src/java/net/brutex/xservices/ws/impl/StorageServiceImpl.java b/src/java/net/brutex/xservices/ws/impl/StorageServiceImpl.java index 215b97b..a88ae37 100644 --- a/src/java/net/brutex/xservices/ws/impl/StorageServiceImpl.java +++ b/src/java/net/brutex/xservices/ws/impl/StorageServiceImpl.java @@ -34,13 +34,11 @@ public class StorageServiceImpl implements StorageService { public String storeText(String text) throws XServicesFault { // TODO Auto-generated method stub - System.err.println("storeText is not yet implemented"); return null; } public String storeBinary(AttachmentType binary) throws XServicesFault { // TODO Auto-generated method stub - System.err.println("storeBinary is not yet implemented"); return null; } @@ -52,7 +50,7 @@ public class StorageServiceImpl implements StorageService { public void deliverCollection(CollectionType collection, TargetNodeType targetnode, boolean isFiring) throws XServicesFault { // TODO Auto-generated method stub - System.err.println("deliverCollection is not yet implemented"); + } } diff --git a/src/java/net/brutex/xservices/ws/impl/XmlServiceImpl.java b/src/java/net/brutex/xservices/ws/impl/XmlServiceImpl.java new file mode 100644 index 0000000..cc0b992 --- /dev/null +++ b/src/java/net/brutex/xservices/ws/impl/XmlServiceImpl.java @@ -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("" + xmlFragment + "")) + .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("" + replace + "")) + .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("" + xmlFragment + "")) + .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("" + xmlFragment + "")) + .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"; + 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; + } +} diff --git a/src/java/net/brutex/xservices/ws/impl/messages.properties b/src/java/net/brutex/xservices/ws/impl/messages.properties new file mode 100644 index 0000000..890bf1d --- /dev/null +++ b/src/java/net/brutex/xservices/ws/impl/messages.properties @@ -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!