1

The code below produces a NumberFormatException in this line:

val cache = cf.createCache(Collections.emptyMap())

Do you see any errors?
Will I need to write a Java version to avoid this, or is there a Scala way?

...
import java.util.Collections
import net.sf.jsr107cache._

object QueryGenerator extends ServerResource {
  private val log = Logger.getLogger(classOf[QueryGenerator].getName)
}

class QueryGenerator extends ServerResource {
  def getCounter(cache:Cache):long = {
      if (cache.containsKey("counter")) {
        cache.get("counter").asInstanceOf[long]
      } else {
        0l
      }
    }

  @Get("html")
  def getHtml(): Representation = {
    val cf = CacheManager.getInstance().getCacheFactory()
    val cache = cf.createCache(Collections.emptyMap())

    val counter = getCounter(cache)

    cache.put("counter", counter + 1)

    val q = QueueFactory.getQueue("query-generator")
    q.add(TaskOptions.Builder.url("/tasks/query-generator").method(Method.GET).countdownMillis(1000L))

    QueryGenerator.log.warning(counter.toString)

    new StringRepresentation("QueryGenerator started!", MediaType.TEXT_HTML)
  }
}

Thanks!

4

2 回答 2

2

我怀疑异常确实发生在对getCounter. NumberFormatException当您尝试将字符串转换为数字并且该字符串不包含可识别的数字时抛出。

于 2010-04-18T12:05:59.713 回答
0

我现在添加了一个用于放置/更新的小型 Java 类。不是最优雅的解决方案,但它有效。Scala 解决方案仍将受到赞赏。

爪哇:

import javax.cache.Cache;

public class CacheHelper {
    public static final void update(Cache cache,String key,Object value) {
        cache.put(key,value);
    }
}

斯卡拉:

import java.util.Collections
import javax.cache.CacheManager
import somewhere.CacheHelper

object QueryGenerator extends ServerResource {
  private val log = Logger.getLogger(classOf[QueryGenerator].getName)
}

class QueryGenerator extends ServerResource {

  @Get("html")
  def getHtml(): Representation = {
    val cf = CacheManager.getInstance().getCacheFactory()
    val cache = cf.createCache(Collections.emptyMap())

    val counter = if (cache.containsKey("counter")) {
      cache.get("counter").asInstanceOf[Int]
    } else {
      0
    }

    CacheHelper.update(cache,"counter",counter+1)

    val q = QueueFactory.getQueue("query-generator")
    q.add(TaskOptions.Builder.url("/tasks/query-generator").method(Method.GET).countdownMillis(1000L))

    QueryGenerator.log.warning(counter.toString())

    new StringRepresentation("QueryGenerator started!", MediaType.TEXT_HTML)
  }
}
于 2010-04-18T14:06:34.487 回答