Created
August 9, 2011 22:05
-
-
Save kings13y/1135322 to your computer and use it in GitHub Desktop.
Sample Rest style service using just Scala and Java 6 annotations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package output | |
import javax.xml.bind.{ Marshaller, JAXBContext } | |
import javax.xml.bind.annotation._ | |
import javax.xml.bind.util.JAXBSource | |
import javax.xml.transform.Source | |
import javax.xml.ws.{ Endpoint, Provider, ServiceMode, WebServiceContext, WebServiceProvider } | |
import javax.xml.ws.http.HTTPBinding | |
import javax.xml.ws.handler.MessageContext | |
import javax.annotation.Resource | |
@WebServiceProvider | |
@ServiceMode(value=javax.xml.ws.Service.Mode.MESSAGE) | |
class SampleService extends Provider[Source] { | |
@Resource | |
var wsContext : WebServiceContext = _ // Declared but non-init variable as this will be injected at runtime | |
override def invoke(source : Source) : Source = { | |
val mc = wsContext.getMessageContext(); | |
val (path, method) = (mc.get(MessageContext.PATH_INFO), mc.get(MessageContext.HTTP_REQUEST_METHOD)) // Multiple val declaration | |
val marshaller = JAXBContext.newInstance("output").createMarshaller(); | |
marshaller.setProperty("jaxb.formatted.output", true); | |
new JAXBSource(marshaller, new SampleDomainObject(message = "PATH: " + path + " ; METHOD: " + method)) | |
} | |
} | |
object MinimalRestServer extends App { // body of this class is used as a closure in the main() method | |
val port = 8084 | |
val endpoint = Endpoint.create( HTTPBinding.HTTP_BINDING, new SampleService()); | |
endpoint.publish("http://localhost:" + port + "/"); | |
println("Waiting for requests...") | |
} | |
@XmlRootElement | |
@XmlAccessorType(XmlAccessType.FIELD) | |
case class SampleDomainObject(val message: String = "name") { | |
def this() = this("") // Default no arg constructor required by JAXB | |
} | |
@XmlRegistry | |
class ObjectFactory { | |
import javax.xml.bind.JAXBElement // Note the package scoped imports for modularity | |
import javax.xml.bind.annotation.{ XmlElementDecl, XmlRegistry } | |
import javax.xml.namespace.QName | |
private val _SampleDomainObject_QNAME = new QName("", "SampleDomainObject"); | |
def createSampleDomainObject() : SampleDomainObject = { | |
return new SampleDomainObject(); | |
} | |
@XmlElementDecl(namespace = "", name = "SampleDomainObject") | |
def createJaxbLoginResp(value: SampleDomainObject) : JAXBElement[SampleDomainObject] = { | |
return new JAXBElement[SampleDomainObject](_SampleDomainObject_QNAME, classOf[SampleDomainObject], value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment