Commits

Stefan Saasen  committed e49e896

Add error handling, change the RoomService methods to return an Either

  • Participants
  • Parent commits 28a3312

Comments (0)

Files changed (2)

File src/main/scala/com/atlassian/plugins/polyglot/scalaexample/hipchat/RemoteRoomService.scala

 package com.atlassian.plugins.polyglot.scalaexample.hipchat
 
 import com.atlassian.plugins.polyglot.scalaexample.CustomPluginSettings
-import com.atlassian.sal.api.net.{ReturningResponseHandler, Response, Request, RequestFactory}
 import xml.XML
+import com.atlassian.sal.api.net._
 
-
-// TODO return an Either
 trait RoomService {
-  def roomHistory(i: Int): Seq[Message]
-
-  /**Return a list of HipChat rooms */
-  def list: Seq[Room]
+  def roomHistory(i: Int): Either[ResponseException,Seq[Message]]
+  def list: Either[ResponseException,Seq[Room]]
 }
 
 class RemoteRoomService(requestFactory: RequestFactory[Request[_, Response]],
 
   type ServiceRequest = Request[_, Response]
 
-  def authenticated[A](method: Request.MethodType, url: String)(f: (ServiceRequest) => A) = {
+  def authenticated[A](method: Request.MethodType, url: String)(f: (ServiceRequest) => A):Either[ResponseException, A] = {
     settings.authenticationToken map {
       token =>
         val r = requestFactory.createRequest(method, "%s&auth_token=%s" format(url, token.value))
-        f(r)
-    }
+        try {
+          Right(f(r))
+        } catch {
+          case r:ResponseException => Left(r)
+        }
+    } getOrElse Left(new ResponseException("Token Key is missing"))
   }
 
   def roomHistory(roomId: Int) = {
     val url = "%s&room_id=%d&date=recent" format(RemoteRoomService.HISTORY_ENDPOINT, roomId) // TODO add timezone
     authenticated(Request.MethodType.GET, url) {
-    request =>
-      request.executeAndReturn(new ReturningResponseHandler[Response, Seq[Message]]() {
-        def handle(response: Response) = {
-          val messages = XML.load(response.getResponseBodyAsStream)
-          Message.listFromXml(messages)
-        }
-      })
-  } getOrElse Nil}
+      _.executeAndReturn(handler( {response =>
+        val messages = XML.load(response.getResponseBodyAsStream)
+        Message.listFromXml(messages)
+      }))
+    }
+  }
 
   def list = authenticated(Request.MethodType.GET, RemoteRoomService.LIST_ENDPOINT) {
-    request =>
-      request.executeAndReturn(new ReturningResponseHandler[Response, Seq[Room]]() {
-        def handle(response: Response) = {
-          val rooms = XML.load(response.getResponseBodyAsStream)
-          Room.listFromXml(rooms)
-        }
-      })
-  } getOrElse Nil
+      _.executeAndReturn(handler( {response =>
+        val rooms = XML.load(response.getResponseBodyAsStream)
+        Room.listFromXml(rooms)
+      }))
+  }
+
+  def handler[A](f: (Response) => A) = new ReturningResponseHandler[Response, A]() {
+    def handle(response: Response) = f(response)
+  }
 }
 
 object RemoteRoomService {

File src/main/scala/com/atlassian/plugins/polyglot/scalaexample/rest/RoomResource.scala

 package com.atlassian.plugins.polyglot.scalaexample.rest
 
-import javax.ws.rs.core.MediaType
 import com.atlassian.plugins.polyglot.scalaexample.hipchat.RoomService
 import javax.ws.rs._
 
+import core.{Response, MediaType}
 import scala.collection.JavaConverters._
 
 @Path("room")
 @Produces(Array(MediaType.APPLICATION_JSON))
 class RoomResource(roomService:RoomService) {
 
+  def errorHandler(e:Exception) = Response.serverError().entity(e.getLocalizedMessage).build()
+  def success[A](entity:java.util.Collection[A]):Response = Response.ok(entity).build()
+
   @GET
-  def list = roomService.list.asJava
+  def list = roomService.list.fold(
+    e => errorHandler(e),
+    s => success(s.asJava)
+  )
 
   @GET
   @Path("{id : \\d+}")
-  def roomHistory(@PathParam("id") roomId:Int) = roomService.roomHistory(roomId).asJava
+  def roomHistory(@PathParam("id") roomId:Int) = roomService.roomHistory(roomId).fold(
+    e => errorHandler(e),
+    s => success(s.asJava)
+  )
 }