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,125 +18,124 @@ 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";
} public DateInfoExtendedType getDateExtended() throws XServicesFault {
throw new XServicesFault("Please supply a valid timezone id or none. Valid timezones are:\n" + valid_ids, GregorianCalendar c = new GregorianCalendar();
new Exception( )); DateInfoExtendedType dateinfo = new DateInfoExtendedType(c,
} TimeZone.getDefault());
if (timezone == null || timezone.length()<1 ) timezone = "GMT0"; return dateinfo;
GregorianCalendar c = new GregorianCalendar(TimeZone.getTimeZone(timezone));
return c;
} }
public BigInteger getTimestamp() { public BigInteger getTimestamp() {
Date d = new Date(); Date d = new Date();
long l = d.getTime(); long l = d.getTime();
return new BigInteger(Long.toString(l)); return new BigInteger(Long.toString(l));
} }
public BigInteger getTimestamp2() { public BigInteger getTimestamp2() {
Date d = new Date(); Date d = new Date();
long l = d.getTime()/1000; long l = d.getTime() / 1000;
return new BigInteger(Long.toString(l)); return new BigInteger(Long.toString(l));
} }
public String getInTimezone(Date date, String timezone)
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)
throws XServicesFault { throws XServicesFault {
String result= null; if (!isValidTimezone(timezone))
try { throw new XServicesFault(ERR_INVALIDTIMEZONE);
SimpleDateFormat f = new SimpleDateFormat(format); TimeZone targetzone = TimeZone.getTimeZone(timezone);
result = f.format(cal.getTime()); String targetstring = DateFormatType.ISO8601.format(date, null, targetzone);
} catch (IllegalArgumentException e) { return targetstring;
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);
} }
public String formatDate(Date cal, DateFormatType format)
public GregorianCalendar parseDateAdvanced(String s, String format, String timezone) throws XServicesFault { 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; 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);
date = f.parse(s); date = f.parse(s);
} catch(IllegalArgumentException e) { } catch (IllegalArgumentException e) {
throw new XServicesFault(ERR_INVALIDFORMAT + e.getMessage()); throw new XServicesFault(ERR_INVALIDFORMAT + e.getMessage());
} catch (ParseException e) { } catch (ParseException e) {
throw new XServicesFault("Cannot parse date: "+ e.getMessage()); throw new XServicesFault("Cannot parse date: " + e.getMessage());
} }
GregorianCalendar cal = new GregorianCalendar(); GregorianCalendar cal = new GregorianCalendar();
cal.setTimeZone(TimeZone.getTimeZone(timezone)); cal.setTimeZone(TimeZone.getTimeZone(timezone));
cal.setTime(date); cal.setTime(date);
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,16 +172,19 @@ 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());
} }
return cal; return cal;
} }
private boolean isValidTimezone(String id) { private boolean isValidTimezone(String id) {
boolean yes = false; boolean yes = false;
for( String s: TimeZone.getAvailableIDs()) { for (String s : TimeZone.getAvailableIDs()) {
if(s.equals(id)) { if (s.equals(id)) {
yes = true; yes = true;
break; break;
} }
@ -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,122 +38,116 @@ 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"),
@WSDLDocumentation(value = "Get XService information.") ret.getProperty("ADDR6"));
public ReturnCode getInfo() { return infotype;
ReturnCode r = new ReturnCode(); }
r.returnCode = 0;
// Get all system properties
Properties props = System.getProperties();
// Enumerate all system properties public ReturnCode getInfo() {
Enumeration<String> e = (Enumeration<String>) props.propertyNames(); ReturnCode r = new ReturnCode();
for (; e.hasMoreElements(); ) { r.returnCode = 0;
// Get property name
String propName = (String)e.nextElement();
// Get property value Properties props = System.getProperties();
String propValue = (String)props.get(propName);
r.stdOut = r.stdOut + propName + ": " + propValue + "\n";
}
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, return r;
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 sendMailSimpleWithAttachment(HostConnection mailhost, public ReturnCode sendMailSimple(HostConnection mailhost, String from, String tolist, String subject, String message)
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", null, 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 sendMailSimpleWithAttachment(HostConnection mailhost, String from, String tolist, String subject, String message, FileSetResource res)
String tolist, String cclist, String bcclist, String subject, {
MailMimeType mimetype, String charset, String message, return sendMail(from, from, tolist, "", "", subject, message,
FileSetResource res, boolean ssl, boolean tls) { "text/plain", res, mailhost.hostname, mailhost.port,
return sendMail(from, from, tolist, cclist, bcclist, subject, message, mailhost.user, mailhost.password, "utf-8", false, false);
mimetype.value(), res, mailhost.hostname, mailhost.port, }
mailhost.user, mailhost.password, charset, tls, ssl);
}
public ReturnCode sleep(int minutes, int seconds) { 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 sleep(0, minutes, seconds, 0); {
} 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) { public ReturnCode sleep(int minutes, int seconds) {
HostInfo info = new HostInfo(); return sleep(0, minutes, seconds, 0);
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, public String generateUUID() {
String cclist, String bcclist, String subject, String message, return UUID.randomUUID().toString();
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, 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)
int milliseconds) { {
Sleep sleep = new Sleep(); EmailTask mail = new EmailTask();
sleep.setTaskName("Sleep"); mail.setTaskName("Mail");
RunTask runner = new RunTask(sleep); RunTask runner = new RunTask(mail);
sleep.setHours(hours); mail.setFrom(from);
sleep.setMinutes(minutes); mail.setReplyTo(replyto);
sleep.setSeconds(seconds); mail.setToList(tolist);
sleep.setMilliseconds(milliseconds); mail.setCcList(cclist);
return runner.postTask(); 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();
}
}

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!