Source

atlassian-scala-example-plugin / src / main / scala / com / atlassian / plugins / polyglot / scalaexample / hipchat / RemoteRoomService.scala

Full commit
package com.atlassian.plugins.polyglot.scalaexample.hipchat

import com.atlassian.plugins.polyglot.scalaexample.CustomPluginSettings
import xml.XML
import com.atlassian.sal.api.net._

trait RoomService {
  def roomHistory(i: Int): Either[ResponseException,Seq[Message]]
  def list: Either[ResponseException,Seq[Room]]
}

class RemoteRoomService(requestFactory: RequestFactory[Request[_, Response]],
                        settings: CustomPluginSettings)
  extends RoomService {

  type ServiceRequest = Request[_, Response]

  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))
        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) {
      _.executeAndReturn(handler( {response =>
        val messages = XML.load(response.getResponseBodyAsStream)
        Message.listFromXml(messages)
      }))
    }
  }

  def list = authenticated(Request.MethodType.GET, RemoteRoomService.LIST_ENDPOINT) {
      _.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 {
  val HOST = "https://api.hipchat.com"
  val LIST_ENDPOINT = HOST + "/v1/rooms/list?format=xml"
  val HISTORY_ENDPOINT = HOST + "/v1/rooms/history?format=xml"
}