Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Split imaging from other modules

  • Loading branch information...
commit a53fe393ca9a4cd2a3326e8ddaacf09a8e7225b1 1 parent 6a9f1b0
@d6y d6y authored
Showing with 0 additions and 20,970 deletions.
  1. +0 −163 amqp/src/main/scala/net/liftweb/amqp/AMQPDispatcher.scala
  2. +0 −137 amqp/src/main/scala/net/liftweb/amqp/AMQPSender.scala
  3. +0 −69 facebook/src/main/scala/net/liftweb/ext_api/facebook/Facebook.scala
  4. +0 −70 facebook/src/main/scala/net/liftweb/ext_api/facebook/FacebookConnect.scala
  5. +0 −399 facebook/src/main/scala/net/liftweb/ext_api/facebook/FacebookRestApi.scala
  6. +0 −130 imaging/src/main/scala/net/liftweb/imaging/ImageHelpers.scala
  7. +0 −248 imaging/src/main/scala/net/liftweb/imaging/ImageResizer.scala
  8. +0 −41 imaging/src/test/scala/net/liftweb/imaging/ImageResizerSpec.scala
  9. +0 −76 jta/README.textile
  10. +0 −56 jta/src/main/resources/jta.properties
  11. +0 −16 jta/src/main/resources/persistence.xml
  12. +0 −64 jta/src/main/scala/net/liftweb/transaction/EntityManagerSynchronization.scala
  13. +0 −234 jta/src/main/scala/net/liftweb/transaction/TransactionContext.scala
  14. +0 −239 jta/src/main/scala/net/liftweb/transaction/TransactionService.scala
  15. +0 −57 jta/src/main/scala/net/liftweb/transaction/atomikos/AtomikosTransactionService.scala
  16. +0 −36 jta/src/main/scala/net/liftweb/transaction/hibernate/LiftTransactionManagerLookup.scala
  17. +0 −61 jta/src/test/scala/TransactionMonadSpec.scala
  18. +0 −15 liftsh
  19. +0 −14 liftsh.cmd
  20. +0 −373 machine/src/main/scala/net/liftweb/machine/ProtoStateMachine.scala
  21. +0 −44 machine/src/test/scala/bootstrap/liftweb/Boot.scala
  22. 0  oauth-mapper/src/main/scala/net/liftweb/oauth/.keep
  23. +0 −157 oauth-mapper/src/main/scala/net/liftweb/oauth/mapper/OAuthConsumer.scala
  24. +0 −78 oauth-mapper/src/main/scala/net/liftweb/oauth/mapper/OAuthNonce.scala
  25. +0 −112 oauth-mapper/src/main/scala/net/liftweb/oauth/mapper/OAuthToken.scala
  26. +0 −189 oauth/src/main/scala/net/liftweb/oauth/OAuth.scala
  27. +0 −64 oauth/src/main/scala/net/liftweb/oauth/OAuthAccessor.scala
  28. +0 −81 oauth/src/main/scala/net/liftweb/oauth/OAuthMessage.scala
  29. +0 −35 oauth/src/main/scala/net/liftweb/oauth/OAuthProblemException.scala
  30. +0 −154 oauth/src/main/scala/net/liftweb/oauth/OAuthSignatureMethod.scala
  31. +0 −105 oauth/src/main/scala/net/liftweb/oauth/OAuthTraits.scala
  32. +0 −121 oauth/src/main/scala/net/liftweb/oauth/OAuthValidator.scala
  33. +0 −77 oauth/src/test/scala/net/liftweb/oauth/OAuthSignatureMethodSpec.scala
  34. +0 −248 openid/src/main/scala/net/liftweb/openid/Extensions.scala
  35. +0 −316 openid/src/main/scala/net/liftweb/openid/OpenID.scala
  36. +0 −263 openid/src/main/scala/net/liftweb/openid/OpenIDProtoUser.scala
  37. +0 −36 openid/src/test/scala/net/liftweb/openid/RawHelperSpec.scala
  38. +0 −16 osgi/src/main/scala/net/liftweb/osgi/OsgiBootable.scala
  39. +0 −187 osgi/src/main/scala/net/liftweb/osgi/internal/Activator.scala
  40. BIN  paypal/src/main/resources/toserve/paypal/en_buynow_107x26.gif
  41. BIN  paypal/src/main/resources/toserve/paypal/en_buynow_68x23.gif
  42. BIN  paypal/src/main/resources/toserve/paypal/en_buynow_cards_122x47.gif
  43. BIN  paypal/src/main/resources/toserve/paypal/en_paynow_107x26.gif
  44. BIN  paypal/src/main/resources/toserve/paypal/en_paynow_cards_144x47.gif
  45. +0 −565 paypal/src/main/scala/net/liftweb/paypal/Paypal.scala
  46. +0 −45 paypal/src/main/scala/net/liftweb/paypal/Rules.scala
  47. +0 −47 paypal/src/main/scala/net/liftweb/paypal/snippet/BuyNow.scala
  48. +0 −47 paypal/src/test/scala/net/liftweb/paypal/PaypalIPNSpec.scala
  49. +0 −7 project/build.properties
  50. +0 −93 project/build/LiftModulesProject.scala
  51. +0 −10 project/plugins/Plugins.scala
  52. BIN  project/sbt-launch-0.7.7.jar
  53. +0 −141 scalate/src/main/scala/net/liftweb/scalate/LiftTemplateEngine.scala
  54. +0 −100 scalate/src/main/scala/net/liftweb/scalate/ScalateView.scala
  55. +0 −1,380 textile/src/main/scala/net/liftweb/textile/TextileParser.scala
  56. +0 −523 textile/src/test/scala/net/liftweb/textile/TextileSpec.scala
  57. 0  widgets/src/main/resources/net/liftweb/widgets/.keep
  58. BIN  widgets/src/main/resources/toserve/autocomplete/indicator.gif
  59. +0 −49 widgets/src/main/resources/toserve/autocomplete/jquery.autocomplete.css
  60. +0 −759 widgets/src/main/resources/toserve/autocomplete/jquery.autocomplete.js
  61. +0 −162 widgets/src/main/resources/toserve/calendars/dayview/style.css
  62. +0 −194 widgets/src/main/resources/toserve/calendars/js/calendarviews.js
  63. +0 −110 widgets/src/main/resources/toserve/calendars/monthview/style.css
  64. +0 −166 widgets/src/main/resources/toserve/calendars/weekview/style.css
  65. +0 −100 widgets/src/main/resources/toserve/common/jquery.bgiframe.js
  66. +0 −119 widgets/src/main/resources/toserve/common/jquery.dimensions.js
  67. +0 −266 widgets/src/main/resources/toserve/common/jquery.tooltip.js
  68. +0 −1,427 widgets/src/main/resources/toserve/flot/excanvas.js
  69. +0 −20 widgets/src/main/resources/toserve/flot/jquery.flot.css
  70. +0 −2,599 widgets/src/main/resources/toserve/flot/jquery.flot.js
  71. +0 −336 widgets/src/main/resources/toserve/flot/jquery.flot.navigate.js
  72. +0 −33 widgets/src/main/resources/toserve/logchanger/logchanger.css
  73. BIN  widgets/src/main/resources/toserve/menu/images/arrows-ffffff.png
  74. BIN  widgets/src/main/resources/toserve/menu/images/shadow.png
  75. +0 −100 widgets/src/main/resources/toserve/menu/jquery.bgiframe.js
  76. +0 −111 widgets/src/main/resources/toserve/menu/jquery.hoverIntent.js
  77. +0 −93 widgets/src/main/resources/toserve/menu/superfish-navbar.css
  78. +0 −23 widgets/src/main/resources/toserve/menu/superfish-vertical.css
  79. +0 −136 widgets/src/main/resources/toserve/menu/superfish.css
  80. +0 −121 widgets/src/main/resources/toserve/menu/superfish.js
  81. +0 −90 widgets/src/main/resources/toserve/menu/supersubs.js
  82. +0 −125 widgets/src/main/resources/toserve/sparklines/sparklines.min.js
  83. BIN  widgets/src/main/resources/toserve/tablesorter/addons/pager/icons/first.png
  84. BIN  widgets/src/main/resources/toserve/tablesorter/addons/pager/icons/last.png
  85. BIN  widgets/src/main/resources/toserve/tablesorter/addons/pager/icons/next.png
  86. BIN  widgets/src/main/resources/toserve/tablesorter/addons/pager/icons/prev.png
  87. +0 −25 widgets/src/main/resources/toserve/tablesorter/addons/pager/jquery.tablesorter.pager.css
  88. +0 −184 widgets/src/main/resources/toserve/tablesorter/addons/pager/jquery.tablesorter.pager.js
  89. +0 −852 widgets/src/main/resources/toserve/tablesorter/jquery.tablesorter.js
  90. BIN  widgets/src/main/resources/toserve/tablesorter/themes/blue/asc.gif
  91. BIN  widgets/src/main/resources/toserve/tablesorter/themes/blue/bg.gif
  92. BIN  widgets/src/main/resources/toserve/tablesorter/themes/blue/desc.gif
  93. +0 −39 widgets/src/main/resources/toserve/tablesorter/themes/blue/style.css
  94. BIN  widgets/src/main/resources/toserve/tablesorter/themes/green/asc.png
  95. BIN  widgets/src/main/resources/toserve/tablesorter/themes/green/bg.png
  96. BIN  widgets/src/main/resources/toserve/tablesorter/themes/green/desc.png
  97. +0 −39 widgets/src/main/resources/toserve/tablesorter/themes/green/style.css
  98. BIN  widgets/src/main/resources/toserve/tree/images/file.gif
  99. BIN  widgets/src/main/resources/toserve/tree/images/folder-closed.gif
  100. BIN  widgets/src/main/resources/toserve/tree/images/folder.gif
  101. BIN  widgets/src/main/resources/toserve/tree/images/minus.gif
  102. BIN  widgets/src/main/resources/toserve/tree/images/plus.gif
  103. BIN  widgets/src/main/resources/toserve/tree/images/spinner.gif
  104. BIN  widgets/src/main/resources/toserve/tree/images/treeview-black-line.gif
  105. BIN  widgets/src/main/resources/toserve/tree/images/treeview-black.gif
  106. BIN  widgets/src/main/resources/toserve/tree/images/treeview-default-line.gif
  107. BIN  widgets/src/main/resources/toserve/tree/images/treeview-default.gif
  108. BIN  widgets/src/main/resources/toserve/tree/images/treeview-famfamfam-line.gif
  109. BIN  widgets/src/main/resources/toserve/tree/images/treeview-famfamfam.gif
  110. BIN  widgets/src/main/resources/toserve/tree/images/treeview-gray-line.gif
  111. BIN  widgets/src/main/resources/toserve/tree/images/treeview-gray.gif
  112. BIN  widgets/src/main/resources/toserve/tree/images/treeview-red-line.gif
  113. BIN  widgets/src/main/resources/toserve/tree/images/treeview-red.gif
  114. +0 −82 widgets/src/main/resources/toserve/tree/jquery.treeview.async.js
  115. +0 −136 widgets/src/main/resources/toserve/tree/jquery.treeview.css
  116. +0 −251 widgets/src/main/resources/toserve/tree/jquery.treeview.js
  117. +0 −100 widgets/src/main/resources/toserve/uploadprogress/uploadprogress.js
  118. +0 −219 widgets/src/main/scala/net/liftweb/widgets/autocomplete/AutoComplete.scala
  119. +0 −135 widgets/src/main/scala/net/liftweb/widgets/calendars/CalendarDayView.scala
  120. +0 −68 widgets/src/main/scala/net/liftweb/widgets/calendars/CalendarItem.scala
  121. +0 −234 widgets/src/main/scala/net/liftweb/widgets/calendars/CalendarMonthView.scala
  122. +0 −81 widgets/src/main/scala/net/liftweb/widgets/calendars/CalendarUtils.scala
  123. +0 −172 widgets/src/main/scala/net/liftweb/widgets/calendars/CalendarWeekView.scala
  124. +0 −40 widgets/src/main/scala/net/liftweb/widgets/calendars/ViewMeta.scala
  125. +0 −261 widgets/src/main/scala/net/liftweb/widgets/flot/Flot.scala
  126. +0 −91 widgets/src/main/scala/net/liftweb/widgets/flot/FlotAjax.scala
  127. +0 −37 widgets/src/main/scala/net/liftweb/widgets/flot/FlotCapability.scala
  128. +0 −221 widgets/src/main/scala/net/liftweb/widgets/flot/FlotOptions.scala
  129. +0 −109 widgets/src/main/scala/net/liftweb/widgets/flot/FlotOverview.scala
  130. +0 −41 widgets/src/main/scala/net/liftweb/widgets/flot/FlotSerie.scala
  131. +0 −27 widgets/src/main/scala/net/liftweb/widgets/flot/FlotUtils.scala
  132. +0 −86 widgets/src/main/scala/net/liftweb/widgets/gravatar/Gravatar.scala
  133. +0 −261 widgets/src/main/scala/net/liftweb/widgets/logchanger/LogLevelChanger.scala
  134. +0 −131 widgets/src/main/scala/net/liftweb/widgets/menu/MenuWidget.scala
  135. +0 −68 widgets/src/main/scala/net/liftweb/widgets/rssfeed/RSSfeed.scala
  136. +0 −29 widgets/src/main/scala/net/liftweb/widgets/sparklines/SparklineStyle.scala
  137. +0 −101 widgets/src/main/scala/net/liftweb/widgets/sparklines/Sparklines.scala
  138. +0 −159 widgets/src/main/scala/net/liftweb/widgets/tablesorter/TableSorter.scala
  139. +0 −175 widgets/src/main/scala/net/liftweb/widgets/tree/TreeView.scala
  140. +0 −144 widgets/src/main/scala/net/liftweb/widgets/uploadprogress/UploadProgress.scala
  141. +0 −84 widgets/src/test/scala/bootstrap/liftweb/Boot.scala
  142. +0 −59 widgets/src/test/scala/webapptest/snippet/AutoCompleteDemo.scala
  143. +0 −147 widgets/src/test/scala/webapptest/snippet/CalendarDayViewDemo.scala
  144. +0 −89 widgets/src/test/scala/webapptest/snippet/CalendarMonthViewDemo.scala
  145. +0 −147 widgets/src/test/scala/webapptest/snippet/CalendarWeekViewDemo.scala
  146. +0 −33 widgets/src/test/scala/webapptest/snippet/GravatarDemo.scala
  147. +0 −31 widgets/src/test/scala/webapptest/snippet/MenuSnippet.scala
  148. +0 −34 widgets/src/test/scala/webapptest/snippet/RSSFeedDemo.scala
  149. +0 −49 widgets/src/test/scala/webapptest/snippet/SparklinesDemo.scala
  150. +0 −48 widgets/src/test/scala/webapptest/snippet/TableSorterDemo.scala
  151. +0 −86 widgets/src/test/scala/webapptest/snippet/TreeViewDemo.scala
  152. +0 −59 widgets/src/test/scala/webapptest/snippet/UploadProgressDemo.scala
  153. +0 −21 widgets/src/test/webapp/WEB-INF/web.xml
  154. +0 −3  widgets/src/test/webapp/anothermenu1.html
  155. +0 −3  widgets/src/test/webapp/anothermenu2.html
  156. +0 −10 widgets/src/test/webapp/autocomplete.html
  157. +0 −8 widgets/src/test/webapp/calday.html
  158. +0 −9 widgets/src/test/webapp/calmonth.html
  159. +0 −7 widgets/src/test/webapp/calweek.html
  160. +0 −4 widgets/src/test/webapp/gravatar.html
  161. +0 −137 widgets/src/test/webapp/index.html
  162. +0 −4 widgets/src/test/webapp/rssfeed.html
  163. +0 −6 widgets/src/test/webapp/sparklines.html
  164. +0 −61 widgets/src/test/webapp/style/style.css
  165. +0 −3  widgets/src/test/webapp/submenu1.html
  166. +0 −3  widgets/src/test/webapp/submenu2.html
  167. +0 −3  widgets/src/test/webapp/submenu3.html
  168. +0 −18 widgets/src/test/webapp/templates-hidden/default.html
  169. +0 −9 widgets/src/test/webapp/tree.html
  170. +0 −54 widgets/src/test/webapp/uploadprogress.html
  171. +0 −265 xmpp/src/main/scala/net/liftweb/xmpp/XMPPDispatcher.scala
View
163 amqp/src/main/scala/net/liftweb/amqp/AMQPDispatcher.scala
@@ -1,163 +0,0 @@
-/*
- * Copyright 2007-2010 WorldWide Conferencing, LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.liftweb {
-package amqp {
-
-import _root_.com.rabbitmq.client._
-import _root_.net.liftweb.actor._
-import _root_.java.io.ObjectInputStream
-import _root_.java.io.ByteArrayInputStream
-import _root_.java.util.Timer
-import _root_.java.util.TimerTask
-
-/**
- * @param a The actor to add as a Listener to this Dispatcher.
- */
-case class AMQPAddListener(a: LiftActor)
-
-/**
- * @param message A deserialized value received via AMQP.
- *
- * Messages received from AMQP are wrapped in this case class. When you
- * register a listener, this is the case class that you will be matching on.
- */
-case class AMQPMessage[T](message: T)
-
-
-/**
- * Reconnect to the AMQP Server after a delay of {@code delay} milliseconds.
- */
-case class AMQPReconnect(delay: Long)
-
-/**
- * An actor that serves as an endpoint for AMQP messages of serialized type T
- * coming into a specific queue/exchange.
- *
- * To listen for messages coming into that queue/exchange, send
- * this actor an AMQPAddListener message.
- *
- * For each message containing a value of type T, all listeners will be send
- * an AMQPMessage contaning that value.
- *
- * See also Enterprise Integration Patterns pp. 508-514
- *
- * @author Steve Jenson (stevej@pobox.com)
- */
-abstract class AMQPDispatcher[T](cf: ConnectionFactory, host: String, port: Int) extends LiftActor {
- var (conn, channel) = connect()
- private var as: List[LiftActor] = Nil
-
- private def connect(): (Connection, Channel) = {
- val conn = cf.newConnection(host, port)
- val channel = conn.createChannel()
- configure(channel)
- (conn, channel)
- }
-
- /**
- * Override this to configure the Channel and Consumer.
- */
- def configure(channel: Channel)
-
- private val reconnectTimer = new Timer("AMQPReconnectTimer")
-
- protected def messageHandler = {
- case AMQPAddListener(a) => as ::= a
- case msg@AMQPMessage(t) => as.foreach(_ ! msg)
- case AMQPReconnect(delay: Long) =>
- try {
- val details = connect()
- conn = details._1
- channel = details._2
- println("AMQPDispatcher: Successfully reconnected to AMQP Server")
- } catch {
- // Attempts to reconnect again using geometric back-off.
- case e: Exception => {
- val amqp = this
- println("AMQPDispatcher: Will attempt reconnect again in " + (delay * 2) + "ms.")
- reconnectTimer.schedule(new TimerTask(){
- override def run = {
- amqp ! AMQPReconnect(delay * 2)
- }
- }, delay)
- }
- }
- case _ =>
- }
-}
-
-/**
- * Example consumer on an AMQP channel.
- */
-class SerializedConsumer[T](channel: Channel, a: LiftActor) extends DefaultConsumer(channel) {
- override def handleDelivery(tag: String, env: Envelope, props: AMQP.BasicProperties, body: Array[Byte]) {
- val routingKey = env.getRoutingKey
- val contentType = props.getContentType
- val deliveryTag = env.getDeliveryTag
- val in = new ObjectInputStream(new ByteArrayInputStream(body))
- val t = in.readObject.asInstanceOf[T];
- // Send t to all registered listeners.
- a ! AMQPMessage(t)
- channel.basicAck(deliveryTag, false);
- }
-}
-
-/**
- * Example Dispatcher that listens on an example queue and exchange. Use this
- * as your guiding example for creating your own Dispatcher.
- *
- */
-class ExampleSerializedAMQPDispatcher[T](factory: ConnectionFactory, host: String, port: Int)
- extends AMQPDispatcher[T](factory, host, port) {
- override def configure(channel: Channel) {
- // Set up the exchange and queue
- channel.exchangeDeclare("mult", "direct")
- channel.queueDeclare("mult_queue")
- channel.queueBind("mult_queue", "mult", "routeroute")
- // Use the short version of the basicConsume method for convenience.
- channel.basicConsume("mult_queue", false, new SerializedConsumer(channel, this))
- }
-}
-
-/**
- * Example class that accepts Strings coming in from the
- * ExampleSerializedAMQPDispatcher.
- */
-class ExampleStringAMQPListener {
- val params = new ConnectionParameters
- params.setUsername("guest")
- params.setPassword("guest")
- params.setVirtualHost("/")
- params.setRequestedHeartbeat(0)
-
- val factory = new ConnectionFactory(params)
- // thor.local is a machine on your network with rabbitmq listening on port 5672
- val amqp = new ExampleSerializedAMQPDispatcher[String](factory, "thor.local", 5672)
-
- // Example Listener that just prints the String it receives.
-
- val stringListener = new LiftActor {
- protected def messageHandler = {
- case msg@AMQPMessage(contents: String) => println("received: " + msg)
- }
- }
-
- amqp ! AMQPAddListener(stringListener)
-}
-
-}
-}
View
137 amqp/src/main/scala/net/liftweb/amqp/AMQPSender.scala
@@ -1,137 +0,0 @@
-/*
- * Copyright 2007-2011 WorldWide Conferencing, LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.liftweb
-package amqp
-
-import net.liftweb.actor._
-import com.rabbitmq.client._
-import java.io.ByteArrayOutputStream
-import java.io.ObjectOutputStream
-
-/**
- * An actor with a long-lived connection to an AMQP exchange/queue.
- *
- * @see ExampleStringAMQPSender for an example use.
- * @author Steve Jenson (stevej@pobox.com)
- */
-abstract class AMQPSender[T](cf: ConnectionFactory, host: String, port: Int, exchange: String, routingKey: String) extends LiftActor {
- val conn = cf.newConnection(host, port)
- val channel = conn.createChannel()
-
- /**
- * Override this to use your own AMQP queue/exchange with the given channel.
- */
- def configure(channel: Channel): AnyRef
-
- def sendMsg(msg: T) {
- // Now write an object to a byte array and shove it across the wire.
- val bytes = new ByteArrayOutputStream
- val store = new ObjectOutputStream(bytes)
- store.writeObject(msg)
- store.close
- channel.basicPublish(exchange, routingKey, null, bytes.toByteArray)
- }
-
- protected def messageHandler = {
- case AMQPMessage(msg: T) => sendMsg(msg)
- }
-}
-
-/**
- * An example subclass of AMQPSender[T]
- *
- * An example of how to send messages to an AMQP queue/exchange. Notice that this
- * is setup with the same params as StringAQMPExample. After making a new instance of
- * StringAMQPExample, just send ExampleAMQPSender ! "hi" to see the message "hi"
- * appear in the output log. Fun and Easy!
- *
- * If you are planning to send lots of messages to lots of different exchange/queues,
- * consider creating Actor-based Senders, that will help your application to scale.
- */
-class StringAMQPSender(cf: ConnectionFactory, host: String, port: Int, exchange: String, routingKey: String)
- extends AMQPSender[String](cf, host, port, exchange, routingKey){
- override def configure(channel: Channel) = {
- val conn = cf.newConnection(host, port)
- val channel = conn.createChannel()
- channel
- }
-}
-
-/**
- * An Example of how to use the Example subclass of AMQPSender[T]. Still following?
- */
-class ExampleStringAMQPSender {
- val params = new ConnectionParameters
- // All of the params, exchanges, and queues are all just example data.
- params.setUsername("guest")
- params.setPassword("guest")
- params.setVirtualHost("/")
- params.setRequestedHeartbeat(0)
- val factory = new ConnectionFactory(params)
-
- val amqp = new StringAMQPSender(factory, "localhost", 5672, "mult", "routeroute")
- amqp ! AMQPMessage("hi")
-}
-
-/**
- * An example of using AMQP in a short-lived manner, setting up and tearing down
- * the connection whenever you need it. The long-lived example above is more
- * efficient with resources.
- */
-object ExampleDirectAMQPSender {
- def sendMsg[T](msg: T) {
- val params = new ConnectionParameters
- // All of the params, exchanges, and queues are all just example data.
- params.setUsername("guest")
- params.setPassword("guest")
- params.setVirtualHost("/")
- params.setRequestedHeartbeat(0)
- sendMsg(msg, params, "localhost", 5672)
- }
-
- def sendMsg[T](msg: T, params: ConnectionParameters, host: String, port: Int) {
- val factory = new ConnectionFactory(params)
- val conn = factory.newConnection(host, port)
- val channel = conn.createChannel()
- // Now write an object to a byte array and shove it across the wire.
- val bytes = new ByteArrayOutputStream
- val store = new ObjectOutputStream(bytes)
- store.writeObject(msg)
- store.close
- channel.basicPublish("mult", "routeroute", null, bytes.toByteArray)
- }
-}
-
-/**
- * Just a few examples of how you might test this. Mostly useful snippets
- * for me to run from script/console to see the bits flying.
- */
-object AMQPExampleFunPack {
- def directExample {
- val recv = new ExampleStringAMQPListener()
- // You should see the message 'hi'
- val sender = new ExampleStringAMQPSender()
- sender
- }
- def actorExample {
- val recv = new ExampleStringAMQPListener()
- // You probably know what message you are going to see. 'hello!'
- val sender = ExampleDirectAMQPSender.sendMsg("hello!")
- sender
- }
-}
-
View
69 facebook/src/main/scala/net/liftweb/ext_api/facebook/Facebook.scala
@@ -1,69 +0,0 @@
-/*
- * Copyright 2007-2010 WorldWide Conferencing, LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.liftweb {
-package ext_api {
-package facebook {
-
-import _root_.net.liftweb.http.{S, SessionVar}
-import _root_.net.liftweb.util.Helpers._
-import _root_.net.liftweb.common.{Box, Empty, Failure, Full}
-
-object Facebook {
- object SessionKey extends SessionVar[Box[String]](sessionKey)
-
- def canvasPage_? : Boolean = S.param("fb_sig_in_canvas") match {
- case Full(num) if toInt(num) == 1 => true
- case _ => false
- }
-
- def addedApplication_? : Boolean = S.param("fb_sig_added") match {
- case Full(num) if toInt(num) == 1 => true
- case _ => false
- }
-
- def loggedIn_? : Boolean = S.param("fb_sig_user") match {
- case Full(num) if toInt(num) > 0 => true
- case _ => false
- }
-
- def userId: Box[Int] = S.param("fb_sig_user") match {
- case Full(num) => Full(toInt(num))
- case _ => Empty
- }
-
- def userId_! : Int = userId.open_!
-
- private def authToken : Box[String] = S.param("auth_token")
-
- def sessionKey : Box[String] = S.param("fb_sig_session_key")
-
- def sessionKey_! : String = sessionKey.open_!
-
- def loginUrl: String = "http://www.facebook.com/login.php?api_key=" + FacebookRestApi.apiKey + "&v=1.0"
- def addUrl : String = "http://www.facebook.com/add.php?api_key=" + FacebookRestApi.apiKey
-
- // To conform with FacebookClient.State
- implicit val facebookClientState: FacebookClient.State = new {
- def sessionKey: Option[String] = S.param("fb_sig_session_key")
- def expiration: Option[Long] = S.param("fb_sig_expires").map[Long](_.toLong)
- def uid: Option[String] = S.param("fb_sig_user")
- }
-}
-
-}
-}
-}
View
70 facebook/src/main/scala/net/liftweb/ext_api/facebook/FacebookConnect.scala
@@ -1,70 +0,0 @@
-/*
- * Copyright 2010 WorldWide Conferencing, LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.liftweb {
-package ext_api {
-package facebook {
-
-import _root_.net.liftweb.http.{S}
-import _root_.net.liftweb.util.Helpers._
-import _root_.net.liftweb.common.{Box, Empty, Failure, Full}
-import scala.xml.{Node}
-
-object FacebookConnect extends FacebookConnect(FacebookRestApi.apiKey, FacebookRestApi.secret)
-
-class FacebookConnect(apiKey:String, apiSecret:String) {
-
- private val prefix = apiKey + "_"
-
- def toSession(params: List[(String,String)]):Box[FacebookSession] = toSession(Map(params:_*))
-
- def toSession(asMap: Map[String,String]):Box[FacebookSession] = {
- for { key <- asMap.get("session_key")
- expirationStr <- asMap.get("expires")
- expiration <- asLong(expirationStr)
- uid <- asMap.get("user") } yield FacebookSession(key, expiration, uid)
- }
-
- def session:Box[FacebookSession] = for (p <- verifyCookiesSig; s <- toSession(p)) yield s
-
- def client:Box[FacebookClient[Node]] = session.map(session => new FacebookClient(apiKey, apiSecret, session, FacebookClient.xmlParser, FacebookFormat.xml))
-
- def verifyParams(params: List[(String,String)], sig: String):Box[List[(String,String)]] = {
- val actualSig = FacebookClient.genSignature(params, apiSecret)
- if (actualSig.equals(sig))
- Full(params)
- else {
- Failure("Invalid Signature expected %s but was %s".format(sig, actualSig))
- }
- }
-
- def verifyCookiesSig:Box[List[(String,String)]] = S.findCookie(apiKey) match {
- case Full(sigCookie) =>
- val fbCookies = for(c <- S.receivedCookies; value <- c.value; if c.name.startsWith(prefix)) yield (c.name.substring(prefix.length), value)
- val ret = verifyParams(fbCookies, sigCookie.value.openOr(""))
- if (ret.isEmpty) {
- for(c <- S.receivedCookies if c.name.startsWith(apiKey)){
- S.addCookie(c.setMaxAge(0))
- }
- }
- ret
- case _ => Empty
- }
-}
-
-}
-}
-}
View
399 facebook/src/main/scala/net/liftweb/ext_api/facebook/FacebookRestApi.scala
@@ -1,399 +0,0 @@
-/*
- * Copyright 2007-2011 WorldWide Conferencing, LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.liftweb {
-package ext_api {
-package facebook {
-
-import java.net.{HttpURLConnection, URL, URLEncoder}
-import java.io.DataOutputStream
-import java.io.InputStream
-import java.util.Date
-
-import xml.{Node, XML, NodeSeq}
-
-import util.Helpers._
-
-object FacebookRestApi {
- def apiKey = System.getProperty("com.facebook.api_key")
- def secret = System.getProperty("com.facebook.secret")
- def apiKey_=(key: String) = System.setProperty("com.facebook.api_key", key)
- def secret_=(key: String) = System.setProperty("com.facebook.secret", key)
-}
-
-object FacebookClient {
- import FacebookRestApi._
-
- var readTimeout = 10.seconds
- var connectTimeout = 10.seconds
-
- val TARGET_API_VERSION = "1.0"
- val FB_SERVER = "api.facebook.com/restserver.php"
- val SERVER_ADDR = "http://" + FB_SERVER
- val HTTPS_SERVER_ADDR = "https://" + FB_SERVER
-
- val SERVER_URL = new URL(SERVER_ADDR)
- val HTTPS_SERVER_URL = new URL(HTTPS_SERVER_ADDR)
-
- val CrLf = "\r\n"
- val Pref = "--"
-
- def urlEncode(name: String): String = URLEncoder.encode(name, "UTF-8")
-
- def stripSig(in: String): String = if (in != null && in.startsWith("fb_sig_")) in.substring(7) else in
-
- def convert(in: List[(String, Any)]): List[String] = in.map{case (name, value) => stripSig(name)+"="+value}
-
- def byteToHex(b: Byte): String = Integer.toHexString((b & 0xf0) >>> 4) + Integer.toHexString(b & 0x0f)
-
- def genSignature(allParams: List[(String, Any)], secret: String): String = {
- val md = _root_.java.security.MessageDigest.getInstance("MD5")
- val theStr = convert(allParams).sortWith(_ < _).mkString("") + secret
-
- md.digest((theStr).getBytes).map(byteToHex(_)).mkString("")
- }
-
- private[facebook] def call[T](params: List[(String, Any)], parser:InputStream => T): T = {
- val theParams = params.map{case (name, value) => urlEncode(name)+"="+urlEncode(value.toString)}.mkString("&")
-
- SERVER_URL.openConnection match {
- case conn: HttpURLConnection => {
- conn.setReadTimeout(readTimeout.millis.toInt)
- conn.setConnectTimeout(connectTimeout.millis.toInt)
-
- conn.setRequestMethod("POST") // [ticket #27]
- conn.setDoOutput(true)
- conn.connect
- conn.getOutputStream.write(theParams.getBytes())
-
- parser(conn.getInputStream())
- }
- }
- }
- private[facebook] def call(params: List[(String, Any)]): Node = call(params, xmlParser)
-
- def xmlParser(is:InputStream):Node = XML.load(is)
-
- private[facebook] def buildParams(methodName: String, params: FacebookParam*): List[(String, Any)] = {
- val allParams: List[(String, Any)] =
- ("method", methodName) ::
- ("api_key", apiKey) ::
- ("v", TARGET_API_VERSION) ::
- params.map(p => (p.key, p.value)).toList
-
- val signature = genSignature(allParams, secret)
-
- val ret = "sig" -> signature :: allParams
- ret
- }
-
- def callMethod(meth: SessionlessFacebookMethod): Node =
- call(buildParams(meth.name, meth.params: _*))
-
- def !?(meth: SessionlessFacebookMethod): Node =
- callMethod(meth)
-
- def fromSession(session: FacebookSession) : FacebookClient[Node] = {
- new FacebookClient(session, xmlParser,FacebookFormat.xml)
- }
-
- def fromAuthToken(authToken: String) : Option[FacebookClient[Node]] = {
- FacebookSession.fromAuthToken(authToken).map(fromSession)
- }
-
- type State = {
- def sessionKey: Option[String]
- def expiration: Option[Long]
- def uid: Option[String]
- }
-
- def fromState(implicit state: State) : Option[FacebookClient[Node]] = {
- for (
- key <- state.sessionKey;
- exp <- state.expiration;
- uid <- state.uid
- ) yield fromSession(FacebookSession(key, exp, uid))
- }
-}
-
-object FacebookFormat extends Enumeration("XML", "JSON"){
- val xml, json = Value
-}
-
-class FacebookClient[T](val apiKey: String, val secret: String, val session: FacebookSession, parser: InputStream=>T, format: FacebookFormat.Value) {
- import FacebookRestApi._
- import FacebookClient._
-
- def this(session: FacebookSession, parser:InputStream => T, format:FacebookFormat.Value) = this(FacebookRestApi.apiKey, FacebookRestApi.secret, session, parser, format)
-
- def callMethod(meth: FacebookMethod, fileName: String, mimeType: String, file: Array[Byte], params: FacebookParam* ): T = {
- val boundary = System.currentTimeMillis.toString
- SERVER_URL.openConnection match {
- case conn: HttpURLConnection => {
- conn.setReadTimeout(readTimeout.millis.toInt)
- conn.setConnectTimeout(connectTimeout.millis.toInt)
-
- conn.setDoInput(true)
- conn.setDoOutput(true)
- conn.setUseCaches(false)
- conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary)
- conn.setRequestProperty("MIME-version", "1.0")
-
- val out = new DataOutputStream(conn.getOutputStream())
-
- buildParams(meth, params: _*).foreach {
- case (name, value) =>
- out.writeBytes(Pref + boundary + CrLf)
- out.writeBytes("Content-disposition: form-data; name='" + name + "'")
- out.writeBytes(CrLf + CrLf + value.toString + CrLf)
- }
-
- out.writeBytes(Pref + boundary + CrLf)
- out.writeBytes("Content-disposition: form-data; filename='" +
- fileName + "'" + CrLf)
- out.writeBytes("Content-Type: " + mimeType + CrLf + CrLf)
-
- out.write(file)
-
- out.writeBytes(CrLf + Pref + boundary + Pref + CrLf)
-
- out.flush()
- out.close()
-
- parser(conn.getInputStream)
- }
- }
- }
-
- def callMethod(meth: FacebookMethod): T =
- call(buildParams(meth, meth.params: _*), parser)
-
- def callMethod(meth: FacebookMethod, otherParams: FacebookParam*): T =
- call(buildParams(meth, (meth.params.toList ::: otherParams.toList): _*), parser)
-
- def !?(meth: FacebookMethod): T = callMethod(meth)
-
- def !?(meth: FacebookMethod, otherParams: UniversalParam*) = callMethod(meth, otherParams: _*)
-
- def !?(meth: UploadPhoto): T = callMethod(meth, meth.fileName, meth.mimeType, meth.fileData)
-
- private def buildParams(meth: FacebookMethod, params: FacebookParam*): List[(String, Any)] = {
- val allParams: List[FacebookParam] = FacebookParam("format" -> format.toString)::
- (if (meth.requiresSession)
- List(FacebookParam("call_id" -> System.currentTimeMillis), FacebookParam("session_key" -> session.key))
- else
- Nil) :::
- params.toList
-
- FacebookClient.buildParams(meth.name, allParams: _*)
- }
-
- def getInfo(users: Iterable[Long], fields: FacebookField*): T = {
- callMethod(GetInfo(users, fields: _*))
- }
-}
-
-object FacebookSession {
- def apply(key: String, expiration: Long, uid: String) : FacebookSession =
- new FacebookSession(key, expiration, uid)
-
- def fromAuthToken(authToken: String): Option[FacebookSession] = {
- val response = FacebookClient !? AuthGetSession(authToken)
- val key = (response \\ "session_key").text
- val uid = (response \\ "uid").text
- val expiration = (response \\ "expires").text
-
- if (key == "")
- None
- else
- Some(FacebookSession(key, expiration.toLong, uid))
- }
-}
-
-class FacebookSession(val key: String, val expiration: Long, val uid: String)
-
-class FacebookMethod(val name: String, attachment: Boolean, val params: FacebookParam*) {
- def this(nm: String, params: FacebookParam*) = { this(nm, false, params: _*) }
-
- def requiresSession: Boolean = true
-}
-
-class SessionlessFacebookMethod(override val name: String, override val params: FacebookParam*) extends FacebookMethod(name, false, params: _*) {
-
- override def requiresSession = false
-}
-
-
-case object AuthCreateToken extends SessionlessFacebookMethod("facebook.auth.createToken")
-case class AuthGetSession(authToken: String) extends SessionlessFacebookMethod("facebook.auth.getSession", AuthToken(authToken))
-case class GetFriends(optionalParams: GetFriendsParam*) extends FacebookMethod("facebook.friends.get", optionalParams: _*)
-case object GetFriendLists extends FacebookMethod("facebook.friends.getLists")
-case class FqlQuery(query: String) extends FacebookMethod("facebook.fql.query", Query(query))
-case class FqlMultiQuery(queries: Map[String,String]) extends FacebookMethod("facebook.fql.multiquery", FacebookParam("queries", {
- queries.map(p => "\""+p._1+"\":\""+p._2+"\"").mkString("{",",","}")
-}))
-case class GetEvents(filters: GetEventsParam*) extends FacebookMethod("facebook.events.get", filters: _*)
-case class GetEventsMembers(eventId: Long) extends FacebookMethod("facebook.events.getMembers", EventId(eventId))
-case object GetAppUsers extends FacebookMethod("facebook.friends.getAppUsers")
-//case object GetRequests extends FacebookMethod("facebook.friends.getRequests") /*This method is not listed in the current facebook api. deprecated?*/
-case class AreFriends(friends1: Iterable[Long], friends2: Iterable[Long]) extends FacebookMethod("facebook.friends.areFriends", FacebookParam("uids1", friends1.mkString(",")), FacebookParam("uids2", friends2.mkString(",")))
-case class GetInfo(users: Iterable[Long], fields: FacebookField*) extends FacebookMethod("facebook.users.getInfo", UserIds(users.toList: _*), FacebookFields(fields: _*))
-case object GetUser extends FacebookMethod("facebook.users.getLoggedInUser")
-case class GetPhotos(primaryFilter: GetPhotosParam, otherFilters: GetPhotosParam*) extends FacebookMethod("facebook.photos.get", (primaryFilter :: otherFilters.toList): _*)
-case class GetAlbums(primaryFilter: GetAlbumsParam, otherFilters: GetAlbumsParam*) extends FacebookMethod("facebook.photos.getAlbums", (primaryFilter :: otherFilters.toList): _*)
-case class GetPhotoTags(photoIds: Long*) extends FacebookMethod(" facebook.photos.getTags", PhotoIds(photoIds: _*))
-case class CreatePhotoAlbum(albumName: String, otherParams: CreatePhotoAlbumParam*) extends FacebookMethod("facebook.photos.createAlbum", (NameParam(albumName) :: otherParams.toList): _*)
-case class AddPhotoTags(photoId: Long, tags: PhotoTag*) extends FacebookMethod("facebook.photos.addTag", PhotoId(photoId), Tags(tags: _*))
-case class UploadPhoto(fileName: String, mimeType: String, fileData: Array[Byte], otherParams: UploadPhotoParam*) extends FacebookMethod("facebook.photos.upload", true, otherParams: _*)
-case object GetNotifications extends FacebookMethod("facebook.notifications.get")
-case class SendNotifications(notification: NodeSeq, recipients: Long*) extends FacebookMethod("facebook.notifications.send", RecipientIds(recipients: _*), Notification(notification))
-//case class SendRequest extends FacebookMethod("facebook.notifications.sendRequest", 5) /*This method was disabled by the facebook api*/
-case class GetGroups(filters: GetGroupsParam*) extends FacebookMethod("facebook.groups.get", filters: _*)
-case class GetGroupMembers(groupId: Long) extends FacebookMethod("facebook.groups.getMembers", GroupId(groupId))
-case class SetFBML(optionalParams: SetFbmlParam*) extends FacebookMethod("facebook.profile.setFBML", optionalParams: _*)
-case class GetFBML(optionalParams: GetFbmlParam*) extends FacebookMethod("facebook.profile.getFBML", optionalParams: _*)
-case class RefreshImage(imageUrl: String) extends FacebookMethod("facebook.fbml.refreshImgSrc", Url(imageUrl))
-case class RefreshRefURL(refUrl: String) extends FacebookMethod("facebook.fbml.refreshRefUrl", Url(refUrl))
-case class SetRefHandle(handle: String, markup: NodeSeq) extends FacebookMethod("facebook.fbml.setRefHandle", RefHandle(handle), FBML(markup))
-
-case class StreamPublish(publishParams: StreamPublishParam*) extends FacebookMethod("facebook.stream.publish", (publishParams.toList): _*)
-
-class FacebookField(val name: String)
-
-case object AboutMe extends FacebookField("about_me")
-case object Activities extends FacebookField("activities")
-case object Affiliations extends FacebookField("affiliations")
-case object Birthday extends FacebookField("birthday")
-case object Books extends FacebookField("books")
-case object CurrentLocation extends FacebookField("current_location")
-case object EducationHistory extends FacebookField("education_history")
-case object FirstName extends FacebookField("first_name")
-case object AddedApp extends FacebookField("has_added_app")
-case object Hometown extends FacebookField("hometown_location")
-case object Highschool extends FacebookField("hs_info")
-case object Interests extends FacebookField("interests")
-case object AppUser extends FacebookField("is_app_user")
-case object LastName extends FacebookField("last_name")
-case object MeetingFor extends FacebookField("meeting_for")
-case object LookingFor extends FacebookField("meeting_for")
-case object MeetingSex extends FacebookField("meeting_sex")
-case object InterestedIn extends FacebookField("meeting_sex")
-case object Movies extends FacebookField("movies")
-case object Music extends FacebookField("music")
-case object Name extends FacebookField("name")
-case object NotesCount extends FacebookField("notes_count")
-case object Pic extends FacebookField("pic")
-case object BigPic extends FacebookField("pic_big")
-case object SmallPic extends FacebookField("pic_small")
-case object SquarePic extends FacebookField("pic_square")
-case object PoliticalView extends FacebookField("political")
-case object UpdateTime extends FacebookField("profile_update_time")
-case object Quotes extends FacebookField("quotes")
-case object Relationship extends FacebookField("relationship_status")
-case object RelationshipStatus extends FacebookField("relationship_status")
-case object Religion extends FacebookField("religion")
-case object Sex extends FacebookField("sex")
-case object SignificantOther extends FacebookField("significant_other_id")
-case object Status extends FacebookField("status")
-case object Timezone extends FacebookField("timezone")
-case object TV extends FacebookField("tv")
-case object WallCount extends FacebookField("wall_count")
-case object WorkHistory extends FacebookField("work_history")
-case object Email extends FacebookField("email")
-case object Username extends FacebookField("username")
-
-sealed abstract class PhotoTag(x: Double, y: Double){ def toJSON: String }
-case class TagById(userId: Long, x: Double, y: Double) extends PhotoTag(x, y){
- def toJSON = "{'x':'" + x.toString + "','y':'" + y.toString + "','tag_uid':" + userId.toString + "}"
-}
-case class TagByName(name: String, x: Double, y: Double) extends PhotoTag(x, y){
- def toJSON = "{'x':'" + x.toString + "','y':'" + y.toString + "','tag_text':'" + name.toString + "'}"
-}
-
-object FacebookParam {
- def apply(key: String, value: Any) = new FacebookParam(key, value)
- def apply(pair: (String, Any)) = new FacebookParam(pair)
-}
-
-class FacebookParam(val key: String, val value: Any){
- def this(pair: (String, Any)) = this(pair._1, pair._2)
-}
-trait UniversalParam extends FacebookParam
-trait GetFriendsParam extends FacebookParam
-trait GetEventsParam extends FacebookParam
-trait GetPhotosParam extends FacebookParam
-trait GetAlbumsParam extends FacebookParam
-trait GetPhotoTagsParam extends FacebookParam
-trait CreatePhotoAlbumParam extends FacebookParam
-trait AddPhotoTagsParam extends FacebookParam
-trait SendNotificationParam extends FacebookParam
-trait GetGroupsParam extends FacebookParam
-trait GetGroupMembersParam extends FacebookParam
-trait SetFbmlParam extends FacebookParam
-trait GetFbmlParam extends FacebookParam
-trait RefreshImageParam extends FacebookParam
-trait RefreshRefParam extends FacebookParam
-trait SetRefHandleParam extends FacebookParam
-trait StreamPublishParam extends FacebookParam
-trait UploadPhotoParam extends FacebookParam
-
-case class Callback(functionName: String) extends FacebookParam("callback", functionName) with UniversalParam
-
-case class AuthToken(token: String) extends FacebookParam("auth_token", token)
-case class Query(query: String) extends FacebookParam("query", query)
-case class FacebookFields(fields: FacebookField*) extends FacebookParam("fields", fields.map(_.name).mkString(","))
-case class FriendListId(friendListId: Long) extends FacebookParam("flid", friendListId) with GetFriendsParam
-case class UserId(userId: Long) extends FacebookParam("uid", userId) with GetEventsParam with GetAlbumsParam with GetGroupsParam with SetFbmlParam with GetFbmlParam
-case class UserIds(userIds: Long*) extends FacebookParam("uids", userIds.mkString(","))
-case class EventId(eventId: Long) extends FacebookParam("eid", eventId)
-case class EventIds(eventIds: Long*) extends FacebookParam("eids", eventIds.mkString(",")) with GetEventsParam
-case class StartTime(startTime: Date) extends FacebookParam("start_time", startTime.getTime()) with GetEventsParam
-case class EndTime(endTime: Date) extends FacebookParam("end_time", endTime.getTime()) with GetEventsParam
-case object RsvpAttending extends FacebookParam("rsvp_status", "attending") with GetEventsParam
-case object RsvpUnsure extends FacebookParam("rsvp_status", "unsure") with GetEventsParam
-case object RsvpDeclined extends FacebookParam("rsvp_status", "declined") with GetEventsParam
-case object RsvpNotReplied extends FacebookParam("rsvp_status", "not_replied") with GetEventsParam
-case class SubjectId(subjectId: Long) extends FacebookParam("subj_id", subjectId) with GetPhotosParam
-case class AlbumId(albumId: Long) extends FacebookParam("aid", albumId) with GetPhotosParam with AddPhotoTagsParam with UploadPhotoParam
-case class AlbumIds(albumIds: Long*) extends FacebookParam("aids", albumIds.mkString(",")) with GetAlbumsParam
-case class PhotoId(photoId: Long) extends FacebookParam("pid", photoId) with AddPhotoTagsParam
-case class PhotoIds(photoIds: Long*) extends FacebookParam("pids", photoIds.mkString(",")) with GetPhotosParam with GetPhotoTagsParam
-case class NameParam(name: String) extends FacebookParam("name", name) with CreatePhotoAlbumParam
-case class Location(location: String) extends FacebookParam("location", location) with CreatePhotoAlbumParam
-case class Description(description: String) extends FacebookParam("description", description) with CreatePhotoAlbumParam
-case class TagUserId(userId: Long) extends FacebookParam("tag_uid", userId)
-case class TagText(text: String) extends FacebookParam("tag_text", text)
-case class Tags(tags: PhotoTag*) extends FacebookParam("tags", tags.map(_.toJSON).mkString("[", ",", "]"))
-case class Notification(markup: NodeSeq) extends FacebookParam("notification", markup) with SendNotificationParam
-case class RecipientIds(recipientIds: Long*) extends FacebookParam("to_ids", recipientIds.mkString(",")) with SendNotificationParam
-case class GroupId(groupId: Long) extends FacebookParam("gid", groupId) with GetGroupMembersParam
-case class GroupIds(groupIds: Long*) extends FacebookParam("gids", groupIds.mkString(",")) with GetGroupsParam
-case class ProfileMarkup(markup: NodeSeq) extends FacebookParam("profile", markup) with SetFbmlParam
-case class ProfileActionMarkup(markup: NodeSeq) extends FacebookParam("profile_action", markup) with SetFbmlParam
-case class MobileProfileMarkup(markup: NodeSeq) extends FacebookParam("mobile_profile", markup) with SetFbmlParam
-case class Url(url: String) extends FacebookParam("url", url) with RefreshImageParam with RefreshRefParam
-case class RefHandle(handle: String) extends FacebookParam("handle", handle) with SetRefHandleParam
-case class FBML(markup: NodeSeq) extends FacebookParam("fbml", markup) with SetRefHandleParam
-case class Caption(caption: String) extends FacebookParam("caption", caption) with UploadPhotoParam
-
-case class TargetId(id:String) extends FacebookParam("target_id", id) with StreamPublishParam
-case class StreamMessage(data: String) extends FacebookParam("message", data) with StreamPublishParam
-case class StreamAttachment(data: String) extends FacebookParam("attachment", data) with StreamPublishParam
-case class StreamLinks(data: String) extends FacebookParam("action_links", data) with StreamPublishParam
-
-}
-}
-}
View
130 imaging/src/main/scala/net/liftweb/imaging/ImageHelpers.scala
@@ -1,130 +0,0 @@
-/*
- * Copyright 2010 WorldWide Conferencing, LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.liftweb {
-package imaging {
-
-import java.awt.{Graphics, RenderingHints, Transparency}
-import java.awt.geom.AffineTransform
-import java.awt.image.{AffineTransformOp, BufferedImage, ColorModel, IndexColorModel}
-
-/**
- * Helpers for manipulating images
- *
- * @author Ross M
- */
-object ImageHelpers {
-
- /**
- * Rendering hints set up for the highest quality rendering
- */
- val highQualityHints = {
- val h = new RenderingHints(null)
- h.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY)
- h.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY)
- h.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC)
- h.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
- h.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)
- h
- }
-
- /**
- * Resize an image of the given source type by the given ratios, properly handling GIF transparency, giving back the resized
- * image and the new image format type that should be used.
- *
- * The image type might change if the input type is an indexed color model, because it is a hard problem to choose an optimized
- * palette, and currently we don't. This function will return "png" as the new type in this case.
- *
- * If the input image is not using an indexed color model with transparency, then the target format and color model will be
- * identical to the source.
- */
- def resize(source: BufferedImage, inputFormat: String, dx: Double, dy: Double): (BufferedImage, String) = {
- var sourceColorModel = source.getColorModel
- val targetColorModel = source.getColorModel
- val standardColorModel = ColorModel.getRGBdefault
- val (targetWidth, targetHeight) = (((source.getWidth: Double) * dx).asInstanceOf[Int], ((source.getHeight: Double) * dy).asInstanceOf[Int])
-
- def resize(src: BufferedImage, dst: BufferedImage) {
- val g = dst.createGraphics
- try {
- g.setRenderingHints(highQualityHints)
- g.drawImage(src, new AffineTransformOp(AffineTransform.getScaleInstance(dx, dy), AffineTransformOp.TYPE_BICUBIC), 0, 0)
- } finally {
- g.dispose
- }
- }
-
- // GIF support in Java is very ornery. For GIFs we have to manually do the masking
- // on input, and then just punt on outputting GIFs and instead output PNGs.
- if (sourceColorModel.isInstanceOf[IndexColorModel] &&
- sourceColorModel.hasAlpha &&
- sourceColorModel.getTransparency == Transparency.BITMASK &&
- sourceColorModel.asInstanceOf[IndexColorModel].getTransparentPixel >= 0){
-
- val indexColorModel = sourceColorModel.asInstanceOf[IndexColorModel]
- val transparent = indexColorModel.getRGB(indexColorModel.getTransparentPixel)
- val masked = new BufferedImage(standardColorModel, standardColorModel.createCompatibleWritableRaster(source.getWidth, source.getHeight), standardColorModel.isAlphaPremultiplied, null)
- var w = masked.getWidth
- var h = masked.getHeight
- var y = 0
- val buf = new Array[Int](w)
-
- while (y < h) {
- source.getRGB(0, y, w, 1, buf, 0, 1)
- var x = 0
- while (x < w) {
- val c = buf(x)
- if (c == transparent) {
- buf(x) = 0
- }
- x += 1
- }
- masked.setRGB(0, y, w, 1, buf, 0, 1)
- y += 1
- }
-
- val resized = new BufferedImage(
- standardColorModel,
- standardColorModel.createCompatibleWritableRaster(targetWidth, targetHeight),
- standardColorModel.isAlphaPremultiplied, null)
-
- resize(masked, resized)
- (resized, "png")
- } else if (sourceColorModel.isInstanceOf[IndexColorModel]){
- // The input color model is indexed, and we know we won't be able
- // to generate a tolerable palette to make another indexed color model,
- // so use sRGB and upgrade to PNG.
- val resized = new BufferedImage(
- standardColorModel,
- standardColorModel.createCompatibleWritableRaster(targetWidth, targetHeight),
- standardColorModel.isAlphaPremultiplied, null)
-
- resize(source, resized)
- (resized, "png")
- } else {
- val resized = new BufferedImage(
- targetColorModel,
- targetColorModel.createCompatibleWritableRaster(targetWidth, targetHeight),
- targetColorModel.isAlphaPremultiplied, null)
-
- resize(source, resized)
- (resized, inputFormat)
- }
- }
-}
-
-}
-}
View
248 imaging/src/main/scala/net/liftweb/imaging/ImageResizer.scala
@@ -1,248 +0,0 @@
-/*
- * Copyright 2010-2011 WorldWide Conferencing, LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.liftweb
-package imaging
-
-
-import java.io.{InputStream,ByteArrayOutputStream,ByteArrayInputStream}
-import java.awt.{Graphics2D, Transparency, RenderingHints}
-import java.awt.image.BufferedImage
-import javax.imageio.{IIOImage, ImageIO, ImageWriteParam}
-
-import org.apache.sanselan.Sanselan
-import org.apache.sanselan.ImageFormat
-import org.apache.sanselan.formats.jpeg.JpegImageMetadata
-import org.apache.sanselan.formats.tiff.constants.TiffTagConstants
-
-import common.{Box, Full, Empty}
-import util.Helpers
-
-
-object ImageOutFormat extends Enumeration("png", "jpg", "gif", "bmp"){
- val png,jpeg,gif,bmp = Value
-}
-
-//Degrees are positive going clockwise (270 is same as -90)
-object ImageOrientation extends Enumeration(1) {
- val ok = Value(1, "OK")
- val mirrored = Value(2, "Mirror")
-
- val rotate180 = Value(3, "Rotate 180")
- val rotate180mirror = Value(4, "Rotate 180 Mirror")
-
- val rotate270mirror = Value(5, "Rotate 270 Mirror")
- val rotate270 = Value(6, "Rotate 270")
-
- val rotate90mirror = Value(7, "Rotate 90 Mirror")
- val rotate90 = Value(8, "Rotate 90")
-
- def valueOf(v: Int):Box[Value] = {
- if (v > 0 && v <= 8) Full(apply(v)) else Empty
- }
-}
-
-case class ImageWithMetaData(image:BufferedImage, orientation:Box[ImageOrientation.Value], format:ImageOutFormat.Value)
-
-object ImageResizer extends ImageResizer(Map(RenderingHints.KEY_INTERPOLATION -> RenderingHints.VALUE_INTERPOLATION_BILINEAR), true)
-
-class ImageResizer(renderingHintsMap:Map[java.awt.RenderingHints.Key,Any], multiStepDownScale:Boolean) {
-
- val renderingHints = {
- val h = new RenderingHints(null)
- renderingHintsMap.foreach(p => h.put(p._1, p._2))
- h
- }
-
- def getOrientation(imageBytes:Array[Byte]):Box[ImageOrientation.Value] = Helpers.tryo {
- Sanselan.getMetadata(imageBytes) match {
- case metaJpg:JpegImageMetadata =>
- val exifValue = metaJpg.findEXIFValue(TiffTagConstants.TIFF_TAG_ORIENTATION)
- if (exifValue != null) ImageOrientation.valueOf(exifValue.getIntValue) else Empty
- case _ => Empty
- }
- }.flatMap(x=>x)
-
- def getImageFromStream(is:java.io.InputStream):ImageWithMetaData = {
- val imageBytes = Helpers.readWholeStream(is)
- val orientation = getOrientation(imageBytes)
- val format = Sanselan.guessFormat(imageBytes) match {
- case ImageFormat.IMAGE_FORMAT_JPEG => ImageOutFormat.jpeg
- case ImageFormat.IMAGE_FORMAT_GIF => ImageOutFormat.gif
- case ImageFormat.IMAGE_FORMAT_PNG => ImageOutFormat.png
- case ImageFormat.IMAGE_FORMAT_BMP => ImageOutFormat.bmp
- case f => throw new RuntimeException("Unsupported image format: " + f)
- }
- ImageWithMetaData(ImageIO.read(new java.io.ByteArrayInputStream(imageBytes)), orientation, format)
- }
-
- def imageToStream(format:ImageOutFormat.Value, image:BufferedImage):InputStream = {
- new ByteArrayInputStream(imageToBytes(format, image, 0.8f))
- }
-
- def imageToBytes(format: ImageOutFormat.Value, image: BufferedImage, jpegQuality: Float):Array[Byte] = {
- val outputStream = new ByteArrayOutputStream()
- format match {
- case ImageOutFormat.jpeg =>
- val imageWriter = ImageIO.getImageWritersByFormatName("jpeg").next()
- val iwp = imageWriter.getDefaultWriteParam()
- iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT)
- iwp.setCompressionQuality(jpegQuality)
- imageWriter.setOutput(ImageIO.createImageOutputStream(outputStream))
- imageWriter.write(null, new IIOImage(image, null, null), iwp)
- imageWriter.dispose()
- case _ =>
- ImageIO.write(image, format.toString, outputStream)
- }
- outputStream.toByteArray()
- }
-
- /**
- * Resize to a square
- * Will preserve the aspect ratio of the original and than center crop the larger dimension.
- * A image of (200w,240h) squared to (100) will first resize to (100w,120h) and then take then crop
- * 10 pixels from the top and bottom of the image to produce (100w,100h)
- */
- def square(orientation:Box[ImageOrientation.Value], originalImage:BufferedImage, max:Int):BufferedImage = {
- val image = {
- val height = originalImage.getHeight
- val width = originalImage.getWidth
- val ratio:Double = width.doubleValue/height
-
- //set smaller dimension to the max
- val (scaledWidth, scaledHeight) = if (width < height) {
- (max,(max.doubleValue/ratio).intValue)
- } else {
- ((max.doubleValue*ratio).intValue, max)
- }
- resize(orientation, originalImage, scaledWidth, scaledHeight)
- }
-
- def halfDiff(dim:Int):Int = (dim-max)/2
-
- if (image.getHeight > max) {
- image.getSubimage(0,halfDiff(image.getHeight), image.getWidth, max)
- } else if (image.getWidth > max) {
- image.getSubimage(halfDiff(image.getWidth),0, max, image.getHeight)
- } else image
- }
-
-
- def scaledMaxDim(width:Int, height:Int , maxWidth:Int, maxHeight:Int):(Int,Int) = {
- val ratio:Double = width.doubleValue/height
-
- val scaleW = (maxWidth, (maxWidth.doubleValue/ratio).intValue)
- val scaleH = ((maxHeight.doubleValue*ratio).intValue,maxHeight)
-
- if (width > height && scaleW._2 <= maxHeight)
- scaleW
- else if (scaleH._1 <= maxWidth)
- scaleH
- else scaleW
- }
-
- /**
- * Resize to maximum dimension preserving the aspect ratio. This is basically equivalent to what you would expect by setting
- * "max-width" and "max-height" CSS attributes but will scale up an image if necessary
- */
- def max(orientation:Box[ImageOrientation.Value],originalImage:BufferedImage, maxWidth:Int, maxHeight:Int):BufferedImage = {
- val (scaledWidth, scaledHeight) = scaledMaxDim(originalImage.getWidth, originalImage.getHeight, maxWidth, maxHeight)
- resize(orientation, originalImage, scaledWidth, scaledHeight)
- }
-
- /**
- * Algorithm adapted from example in Filthy Rich Clients http://filthyrichclients.org/
- * Resize an image and account of its orientation. This will not preserve aspect ratio.
- */
- def resize(orientation:Box[ImageOrientation.Value], img:BufferedImage, targetWidth:Int, targetHeight:Int): BufferedImage = {
- val imgType = if (img.getTransparency() == Transparency.OPAQUE) BufferedImage.TYPE_INT_RGB else BufferedImage.TYPE_INT_ARGB
- var ret = img
- var scratchImage:BufferedImage = null
- var g2:Graphics2D = null
- var w = img.getWidth
- var h = img.getHeight
- var prevW = ret.getWidth
- var prevH = ret.getHeight
-
- val isTranslucent:Boolean = img.getTransparency != Transparency.OPAQUE
-
- //If we're resizing down by more than a factor of two, resize in multiple steps to preserve image quality
- do {
- if (w > targetWidth && multiStepDownScale) {
- w /= 2
- if (w < targetWidth) {
- w = targetWidth
- }
- } else w = targetWidth
-
- if (h > targetHeight && multiStepDownScale) {
- h /= 2
- if (h < targetHeight) {
- h = targetHeight
- }
- } else h = targetHeight
-
- if (scratchImage == null || isTranslucent) {
- scratchImage = new BufferedImage(w, h, imgType);
- g2 = scratchImage.createGraphics
- }
- g2.setRenderingHints(renderingHints)
- g2.drawImage(ret, 0, 0, w, h, 0, 0, prevW, prevH, null)
- prevW = w
- prevH = h
-
- ret = scratchImage
- } while (w != targetWidth || h != targetHeight)
-
- if (g2 != null) {
- g2.dispose
- }
-
- // If we used a scratch buffer that is larger than our target size,
- // create an image of the right size and copy the results into it
- // If there is an orientation value other than the default, rotate the image appropriately
- if (targetWidth != ret.getWidth || targetHeight != ret.getHeight || orientation.map(_ != ImageOrientation.ok).getOrElse(false)) {
-
- val (tW, tH, rotFunc) = orientation match {
- case Full(ImageOrientation.rotate180) =>
- (targetWidth, targetHeight, (g2:Graphics2D) => {
- g2.rotate(math.Pi)
- g2.translate(-targetWidth, -targetHeight)
- })
- case Full(ImageOrientation.rotate270) =>
- (targetHeight, targetWidth, (g2:Graphics2D) => {
- g2.rotate(math.Pi/2)
- g2.translate(0, -targetHeight)
- })
- case Full(ImageOrientation.rotate90) =>
- (targetHeight, targetWidth, (g2:Graphics2D) => {
- g2.rotate(-math.Pi/2)
- g2.translate(-targetWidth, 0)
- })
- case _ => (targetWidth, targetHeight, (g2:Graphics2D) => {})
- }
- scratchImage = new BufferedImage(tW, tH, imgType)
- g2 = scratchImage.createGraphics
- rotFunc(g2)
- g2.drawImage(ret, 0, 0, null)
- g2.dispose
- ret = scratchImage
- }
-
- ret
- }
-
-}
View
41 imaging/src/test/scala/net/liftweb/imaging/ImageResizerSpec.scala
@@ -1,41 +0,0 @@
-/*
- * Copyright 2010-2011 WorldWide Conferencing, LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.liftweb
-package imaging
-
-
-import org.specs.Specification
-
-
-object ImageResizerSpec extends Specification {
-
- "ImageResizer scaledMaxDim function" should {
- "be invariant" in {
- val range = (1 to 10)
- for {w <- range
- h <- range
- maxW <- range
- maxH <- range}{
- val (scaledWidth, scaledHeight) = ImageResizer.scaledMaxDim(w,h, maxW,maxH)
-
- (scaledWidth) must beLessThanOrEqualTo(maxW)
- (scaledHeight) must beLessThanOrEqualTo(maxH)
- (scaledWidth == maxW || scaledHeight == maxH) must beTrue
- }
- }
- }
-}
View
76 jta/README.textile
@@ -1,76 +0,0 @@
-h1. Lift JTA Transaction API
-
-The semantics are the same as used in the EJB spec. E.g. Required, RequiresNew, Mandatory, Supports, Never. All these are exposed as monadic objects and high-order functions in the TransactionContext object.
-
-The implementation is hooked into the Lift's JPA implementation.
-Check the ScalaDoc (or the source) for the documentation on usage, semantics etc.
-
-There are two versions of the API, one monadic and one using high-order functions.
-
-h3. Monadic API
-
-<pre>
- for {
- ctx <- TransactionContext.Required
- entity <- updatedEntities
- if !ctx.isRollbackOnly
- } {
- // transactional stuff
- ctx.getEntityManager.merge(entity)
- }
-</pre>
-
-<pre>
-val users = for {
- ctx <- TransactionContext.RequiresNew
- name <- userNames
- } yield {
- // transactional stuff
- val query = ctx.getEntityManager.createNamedQuery("findUserByName")
- query.setParameter("userName", name)
- query.getSingleResult
- }
-</pre>
-
-h3. High-order functions API
-
-<pre>
-TransactionContext.withTxRequired {
- ... // REQUIRED semantics
-
- TransactionContext.withTxRequiresNew {
- ... // REQUIRES_NEW semantics
- }
-}
-</pre>
-
-h2. Configuration
-
-The configuration is done in the persistence.xml file + the jta.properties. Sample configuration files can be found in the src/main/resources directory.
-Here are the essential configuration options in the JPA persistence.xml file:
-
-<pre>
-<persistence xmlns="http://java.sun.com/xml/ns/persistence"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
- version="1.0">
- <persistence-unit name="LiftPersistenceUnit" transaction-type="JTA">
- <provider>org.hibernate.ejb.HibernatePersistence</provider>
-
- <mapping-file>...</mapping-file>
- <class>...</class>
-
- <properties>
- <property name="hibernate.transaction.manager_lookup_class"
- value="net.liftweb.transaction.hibernate.LiftTransactionManagerLookup" />
- </properties>
- </persistence-unit>
-</persistence>
-</pre>
-
-h2. TODOs
-
-Currently it is hard-coded to use the Atomikos Transaction library and the Hibernate JPA implementation.
-This will have to be configurable + some other options as well. See the TODOs in the code.
-
-
View
56 jta/src/main/resources/jta.properties
@@ -1,56 +0,0 @@
-# ==================================================
-# === ATOMIKOS TRANSACTION MANAGER CONFIGURATION ===
-# ==================================================
-
-#Required: factory implementation class of the transaction core.
-com.atomikos.icatch.service=com.atomikos.icatch.standalone.UserTransactionServiceFactory
-
-com.atomikos.icatch.lock_logs=false
-
-com.atomikos.icatch.force_shutdown_on_vm_exit=true
-
-#Set base name of log file this name will be used as the first part of the system-generated log file name
-com.atomikos.icatch.log_base_name = tmlog
-
-#Set base name of file where messages are output (also known as the 'console file').
-com.atomikos.icatch.console_file_name = tm.out
-
-#Set output directory where console file and other files are to be put make sure this directory exists!
-com.atomikos.icatch.output_dir = tm/jta
-
-#Set directory of log files; make sure this directory exists!
-com.atomikos.icatch.log_base_dir = tm/log
-
-#Set the max timeout (in milliseconds) for local transactions
-com.atomikos.icatch.max_timeout = 30000000
-
-#The globally unique name of this transaction manager process override this value with a globally unique name
-com.atomikos.icatch.tm_unique_name = lift_tm
-
-#Set this to WARN, INFO or DEBUG to control the granularity of output to the console file.
-com.atomikos.icatch.console_log_level=DEBUG
-
-#Do you want transaction logging to be enabled or not? If set to false, then no logging overhead will be done at the risk of losing data after restart or crash.
-com.atomikos.icatch.enable_logging=false
-
-#Should two-phase commit be done in (multi-)threaded mode or not? NOTE: threads are reused on JDK 1.5 or higher. For JDK 1.4, thread reuse is enabled as soon as the concurrent backport is in the classpath.
-com.atomikos.icatch.threaded_2pc=true
-
-#Do we want to use parallel subtransactions? JTA's default is NO for J2EE compatibility
-#com.atomikos.icatch.serial_jta_transactions=true
-
-#If you want to do explicit resource registration then you need to set this value to false.
-#com.atomikos.icatch.automatic_resource_registration=true
-
-#Set the max number of active local transactions or -1 for unlimited.
-#com.atomikos.icatch.max_actives = 50
-
-#Size limit (in bytes) for the console file; negative means unlimited.
-#com.atomikos.icatch.console_file_limit=-1
-
-#For size-limited console files, this option specifies a number of rotating files to maintain.
-#com.atomikos.icatch.console_file_count=1
-
-#Set the number of log writes between checkpoints
-#com.atomikos.icatch.checkpoint_interval=500
-
View
16 jta/src/main/resources/persistence.xml
@@ -1,16 +0,0 @@
-<persistence xmlns="http://java.sun.com/xml/ns/persistence"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
- version="1.0">
- <persistence-unit name="LiftPersistenceUnit" transaction-type="JTA">
- <provider>org.hibernate.ejb.HibernatePersistence</provider>
-
- <mapping-file></mapping-file>
- <class></class>
-
- <properties>
- <property name="hibernate.transaction.manager_lookup_class"
- value="net.liftweb.transaction.hibernate.LiftTransactionManagerLookup" />
- </properties>
- </persistence-unit>
-</persistence>
View
64 jta/src/main/scala/net/liftweb/transaction/EntityManagerSynchronization.scala
@@ -1,64 +0,0 @@
-/*
- * Copyright 2009-2011 WorldWide Conferencing, LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.liftweb
-package transaction
-
-import net.liftweb.common.Loggable
-
-import javax.transaction.{ TransactionManager, Status, Synchronization, SystemException}
-import javax.persistence.EntityManager
-
-
-/**
- * EntityManager JTA synchronization class.
- * <p>
- * Registered in method: [joinTransaction].
- *
- * @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
- */
-class EntityManagerSynchronization(
- val em: EntityManager,
- val tm: TransactionManager,
- val closeAtTxCompletion: Boolean)
- extends Synchronization with Loggable {
-
- def beforeCompletion = {
- try {
- val status = tm.getStatus
- if (status != Status.STATUS_ROLLEDBACK &&
- status != Status.STATUS_ROLLING_BACK &&
- status != Status.STATUS_MARKED_ROLLBACK) {
- logger.debug("Flushing EntityManager...")
- em.flush // flush EntityManager on success
- }
- } catch {
- case e: SystemException => throw new RuntimeException(e)
- }
- }
-
- def afterCompletion(status: Int) = {
- val status = tm.getStatus
- if (closeAtTxCompletion) {
- em.close
- }
- if (status == Status.STATUS_ROLLEDBACK ||
- status == Status.STATUS_ROLLING_BACK ||
- status == Status.STATUS_MARKED_ROLLBACK) {
- TransactionContext.closeEntityManager // destroy EntityManager on rollback
- }
- }
-}
View
234 jta/src/main/scala/net/liftweb/transaction/TransactionContext.scala
@@ -1,234 +0,0 @@
-/*
- * Copyright 2009-2011 WorldWide Conferencing, LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.liftweb
-package transaction
-
-import javax.persistence.EntityManager
-import javax.transaction.{Transaction, Status, TransactionManager}
-
-import org.scala_libs.jpa.{ScalaEntityManager, ScalaEMFactory}
-
-import common.Loggable
-
-
-/**
- * Base monad for the transaction monad implementations.
- *
- * @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
- */
-trait TransactionMonad {
-
- // -----------------------------
- // Monadic definitions
- // -----------------------------
-
- def map[T](f: TransactionMonad => T): T
- def flatMap[T](f: TransactionMonad => T): T
- def foreach(f: TransactionMonad => Unit): Unit
- def filter(f: TransactionMonad => Boolean): TransactionMonad =
- if (f(this)) this else TransactionContext.NoOpTransactionMonad
-
- // -----------------------------
- // JTA Transaction definitions
- // -----------------------------
-
- /**
- * Returns the current Transaction.
- */
- def getTransaction: Transaction = TransactionContext.getTransactionManager.getTransaction
-
- /**
- * Marks the current transaction as doomed.
- */
- def setRollbackOnly = TransactionContext.setRollbackOnly
-
- /**
- * Marks the current transaction as doomed.
- */
- def doom = TransactionContext.setRollbackOnly
-
- /**
- * Checks if the current transaction is doomed.
- */
- def isRollbackOnly = TransactionContext.isRollbackOnly
-
- /**
- * Checks that the current transaction is NOT doomed.
- */
- def isNotDoomed = !TransactionContext.isRollbackOnly
-
- // -----------------------------
- // JPA EntityManager definitions
- // -----------------------------
-
- /**
- * Returns the current EntityManager.
- */
- def getEntityManager: EntityManager = TransactionContext.getEntityManager
-
- /**
- * Checks if an EntityManager exists in current context.
- */
- //def hasEntityManager: Boolean = TransactionContext.hasEntityManager
-
- /**
- * Closes and removes the current EntityManager.
- * <p/>
- * IMPORTANT: This method must always be used to close the EntityManager, never use em.close directly.
- */
- def closeEntityManager = TransactionContext.closeEntityManager
-}
-
-/**
- * Manages a thread-local stack of TransactionContexts.
- * <p/>
- * Choose TransactionService implementation by implicit definition of the implementation of choice,
- * e.g. <code>implicit val txService = TransactionServices.AtomikosTransactionService</code>.
- * <p/>
- * Example usage 1:
- * <pre>
- * for {
- * ctx <- TransactionContext.Required
- * entity <- updatedEntities
- * if !ctx.isRollbackOnly
- * } {
- * // transactional stuff
- * ctx.getEntityManager.merge(entity)
- * }
- * </pre>
- * Example usage 2:
- * <pre>
- * val users = for {
- * ctx <- TransactionContext.Required
- * name <- userNames
- * } yield {
- * // transactional stuff
- * val query = ctx.getEntityManager.createNamedQuery("findUserByName")
- * query.setParameter("userName", name)
- * query.getSingleResult
- * }
- * </pre>
- *
- * @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
- */
-object TransactionContext extends TransactionProtocol with Loggable {
- // FIXME: make configurable
- private implicit val defaultTransactionService = atomikos.AtomikosTransactionService
-
- private[TransactionContext] val stack = new scala.util.DynamicVariable(new TransactionContext)
-
- object Required extends TransactionMonad {
- def map[T](f: TransactionMonad => T): T = withTxRequired { f(this) }
- def flatMap[T](f: TransactionMonad => T): T = withTxRequired { f(this) }
- def foreach(f: TransactionMonad => Unit): Unit = withTxRequired { f(this) }
- }
-
- object RequiresNew extends TransactionMonad {
- def map[T](f: TransactionMonad => T): T = withTxRequiresNew { f(this) }
- def flatMap[T](f: TransactionMonad => T): T = withTxRequiresNew { f(this) }
- def foreach(f: TransactionMonad => Unit): Unit = withTxRequiresNew { f(this) }
- }
-
- object Supports extends TransactionMonad {
- def map[T](f: TransactionMonad => T): T = withTxSupports { f(this) }
- def flatMap[T](f: TransactionMonad => T): T = withTxSupports { f(this) }
- def foreach(f: TransactionMonad => Unit): Unit = withTxSupports { f(this) }
- }
-
- object Mandatory extends TransactionMonad {
- def map[T](f: TransactionMonad => T): T = withTxMandatory { f(this) }
- def flatMap[T](f: TransactionMonad => T): T = withTxMandatory { f(this) }
- def foreach(f: TransactionMonad => Unit): Unit = withTxMandatory { f(this) }
- }
-
- object Never extends TransactionMonad {
- def map[T](f: TransactionMonad => T): T = withTxNever { f(this) }
- def flatMap[T](f: TransactionMonad => T): T = withTxNever { f(this) }
- def foreach(f: TransactionMonad => Unit): Unit = withTxNever { f(this) }
- }
-
- object NoOpTransactionMonad extends TransactionMonad {
- def map[T](f: TransactionMonad => T): T = f(this)
- def flatMap[T](f: TransactionMonad => T): T = f(this)
- def foreach(f: TransactionMonad => Unit): Unit = f(this)
- override def filter(f: TransactionMonad => Boolean): TransactionMonad = this
- }
-
- private[transaction] def setRollbackOnly = current.setRollbackOnly
-
- private[transaction] def isRollbackOnly = current.isRollbackOnly
-
- private[transaction] def getTransactionManager: TransactionManager = current.getTransactionManager
-
- private[transaction] def getTransaction: Transaction = current.getTransactionManager.getTransaction
-
- private[transaction] def getEntityManager: EntityManager = current.getEntityManager
-
- private[transaction] def closeEntityManager = current.closeEntityManager
-
- private[this] def current = stack.value
-
- /**
- * Continues with the invocation defined in 'body' with the brand new context define in 'newCtx', the old
- * one is put on the stack and will automatically come back in scope when the method exits.
- * <p/>
- * Suspends and resumes the current JTA transaction.
- */
- private[transaction] def withNewContext[T](body: => T): T = {
- val suspendedTx: Option[Transaction] =
- if (isInExistingTransaction(getTransactionManager)) {
- logger.debug("Suspending TX")
- Some(getTransactionManager.suspend)
- } else None
- val result = stack.withValue(new TransactionContext) { body }
- if (suspendedTx.isDefined) {
- logger.debug("Resuming TX")
- getTransactionManager.resume(suspendedTx.get)
- }
- result
- }
-}
-
-/**
- * Transaction context, holds the EntityManager and the TransactionManager.
- *
- * @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
- */
-class TransactionContext(private implicit val transactionService: TransactionService)
- extends ScalaEntityManager with ScalaEMFactory {
-
- val em: EntityManager = transactionService.entityManagerFactory.createEntityManager
- val tm: TransactionManager = transactionService.transactionManager
-
- private def setRollbackOnly = tm.setRollbackOnly
-
- protected def getUnitName = "N/A"
-
- private def isRollbackOnly: Boolean = tm.getStatus == Status.STATUS_MARKED_ROLLBACK
-
- private def getTransactionManager: TransactionManager = tm
-
- private def getEntityManager: EntityManager = em
-
- private def closeEntityManager = em.close
-
- // ---------------------------------
- // To make ScalaEMFactory happy
- val factory = this
- def openEM: javax.persistence.EntityManager = em
- def closeEM(e: javax.persistence.EntityManager) = closeEntityManager
-}
View
239 jta/src/main/scala/net/liftweb/transaction/TransactionService.scala
@@ -1,239 +0,0 @@
-/*
- * Copyright 2009-2011 WorldWide Conferencing, LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.liftweb
-package transaction
-
-import javax.transaction.{Transaction, TransactionManager, Status, SystemException, TransactionRequiredException}
-import javax.persistence.{Persistence, EntityManagerFactory, NonUniqueResultException, NoResultException}
-
-import common.Logger
-
-
-/**
- * JTA Transaction service.
- *
- * @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
- */
-trait TransactionService {
- def transactionManager: TransactionManager
- def entityManagerFactory: EntityManagerFactory
-}
-
-/**
- * JPA Entity Manager service.
- *
- * @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
- */
-trait EntityManagerService {
- // TODO: make configurable?
- lazy val JPA_PERSISTENT_UNIT = "LiftPersistenceUnit"
- lazy val entityManagerFactory = Persistence.createEntityManagerFactory(JPA_PERSISTENT_UNIT)
-}
-
-/**
- * <p>
- * Trait that implements a JTA transaction service that obeys the transaction semantics defined
- * in the transaction attribute types for the transacted methods according to the EJB 3 draft specification.
- * The aspect handles UserTransaction, TransactionManager instance variable injection thru @javax.ejb.Inject
- * (name subject to change as per EJB 3 spec) and method transaction levels thru @javax.ejb.TransactionAttribute.
- * </p>
- *
- * <p>
- * This trait should be inherited to implement the getTransactionManager() method that should return a concrete
- * javax.transaction.TransactionManager implementation (from JNDI lookup etc).
- * </p>
- * <p>
- * <h3>Transaction attribute semantics</h3>
- * (From http://www.kevinboone.com/ejb-transactions.html)
- * </p>
- * <p>
- * <h4>Required</h4>
- * 'Required' is probably the best choice (at least initially) for an EJB method that will need to be transactional. In this case, if the method's caller is already part of a transaction, then the EJB method does not create a new transaction, but continues in the same transaction as its caller. If the caller is not in a transaction, then a new transaction is created for the EJB method. If something happens in the EJB that means that a rollback is required, then the extent of the rollback will include everything done in the EJB method, whatever the condition of the caller. If the caller was in a transaction, then everything done by the caller will be rolled back as well. Thus the 'required' attribute ensures that any work done by the EJB will be rolled back if necessary, and if the caller requires a rollback that too will be rolled back.
- * </p>
- * <p>
- * <h4>RequiresNew</h4>
- * 'RequiresNew' will be appropriate if you want to ensure that the EJB method is rolled back if necessary, but you don't want the rollback to propogate back to the caller. This attribute results in the creation of a new transaction for the method, regardless of the transactional state of the caller. If the caller was operating in a transaction, then its transaction is suspended until the EJB method completes. Because a new transaction is always created, there may be a slight performance penalty if this attribute is over-used.
- * </p>
- * <p>
- * <h4>Mandatory</h4>
- * With the 'mandatory' attribute, the EJB method will not even start unless its caller is in a transaction. It will throw a <code>TransactionRequiredException</code> instead. If the method does start, then it will become part of the transaction of the caller. So if the EJB method signals a failure, the caller will be rolled back as well as the EJB.
- * </p>
- * <p>
- * <h4>Supports</h4>
- * With this attribute, the EJB method does not care about the transactional context of its caller. If the caller is part of a transaction, then the EJB method will be part of the same transaction. If the EJB method fails, the transaction will roll back. If the caller is not part of a transaction, then the EJB method will still operate, but a failure will not cause anything to roll back. 'Supports' is probably the attribute that leads to the fastest method call (as there is no transactional overhead), but it can lead to unpredicatable results. If you want a method to be isolated from transactions, that is, to have no effect on the transaction of its caller, then use 'NotSupported' instead.
- * </p>
- * <p>
- * <h4>NotSupported</h4>
- * With the 'NotSupported' attribute, the EJB method will never take part in a transaction. If the caller is part of a transaction, then the caller's transaction is suspended. If the EJB method fails, there will be no effect on the caller's transaction, and no rollback will occur. Use this method if you want to ensure that the EJB method will not cause a rollback in its caller. This is appropriate if, for example, the method does something non-essential, such as logging a message. It would not be helpful if the failure of this operation caused a transaction rollback.
- * </p>
- * <p>
- * <h4>Never</h4>
- * The 'NotSupported'' attribute will ensure that the EJB method is never called by a transactional caller. Any attempt to do so will result in a <code>RemoteException</code> being thrown. This attribute is probably less useful than `NotSupported', in that NotSupported will assure that the caller's transaction is never affected by the EJB method (just as `Never' does), but will allow a call from a transactional caller if necessary.
- * </p>
- *
- * @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
- */
-trait TransactionProtocol {
- private val logger = Logger(classOf[TransactionProtocol])
-
- /**
- * Wraps body in a transaction with REQUIRED semantics.
- * <p/>
- * Creates a new transaction if no transaction is active in scope, else joins the outer transaction.
- */
- def withTxRequired[T](body: => T): T = {
- val tm = TransactionContext.getTransactionManager
- if (!isInExistingTransaction(tm)) {
- tm.begin
- try {
- joinTransaction
- body
- } catch {
- case e: Exception => handleException(tm, e)
- } finally {
- commitOrRollBack(tm)
- }
- } else body
- }
-
- /**
- * Wraps body in a transaction with REQUIRES_NEW semantics.
- * <p/>
- * Suspends existing transaction, starts a new transaction, invokes body,
- * commits or rollbacks new transaction, finally resumes previous transaction.
- */
- def withTxRequiresNew[T](body: => T): T = TransactionContext.withNewContext {
- val tm = TransactionContext.getTransactionManager
- tm.begin
- try {
- joinTransaction
- body
- } catch {
- case e: Exception => handleException(tm, e)
- } finally {
- commitOrRollBack(tm)
- }
- }
-
- /**
- * Wraps body in a transaction with NOT_SUPPORTED semantics.
- * <p/>
- * Suspends existing transaction, invokes body, resumes transaction.
- */
- def withTxNotSupported[T](body: => T): T = TransactionContext.withNewContext {
- body
- }
-
- /**
- * Wraps body in a transaction with SUPPORTS semantics.
- * <p/>
- * Basicalla a No-op.
- */
- def withTxSupports[T](body: => T): T = {
- // attach to current if exists else skip -> do nothing
- body
- }
-
- /**
- * Wraps body in a transaction with MANDATORY semantics.
- * <p/>
- * Throws a TransactionRequiredException if there is no transaction active in scope.
- */
- def withTxMandatory[T](body: => T): T = {
- if (!isInExistingTransaction(TransactionContext.getTransactionManager)) throw new TransactionRequiredException("No active TX at method with TX type set to MANDATORY")
- body
- }
-
- /**
- * Wraps body in a transaction with NEVER semantics.
- * <p/>
- * Throws a SystemException in case of an existing transaction in scope.
- */
- def withTxNever[T](body: => T): T = {
- if (isInExistingTransaction(TransactionContext.getTransactionManager)) throw new SystemException("Detected active TX at method with TX type set to NEVER")
- body
- }
-
- protected def handleException(tm: TransactionManager, e: Exception) = {
- if (isInExistingTransaction(tm)) {
- // Do not roll back in case of NoResultException or NonUniqueResultException
- if (!e.isInstanceOf[NoResultException] &&
- !e.isInstanceOf[NonUniqueResultException]) {
- logger.debug("Setting TX to ROLLBACK_ONLY, due to: " + e)
- tm.setRollbackOnly
- }
- }
- throw e
- }
-
- protected def commitOrRollBack(tm: TransactionManager) = {
- if (isInExistingTransaction(tm)) {
- if (isRollbackOnly(tm)) {
- logger.debug("Rolling back TX marked as ROLLBACK_ONLY")
- tm.rollback
- } else {
- logger.debug("Committing TX")
- tm.commit
- }
- }
- }
-
- // ---------------------------
- // Helper methods
- // ---------------------------
-
- /**
- * Checks if a transaction is an existing transaction.
- *
- * @param tm the transaction manager
- * @return boolean
- */
- protected def isInExistingTransaction(tm: TransactionManager): Boolean = tm.getStatus != Status.STATUS_NO_TRANSACTION
-
- /**
- * Checks if current transaction is set to rollback only.
- *
- * @param tm the transaction manager
- * @return boolean
- */
- protected def isRollbackOnly(tm: TransactionManager): Boolean = tm.getStatus == Status.STATUS_MARKED_ROLLBACK
-
- /**
- * Join JTA transaction.
- */
- private def joinTransaction = {
- val em = TransactionContext.getEntityManager
- val tm = TransactionContext.getTransactionManager
- tm.getTransaction.registerSynchronization(new EntityManagerSynchronization(em, tm, false))
- em.joinTransaction // join JTA transaction
- }
-
- /**
- * A ThreadLocal variable where to store suspended TX and enable pay as you go
- * before advice - after advice data sharing in a specific case of requiresNew TX
- */
- private val suspendedTx = new ThreadLocal[Transaction] {
- override def initialValue = null
- }
-
- private def storeInThreadLocal(tx: Transaction) = suspendedTx.set(tx)
-
- private def fetchFromThreadLocal: Option[Transaction] = {
- if (suspendedTx != null && suspendedTx.get() != null) Some(suspendedTx.get.asInstanceOf[Transaction])
- else None
- }
-}
View
57 jta/src/main/scala/net/liftweb/transaction/atomikos/AtomikosTransactionService.scala
@@ -1,57 +0,0 @@
-/*
- * Copyright 2009-2010 WorldWide Conferencing, LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of th