溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Scitter庫的增強(qiáng)方法是什么

發(fā)布時(shí)間:2021-12-09 09:15:29 來源:億速云 閱讀:167 作者:iii 欄目:編程語言

本篇內(nèi)容介紹了“Scitter庫的增強(qiáng)方法是什么”的有關(guān)知識(shí),在實(shí)際案例的操作過程中,不少人都會(huì)遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

現(xiàn)在對(duì)于Scala而言,Twitter是一個(gè)很好的學(xué)習(xí)對(duì)象。在之前一篇文章中,Ted已經(jīng)談到了 Twitter,這個(gè)微博客站點(diǎn)目前正引起社會(huì)性網(wǎng)絡(luò)的極大興趣,我們還談到它的基于 XML-/REST 的 API 如何使它成為開發(fā)人員進(jìn)行研究和探索的一個(gè)有趣平臺(tái)。為此,我們首先充實(shí)了“Scitter” 的基本結(jié)構(gòu),Scitter 是用于訪問 Twitter 的一個(gè) Scala 庫。

我們對(duì)于 Scitter 有幾個(gè)目標(biāo):

  1. 簡化 Twitter 訪問,比過去打開 HTTP 連接然后 “手動(dòng)” 執(zhí)行操作更容易。

  2. 可以從 Java 客戶機(jī)輕松訪問它。

  3. 輕松模擬以便進(jìn)行測試。

在這一期,我們不必完成整個(gè) Twitter API,但是我們將完成一些核心部分,目的是讓這個(gè)庫達(dá)到公共源代碼控制庫的程度,便于其他人來完成這項(xiàng)工作。

到目前為止:Scitter 0.1

首先我們簡單回顧一下到目前為止我們所處的階段:

清單 1. Scitter v0.1

package com.tedneward.scitter
{
  import org.apache.commons.httpclient._, auth._, methods._, params._
  import scala.xml._

  /**
   * Status message type. This will typically be the most common message type
   * sent back from Twitter (usually in some kind of collection form). Note
   * that all optional elements in the Status type are represented by the
   * Scala Option[T] type, since that's what it's there for.
   */
  abstract class Status
  {
    /**
     * Nested User type. This could be combined with the top-level User type,
     * if we decide later that it's OK for this to have a boatload of optional
     * elements, including the most-recently-posted status update (which is a
     * tad circular).
     */
    abstract class User
    {
      val id : Long
      val name : String
      val screenName : String
      val description : String
      val location : String
      val profileImageUrl : String
      val url : String
      val protectedUpdates : Boolean
      val followersCount : Int
    }
    /**
     * Object wrapper for transforming (format) into User instances.
     */
    object User
    {
      /*
      def fromAtom(node : Node) : Status =
      {
      
      }
      */
      /*
      def fromRss(node : Node) : Status =
      {
      
      }
      */
      def fromXml(node : Node) : User =
      {
        new User {
          val id = (node \ "id").text.toLong
          val name = (node \ "name").text
          val screenName = (node \ "screen_name").text
          val description = (node \ "description").text
          val location = (node \ "location").text
          val profileImageUrl = (node \ "profile_image_url").text
          val url = (node \ "url").text
          val protectedUpdates = (node \ "protected").text.toBoolean
          val followersCount = (node \ "followers_count").text.toInt
        }
      }
    }
  
    val createdAt : String
    val id : Long
    val text : String
    val source : String
    val truncated : Boolean
    val inReplyToStatusId : Option[Long]
    val inReplyToUserId : Option[Long]
    val favorited : Boolean
    val user : User
  }
  /**
   * Object wrapper for transforming (format) into Status instances.
   */
  object Status
  {
    /*
    def fromAtom(node : Node) : Status =
    {
    
    }
    */
    /*
    def fromRss(node : Node) : Status =
    {
    
    }
    */
    def fromXml(node : Node) : Status =
    {
      new Status {
        val createdAt = (node \ "created_at").text
        val id = (node \ "id").text.toLong
        val text = (node \ "text").text
        val source = (node \ "source").text
        val truncated = (node \ "truncated").text.toBoolean
        val inReplyToStatusId =
          if ((node \ "in_reply_to_status_id").text != "")
            Some((node \"in_reply_to_status_id").text.toLong)
          else
            None
        val inReplyToUserId = 
          if ((node \ "in_reply_to_user_id").text != "")
            Some((node \"in_reply_to_user_id").text.toLong)
          else
            None
        val favorited = (node \ "favorited").text.toBoolean
        val user = User.fromXml((node \ "user")(0))
      }
    }
  }


  /**
   * Object for consuming "non-specific" Twitter feeds, such as the public timeline.
   * Use this to do non-authenticated requests of Twitter feeds.
   */
  object Scitter
  {
    /**
     * Ping the server to see if it's up and running.
     *
     * Twitter docs say:
     * test
     * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
     * URL: http://twitter.com/help/test.format
     * Formats: xml, json
     * Method(s): GET
     */
    def test : Boolean =
    {
      val client = new HttpClient()

      val method = new GetMethod("http://twitter.com/help/test.xml")

      method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
        new DefaultHttpMethodRetryHandler(3, false))

      client.executeMethod(method)
      
      val statusLine = method.getStatusLine()
      statusLine.getStatusCode() == 200
    }
    /**
     * Query the public timeline for the most recent statuses.
     *
     * Twitter docs say:
     * public_timeline
     * Returns the 20 most recent statuses from non-protected users who have set
     * a custom user icon.  Does not require authentication.  Note that the
     * public timeline is cached for 60 seconds so requesting it more often than
     * that is a waste of resources.
     * URL: http://twitter.com/statuses/public_timeline.format
     * Formats: xml, json, rss, atom
     * Method(s): GET
     * API limit: Not applicable
     * Returns: list of status elements     
     */
    def publicTimeline : List[Status] =
    {
      import scala.collection.mutable.ListBuffer
    
      val client = new HttpClient()

      val method = new GetMethod("http://twitter.com/statuses/public_timeline.xml")

      method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
        new DefaultHttpMethodRetryHandler(3, false))

      client.executeMethod(method)
      
      val statusLine = method.getStatusLine()
      if (statusLine.getStatusCode() == 200)
      {
        val responseXML =
          XML.loadString(method.getResponseBodyAsString())

        val statusListBuffer = new ListBuffer[Status]

        for (n <- (responseXML \\ "status").elements)
          statusListBuffer += (Status.fromXml(n))
        
        statusListBuffer.toList
      }
      else
      {
        Nil
      }
    }
  }
  /**
   * Class for consuming "authenticated user" Twitter APIs. Each instance is
   * thus "tied" to a particular authenticated user on Twitter, and will
   * behave accordingly (according to the Twitter API documentation).
   */
  class Scitter(username : String, password : String)
  {
    /**
     * Verify the user credentials against Twitter.
     *
     * Twitter docs say:
     * verify_credentials
     * Returns an HTTP 200 OK response code and a representation of the
     * requesting user if authentication was successful; returns a 401 status
     * code and an error message if not.  Use this method to test if supplied
     * user credentials are valid.
     * URL: http://twitter.com/account/verify_credentials.format
     * Formats: xml, json
     * Method(s): GET
     */
    def verifyCredentials : Boolean =
    {
      val client = new HttpClient()

      val method = new GetMethod("http://twitter.com/help/test.xml")

      method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
        new DefaultHttpMethodRetryHandler(3, false))
        
      client.getParams().setAuthenticationPreemptive(true)
      val creds = new UsernamePasswordCredentials(username, password)
      client.getState().setCredentials(
        new AuthScope("twitter.com", 80, AuthScope.ANY_REALM), creds)

      client.executeMethod(method)
      
      val statusLine = method.getStatusLine()
      statusLine.getStatusCode() == 200
    }
  }
}

代碼有點(diǎn)長,但是很容易分為幾個(gè)基本部分:

  1. case 類 UserStatus,表示 Twitter 在對(duì) API 調(diào)用的響應(yīng)中發(fā)回給客戶機(jī)的基本類型,包括用于構(gòu)造或提取 XML 的一些方法。

  2. 一個(gè) Scitter 獨(dú)立對(duì)象,處理那些不需要對(duì)用戶進(jìn)行驗(yàn)證的操作。

  3. 一個(gè) Scitter 實(shí)例(用 username 和 password 參數(shù)化),用于那些需要對(duì)用戶執(zhí)行驗(yàn)證的操作。

到目前為止,對(duì)于這兩種 Scitter 類型,我們只談到了測試、verifyCredentials 和 public_timeline API。雖然這些有助于確定 HTTP 訪問的基礎(chǔ)(使用 Apache HttpClient 庫)可以工作,并且我們將 XML 響應(yīng)轉(zhuǎn)換成 Status 對(duì)象的基本方式也是可行的,但是現(xiàn)在我們甚至不能進(jìn)行基本的 “我的朋友在說什么” 的公共時(shí)間線查詢,也沒有采取過基本的措施來防止代碼庫中出現(xiàn) “重復(fù)” 問題,更不用說尋找一些方法來模擬用于測試的網(wǎng)絡(luò)訪問代碼。

顯然,在這一期我們有很多事情要做。

連接

對(duì)于代碼,***件讓我煩惱的事就是,我在 Scitter 對(duì)象和類的每個(gè)方法中都重復(fù)這樣的操作序列:創(chuàng)建 HttpClient 實(shí)例,對(duì)它進(jìn)行初始化,用必要的驗(yàn)證參數(shù)對(duì)它進(jìn)行參數(shù)化,等等。當(dāng)它們只有 3 個(gè)方法時(shí),可以進(jìn)行管理,但是顯然不易于伸縮,而且以后還會(huì)增加很多方法。此外,以后重新在那些方法中引入模擬和/或本地/離線測試功能將十分困難。所以我們要解決這個(gè)問題。

實(shí)際上,我們這里介紹的并不是 Scala 本身,而是不要重復(fù)自己(Don't-Repeat-Yourself)的思想。因此,我將從基本的面向?qū)ο蠓椒ㄩ_始:創(chuàng)建一個(gè) helper 方法,用于做實(shí)際工作:

清單 2. 對(duì)代碼庫執(zhí)行 DRY 原則

package com.tedneward.scitter
{
  // ...
  object Scitter
  {
    // ...
    private[scitter] def exec ute(url : String) =
    {
      val client = new HttpClient()
      val method = new GetMethod(url)
      
      method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
        new DefaultHttpMethodRetryHandler(3, false))
        
      client.executeMethod(method)
      
      (method.getStatusLine().getStatusCode(), method.getResponseBodyAsString())
    }
  }
}

注意兩點(diǎn):首先,我從 execute() 方法返回一個(gè)元組,其中包含狀態(tài)碼和響應(yīng)主體。這正是讓元組成為語言中固有的一部分的一個(gè)強(qiáng)大之處,因?yàn)閷?shí)際上很容易從一個(gè)方法調(diào)用返回多個(gè)返回值。當(dāng)然,在 Java 代碼中,也可以通過創(chuàng)建包含元組元素的***或嵌套類來實(shí)現(xiàn)這一點(diǎn),但是這需要一整套專用于這一個(gè)方法的代碼。此外,本來也可以返回一個(gè)包含 String 鍵和 Object 值的 Map,但是那樣就在很大程度上喪失了類型安全性。元組并不是一個(gè)非常具有變革性的特性,它只不過是又一個(gè)使 Scala 成為強(qiáng)大語言的優(yōu)秀特性。

由于使用元組,我需要使用 Scala 的另一個(gè)特色語法將兩個(gè)結(jié)果都捕捉到本地變量中,就像下面這個(gè)重寫后的 Scitter.test 那樣:

清單 3. 這符合 DRY 原則嗎?

package com.tedneward.scitter
{
  // ...
  object Scitter
  {
    /**
     * Ping the server to see if it's up and running.
     *
     * Twitter docs say:
     * test
     * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
     * URL: http://twitter.com/help/test.format
     * Formats: xml, json
     * Method(s): GET
     */
    def test : Boolean =
    {
      val (statusCode, statusBody) =
        execute("http://twitter.com/statuses/public_timeline.xml")
      statusCode == 200
    }
  }
}

實(shí)際上,我可以輕松地將 statusBody 全部去掉,并用 _ 替代它,因?yàn)槲覜]有用過第二個(gè)參數(shù)(test 沒有返回 statusBody),但是對(duì)于其他調(diào)用將需要這個(gè) statusBody,所以出于演示的目的,我保留了該參數(shù)。

注意,execute() 沒有泄露任何與實(shí)際 HTTP 通信相關(guān)的細(xì)節(jié) — 這是 Encapsulation 101。這樣便于以后用其他實(shí)現(xiàn)替換 execute()(以后的確要這么做),或者便于通過重用 HttpClient 對(duì)象來優(yōu)化代碼,而不是每次重新實(shí)例化新的對(duì)象。

接下來,注意到 execute() 方法在 Scitter 對(duì)象上嗎?這意味著我將可以從不同的 Scitter 實(shí)例中使用它(至少現(xiàn)在可以這樣做,如果以后在 execute() 內(nèi)部執(zhí)行的操作不允許這樣做,則另當(dāng)別論)— 這就是我將 execute() 標(biāo)記為 private[scitter] 的原因,這意味著 com.tedneward.scitter 包中的所有內(nèi)容都可以看到它。

(順便說一句,如果還沒有運(yùn)行測試的話,那么請(qǐng)運(yùn)行測試,確保一切運(yùn)行良好。我將假設(shè)我們在討論代碼時(shí)您會(huì)運(yùn)行測試,所以如果我忘了提醒您,并不意味著您也忘記這么做。)

順便說一句,對(duì)于經(jīng)過驗(yàn)證的訪問,為了支持 Scitter 類,需要一個(gè)用戶名和密碼,所以我將創(chuàng)建一個(gè)重載的 execute() 方法,該方法新增兩個(gè) String 參數(shù):

清單 4. 更加 DRY 化的版本

package com.tedneward.scitter
{
  // ...
  object Scitter
  {
    // ...
    private[scitter] def execute(url : String, username : String, password : String) =
    {
      val client = new HttpClient()
      val method = new GetMethod(url)
      
      method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
        new DefaultHttpMethodRetryHandler(3, false))
        
  client.getParams().setAuthenticationPreemptive(true)
  client.getState().setCredentials(
new AuthScope("twitter.com", 80, AuthScope.ANY_REALM),
  new UsernamePasswordCredentials(username, password))
      
      client.executeMethod(method)
      
      (method.getStatusLine().getStatusCode(), method.getResponseBodyAsString())
    }
  }
}

實(shí)際上,除了驗(yàn)證部分,這兩個(gè) execute() 基本上是做相同的事情,我們可以按照第二個(gè)版本完全重寫***個(gè) execute(),但是要注意,Scala 要求顯式表明重載的 execute() 的返回類型:

清單 5. 放棄 DRY

package com.tedneward.scitter
{
  // ...
  object Scitter
  {
    // ...
    private[scitter] def execute(url : String) : (Int, String) =
  execute(url, "", "")
    private[scitter] def execute(url : String, username : String, password : String) =
    {
      val client = new HttpClient()
      val method = new GetMethod(url)
      
      method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
        new DefaultHttpMethodRetryHandler(3, false))
        
      if ((username != "") && (password != ""))
      {
        client.getParams().setAuthenticationPreemptive(true)
        client.getState().setCredentials(
          new AuthScope("twitter.com", 80, AuthScope.ANY_REALM),
            new UsernamePasswordCredentials(username, password))
      }
      
      client.executeMethod(method)
      
      (method.getStatusLine().getStatusCode(), method.getResponseBodyAsString())
    }
  }
}

到目前為止,一切良好。我們對(duì) Scitter 的通信部分進(jìn)行了 DRY 化處理,接下來我們轉(zhuǎn)移到下一件事情:獲得朋友的 tweet 的列表。

連接(到朋友)

Twitter API 表明,friends_timeline API 調(diào)用 “返回認(rèn)證用戶和該用戶的朋友發(fā)表的最近 20 條狀態(tài)”。(它還指出,對(duì)于直接從 Twitter Web 站點(diǎn)使用 Twitter 的用戶,“這相當(dāng)于 Web 上的 ‘/home’”。)對(duì)于任何 Twitter API 來說,這是非?;镜囊?,所以讓我們將它添加到 Scitter 類中。之所以將它添加到類而不是對(duì)象中,是因?yàn)檎缥臋n中指出的那樣,這是以驗(yàn)證用戶的身份做的事情,而我已經(jīng)決定歸入 Scitter 類,而不是 Scitter 對(duì)象。

但是,這里我們碰到一塊絆腳石:friends_timeline 調(diào)用接受一組 “可選參數(shù)”,包括 since_id、max_id、countpage,以控制返回的結(jié)果。這是一項(xiàng)比較復(fù)雜的操作,因?yàn)?Scala 不像其他語言(例如 Groovy、JRuby 或 JavaScript)那樣原生地支持 “可選參數(shù)” 的思想,但是我們首先來處理簡單的東西 — 我們來創(chuàng)建一個(gè) friendsTimeline 方法,該方法只執(zhí)行一般的、非參數(shù)化的調(diào)用:

清單 6.“告訴我你身邊的朋友是怎樣的...”

package com.tedneward.scitter
{
  class Scitter
  {
    def friendsTimeline : List[Status] =
    {
      val (statusCode, statusBody) =
       Scitter.execute("http://twitter.com/statuses/friends_timeline.xml",
                        username, password)

      if (statusCode == 200)
      {
        val responseXML = XML.loadString(statusBody)

        val statusListBuffer = new ListBuffer[Status]

        for (n <- (responseXML \\ "status").elements)
          statusListBuffer += (Status.fromXml(n))
        
        statusListBuffer.toList
      }
      else
      {
        Nil
      }
    }
  }
}

到目前為止,一切良好。用于測試的相應(yīng)方法看上去如下所示:

清單 7. “我能判斷您是怎樣的人 ”(Miguel de Cervantes)

package com.tedneward.scitter.test
{
  class ScitterTests
  {
    // ...

    @Test def scitterFriendsTimeline =
    {
      val scitter = new Scitter(testUser, testPassword)
      val result = scitter.friendsTimeline
      assertTrue(result.length > 0)
    }
  }
}

好極了??瓷先ゾ拖?Scitter 對(duì)象中的 publicTimeline() 方法,并且行為也幾乎完全相同。

對(duì)于我們來說,那些可選參數(shù)仍然有問題。因?yàn)?Scala 并沒有可選參數(shù)這樣的語言特性,乍一看來,惟一的選擇就是完整地創(chuàng)建重載的 friendsTimeline() 方法,讓該方法帶有一定數(shù)量的參數(shù)。

幸運(yùn)的是,還有一種更好的方式,即通過一種有趣的方式將 Scala 的兩個(gè)語言特性(有一個(gè)特性我還沒有提到過) — case 類和 “重復(fù)參數(shù)” 結(jié)合起來(見清單 8):

清單 8. “我有多愛你?……”

package com.tedneward.scitter
{
  // ...
  
  abstract class OptionalParam
  case class Id(id : String) extends OptionalParam
  case class UserId(id : Long) extends OptionalParam
  case class Since(since_id : Long) extends OptionalParam
  case class Max(max_id : Long) extends OptionalParam
  case class Count(count : Int) extends OptionalParam
  case class Page(page : Int) extends OptionalParam
  
  class Scitter(username : String, password : String)
  {
    // ...

    def friendsTimeline(options : OptionalParam*) : List[Status] =
    {
      val optionsStr =
        new StringBuffer("http://twitter.com/statuses/friends_timeline.xml?")
      for (option <- options)
      {
        option match
        {
          case Since(since_id) =>
            optionsStr.append("since_id=" + since_id.toString() + "&")
          case Max(max_id) =>
            optionsStr.append("max_id=" + max_id.toString() + "&")
          case Count(count) =>
            optionsStr.append("count=" + count.toString() + "&")
          case Page(page) =>
            optionsStr.append("page=" + page.toString() + "&")
        }
      }
      
      val (statusCode, statusBody) =
        Scitter.execute(optionsStr.toString(), username, password)
      if (statusCode == 200)
      {
        val responseXML = XML.loadString(statusBody)

        val statusListBuffer = new ListBuffer[Status]

        for (n <- (responseXML \\ "status").elements)
          statusListBuffer += (Status.fromXml(n))
        
        statusListBuffer.toList
      }
      else
      {
        Nil
      }
    }
  }
}

看到標(biāo)在選項(xiàng)參數(shù)后面的 * 嗎?這表明該參數(shù)實(shí)際上是一個(gè)參數(shù)序列,這類似于 Java 5 中的 varargs 結(jié)構(gòu)。和 varargs 一樣,傳遞的參數(shù)數(shù)量可以像前面那樣為 0(不過,我們將需要回到測試代碼,向 friendsTimeline 調(diào)用增加一對(duì)括號(hào),否則編譯器無法作出判斷:是調(diào)用不帶參數(shù)的方法,還是出于部分應(yīng)用之類的目的而調(diào)用該方法);我們還可以開始傳遞那些 case 類型,如下面的清單所示:

清單 9. “……聽我細(xì)細(xì)說”(William Shakespeare)

package com.tedneward.scitter.test
{
  class ScitterTests
  {
    // ...

    @Test def scitterFriendsTimelineWithCount =
    {
      val scitter = new Scitter(testUser, testPassword)
      val result = scitter.friendsTimeline(Count(5))
      assertTrue(result.length == 5)
    }
  }
}

當(dāng)然,總是存在這樣的可能性:客戶機(jī)傳入古怪的參數(shù)序列,例如 friendsTimeline(Count(5), Count(6), Count(7)),但是在這里,我們只是將列表傳遞給 Twitter(希望它們的錯(cuò)誤處理足夠強(qiáng)大,能夠只采用指定的***那個(gè)參數(shù))。當(dāng)然,如果真的擔(dān)心這一點(diǎn),也很容易在構(gòu)造發(fā)送到 Twitter 的 URL 之前,從頭至尾檢查重復(fù)參數(shù)列表,并采用指定的每種參數(shù)的***一個(gè)參數(shù)。不過,后果自負(fù)。

兼容性

但是,這又產(chǎn)生一個(gè)有趣的問題:從 Java 代碼調(diào)用這個(gè)方法有多容易?畢竟,如果這個(gè)庫的主要目標(biāo)之一是維護(hù)與 Java 代碼的兼容性,那么我們需要確保 Java 代碼在使用它時(shí)不至于太麻煩。

我們首先通過我們的好朋友 javap 檢驗(yàn)一下 Scitter 類:

清單 10. 哦,沒錯(cuò),Java 代碼……我現(xiàn)在想起來了……

C:\>javap -classpath classes com.tedneward.scitter.Scitter
Compiled from "scitter.scala"
public class com.tedneward.scitter.Scitter extends java.lang.Object implements s
cala.ScalaObject{
    public com.tedneward.scitter.Scitter(java.lang.String, java.lang.String);
    public scala.List friendsTimeline(scala.Seq);
    public boolean verifyCredentials();
    public int $tag()       throws java.rmi.RemoteException;
}

這時(shí)我心中有兩點(diǎn)擔(dān)心。首先,friendsTimeline() 帶有一個(gè) scala.Seq 參數(shù)(這是我們剛才用過的重復(fù)參數(shù)特性)。其次,friendsTimeline() 方法和 Scitter 對(duì)象中的 publicTimeline() 方法一樣(如果不信,可以運(yùn)行 javap 查證),返回一個(gè)元素列表 scala.List。這兩種類型在 Java 代碼中有多好用?

最簡單的方法是用 Java 代碼而不是 Scala 編寫一組小型的 JUnit 測試,所以接下來我們就這樣做。雖然可以測試 Scitter 實(shí)例的構(gòu)造,并調(diào)用它的 verifyCredentials() 方法,但這些并不是特別有用 — 記住,我們不是要驗(yàn)證 Scitter 類的正確性,而是要看看從 Java 代碼中使用它有多容易。為此,我們直接編寫一個(gè)測試,該測試將獲取 “friends timeline” — 換句話說,我們要實(shí)例化一個(gè) Scitter 實(shí)例,并且不使用任何參數(shù)來調(diào)用它的 friendsTimeline() 方法。

這有點(diǎn)復(fù)雜,因?yàn)樾枰獋魅搿?code>scala.Seq 參數(shù) — scala.Seq 是一個(gè) Scala 特性,它將映射到底層 JVM 中的一個(gè)接口,所以不能直接實(shí)例化。我們可以嘗試典型的 Java null 參數(shù),但是這樣做會(huì)在運(yùn)行時(shí)拋出異常。我們需要的是一個(gè) scala.Seq 類,以便從 Java 代碼中輕松地實(shí)例化這個(gè)類。

最終,我們還是在 mutable.ListBuffer 類型中找到一個(gè)這樣的類,這正是在 Scitter 實(shí)現(xiàn)本身中使用的類型:

清單 11. 現(xiàn)在我明白了自己為什么喜歡 Scala……

package com.tedneward.scitter.test;

import org.junit.*;
import com.tedneward.scitter.*;

public class JavaScitterTests
{
  public static final String testUser = "TESTUSER";
  public static final String testPassword = "TESTPASSWORD";
  
  @Test public void getFriendsStatuses()
  {
    Scitter scitter = new Scitter(testUser, testPassword);
    if (scitter.verifyCredentials())
    {
      scala.List statuses =
        scitter.friendsTimeline(new scala.collection.mutable.ListBuffer());
      Assert.assertTrue(statuses.length() > 0);
    }
    else
      Assert.assertTrue(false);
  }
}

使用返回的 scala.List 不是問題,因?yàn)槲覀兛梢韵駥?duì)待其他 Collection 類一樣對(duì)待它(不過我們的確懷念 Collection 的一些優(yōu)點(diǎn),因?yàn)?List 上基于 Scala 的方法都假設(shè)您將從 Scala 中與它們交互),所以,遍歷結(jié)果并不難,只要用上一點(diǎn) “舊式” Java 代碼(大約 1995 年時(shí)候的風(fēng)格):

清單 12. 重回 1995,又見 Vector……

package com.tedneward.scitter.test;

import org.junit.*;
import com.tedneward.scitter.*;

public class JavaScitterTests
{
  public static final String testUser = "TESTUSER";
  public static final String testPassword = "TESTPASSWORD";

  @Test public void getFriendsStatuses()
  {
    Scitter scitter = new Scitter(testUser, testPassword);
    if (scitter.verifyCredentials())
    {
      scala.List statuses =
        scitter.friendsTimeline(new scala.collection.mutable.ListBuffer());
      Assert.assertTrue(statuses.length() > 0);
      
      for (int i=0; i<STATUSES.LENGTH(); PRE < } Assert.assertTrue(false); else stat.text()); + ? said System.out.println(stat.user().screenName() stat="(Status)statuses.apply(i);" Status { i++)>

這將我們引向另一個(gè)部分,即將參數(shù)傳遞到 friendsTimeline() 方法。不幸的是,ListBuffer 類型不是將一個(gè)集合作為構(gòu)造函數(shù)參數(shù),所以我們必須構(gòu)造參數(shù)列表,然后將集合傳遞到方法調(diào)用。這樣有些單調(diào)乏味,但還可以承受:

清單 13. 現(xiàn)在可以回到 Scala 嗎?

package com.tedneward.scitter.test;

import org.junit.*;
import com.tedneward.scitter.*;

public class JavaScitterTests
{
  public static final String testUser = "TESTUSER";
  public static final String testPassword = "TESTPASSWORD";
  
  // ...

  @Test public void getFriendsStatusesWithCount()
  {
    Scitter scitter = new Scitter(testUser, testPassword);
    if (scitter.verifyCredentials())
    {
      scala.collection.mutable.ListBuffer params =
        new scala.collection.mutable.ListBuffer();
      params.$plus$eq(new Count(5));
      
      scala.List statuses = scitter.friendsTimeline(params);

      Assert.assertTrue(statuses.length() > 0);
      Assert.assertTrue(statuses.length() == 5);
      
      for (int i=0; i<STATUSES.LENGTH(); PRE < } Assert.assertTrue(false); else stat.text()); + ? said System.out.println(stat.user().screenName() stat="(Status)statuses.apply(i);" Status { i++)>

所以,雖然 Java 版本比對(duì)應(yīng)的 Scala 版本要冗長一點(diǎn),但是到目前為止,從任何要使用 Scitter 庫的 Java 客戶機(jī)中調(diào)用該庫仍然非常簡單。好極了。

“Scitter庫的增強(qiáng)方法是什么”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI