XRP Valuation

UPDATE -  November 11, 2017:
I NO LONGER AGREE WITH THE BELOW ANALYSIS.
I have updated my thoughts and valuation in the following note:
 http://cryptoizzy.blogspot.com/2017/11/goodbye-to-ripple.html

I am leaving this note here, but please take this warning and review my new piece.
Best,
Izzy






XRP/RIPPLE VALUATION – By Ihsotas Otomakan (IzzyOtto)


Introduction
I hope you find my thought processes interesting and helpful in your exploration of cryptos.

Please be aware that I’m neither giving investment advice nor suggesting anyone buy or sell anything. I’m simply sharing my personal assessment process for determining value.

The main difficulty in arriving at a valuation is dealing with uncertainty. I have striven to be clear about my assumptions and estimates, but I have no doubt that even if I am proven largely correct over the course of time, many of the details to my analysis will be changed and refined. If you have a particular question or response to my methodology, I invite you to contact me at izzyotomakan@gmail.com. I’ll do my best to respond, and if appropriate, may post edits/updates to this analysis.

I also have additional thoughts on cryptos that I plan on sharing. If you'd like to be kept up on these, please either follow this blog or just let me know via email. Thanks.

Best,
Izzy

On Cryptocurrency Valuation Methodologies
The exercise of applying traditional asset valuation metrics to a cryptocurrency is considered by many as lying somewhere between unwieldy and impossible. Modern financial and portfolio theories generally view asset valuation as being an exercise in determining the present value of cash flow streams which may be generated in the future. As cryptocurrencies have no innate cash-flow generating ability, this approach quickly hits a dead end.
Trying to approach cryptocurrencies from the perspective of traditional currencies (ie, USD, GBP, EUR) similarly falls short. All extant global currencies are intimately tied to the economic, political and legal structures of a sponsoring country (or group of countries). Cryptocurrencies, existing independently of nation-state sponsors, lack any of the metrics that would be appropriate for such an exercise.
As a consequence of the inapplicability of these traditional approaches, any sound and reasoned cryptocurrency valuation must employ novel methodologies and perspectives. My endeavor in this analysis is to provide just such a different framework, which if successful will appear both rational and perhaps even obvious in hindsight.[1]In any case, though I will provide data where both relevant and available, I will largely rely upon a series of logical steps which if followed to conclusion will yield what I believe to be a valuation floor for Ripple. Please note that this analysis is only meant to describe a valuation floor, that is a minimum functional value according to a singular approach. It is my opinion that when other approaches are applied to cryptocurrency valuation (including, but not limited to Ripple), the ultimate valuation may be substantially higher than that which we will arrive at in this report. Nevertheless, while I save that fuller approach for a future analysis to be shared, I am pleased to be able to represent that the (more limited) valuation approach which I present here still demonstrates substantial upside versus the current trading levels of Ripple coins.

What makes Ripple a unique candidate for this valuation analysis?
To answer this question we must first consider the proposition that most crypto-coins lack significant value outside of their use as money. This may sound like an obvious or even foolish statement at first glance, but it’s a necessary starting point. When we realize that even this value is dependent on the size of the economic community which agrees that ‘it is money’ (both in theory and practice), we quickly realize that in this regard most crypto-coins are currently at a significant disadvantage relative to state-sponsored currencies.
A state-sponsored currency almost definitionally has a significant economic community that agrees ‘it is money’. This occurs by virtue of the fact that the state sponsor declares their currency to be ‘legal tender’ – viewed in the eyes of their courts (and tax authorities) as an acceptable means to satisfy economic obligations[2]. So long as individuals accept the government’s rule of law in a country, they also implicitly become members of the economic community which accepts that currency as money.
Many proponents of Bitcoin (and cryptocurrencies in general) argue that in time, the size of the community which accepts cryptos ‘as money’ will grow, irrespective of legal tender recognition. This may ultimately be so, but for current valuation purposes yields ill-defined parameters for assessment. As such, we may ask another question: Is there a basis outside of use ‘as money’ which may be used to establish a valuation framework for a cryptocurrency? The short answer to this question is yes – and it lies in what I refer to as functional utility (a fancy way of saying its used for some purpose).[3]
Many cryptocurrencies doexhibit some functional utility outside of their use as traditional money. For example, they may serve as means and methods of crowd-funding investment projects, rewarding social community behavior, or facilitating complex contractual arrangements (more on this shortly). However, while some of these uses may ultimately result in significant functional-utility value, the vast majority of cryptos currently lack a clear pathway to realize this value – much less point to a valuation that exceeds current trading levels. And this, is where Ripple is different.
Ripple is relatively unique amongst cryptocurrencies in that it:
a)     Has a clearly quantifiable functional-utility value apart from any wider general acceptance as ‘money’, AND
b)     That functional-utility valuation appears to be significantly higher than current trading values.

Ripple and The Cross Border Payments Market
In order to understand Ripples functional utility value, we must examine the cross-border payments market, and how Ripple can and will be used as a means to serve that market.
Cryptocurrencies are an efficient means to move money between countries and bypass governmental regulation and red-tape. This is probably best illustrated by example – and so we begin by discussing the case of Bitcoin and Chinese Capital controls.
In the past several years, there has been a growing fear amongst many that the native Chinese currency, the Renminbi (also referred to as Yuan), is overvalued and due for a significant move lower versus other world currencies (the US dollar in particular). For various reasons, the Chinese government doesn’t want this to happen (at least not abruptly) and so has taken multiple steps to prevent it from happening. One of these steps is the institution of ‘capital controls’ – rules and regulations that make it difficult for Chinese citizens to move their Yuan denominated wealth out of the country and into other currencies. This has put both individual Chinese citizens and the Chinese government at odds with each other.
While the Chinese government can prevent citizens from transferring money abroad through the official banking system (no Chinese bank would dare defy an order from the government), they have been relatively powerless to prevent citizens from moving money out of China through Bitcoin. A simple example might be a Chinese local purchasing Bitcoin in China and paying for it with Yuan. That Chinese citizen then boards a flight from Beijing to New York, carrying their Bitcoin wallet private key on a slip of paper in their pocket. Once they land in New York, they might arrange to meet a Bitcoin buyer in a coffee shop, whereby in exchange for US dollars, they transfer their Bitcoin.
There are however, problems and costs with this. First and foremost, the Chinese citizen in our example may be (in the eyes of the Chinese government) breaking the law – potentially exposing himself to liability should he be caught. Furthermore, until the Chinese citizen in our example sells his Bitcoin for US $, he is exposed to the volatility of BTC. Depending on how he transacts, he also may be paying significant fees.
Nevertheless, the example demonstrates how crypto-currencies (in this case Bitcoin) can be used as an ‘intermediary-currency’ to move money around the world. Note that in this situation, Bitcoin is not being used as ‘money’ in a traditional sense, but as a specific tool for transferring money and bypassing regulation. This is an example of the functional-utility to which I earlier referred. Bitcoin (and all cryptocurrencies to an extent) may have a functional-utility in the form of money transfers – but is this the best way they may be used for that purpose? And just how do we value this functional utility?
And so, without further ado, we come to Ripple and the (legitimate and legal) Cross-Border payments market.
According to McKinsey & Company’s 2015 report, the 2014 size of the annual (legal) B2B cross-border payments market was $155 Trillion.[4]Assuming a modest 5% CAGR, we may estimate the 2020 B2B cross-border payments market at $207 Trillion. Regardless of what your personal opinion is of ‘banks’ in general, it’s worth noting that allof these transfers were presumably done through banks. Philosophical and moral imperatives aside, from a purely practical perspective, it’s where the money is.Unfortunately, as even a short google search will demonstrate, transferring money cross-borders is currently very complex, time-consuming (it can take several days to clear), and expensive.
But like in our example with Cryptocurrencies, it should be easy. All you would need to do to move money from Country-1/Currency-A to Country-2/Currency-B would be to buy a cryptocurrency in Country-1 using Currency-A, and then turn around and sell that same crypto-currency in Country-2 forCurrency B! As long as you have bank accounts on both sides set up and agreeing to the legitimacy and legality of the transactions, you could do this relatively quickly and easily.
So what would you need to do this?
Well, first and foremost, you need the banks to sign on to it and invest their own resources to adopt it. Since all of that $200+ trillion moves through business bank accounts, the banks will need to have the regulatory, legal, and logistical systems set-up before they can adopt the system. This is no small thing to get the banks to do, but of course the payoff for them to get it right is huge. Once the system is working, the participating banks can do away with their current slow and expensive cross-border-payments protocols and generate significant operational savings as well as market new, better services to their clients.
The fact that Ripple appears to have demonstrated such significant early success in signing up banks bodes well for their continued success, as first mover advantage in getting banks to adopt such a system is likely to be key. This is because:
a)     The more banks you have on board (as part of your cross-border money transfer community), the easier it is to convince other banks to sign up. Not only does it become an ‘easier sell’ internally at banks to adopt something new (if other reputable banks have already done so), but the very fact that other banks are already signed up means you (as a new member) will have all of those other banks as potential counterparties to engage in your future transactions.

b)     Switching costs are likely to be relatively high. Even if a ‘newer, better, faster’ crypto-currency solution comes out tomorrow, it is unlikely that any of the banks who signed up for Ripple will be keen to scrap all their legal, operational, and system integration work in favor of trying again with someone else and starting over.[5]

The Numbers
We start with our 2020 estimate of global B2B cross-border money transfers of $207 trillion.
Let’s assume (just to begin with) that Ripple accounts for 100% of this volume. Let’s further assume that this volume of transfers is evenly distributed amongst the days of the year, so daily transactions are valued at $207 trillion / 365 days = $567 billion… or for the sake of round numbers - $600 billion.
Now if $600 billion of money value is transferred through Ripple each day, some significant portion of that total must exist in the form of Ripple dedicated to effecting these foreign exchange transactions. To demonstrate this, let’s assume that this dollar amount is done in one, single transaction (and then we’ll adjust to come closer to a more realistic viewpoint).
In this theoretical example, we assume American Bank A wants to send $US 600 billion to Chinese Bank B, where it should ultimately ‘arrive’ as the Remnibi equivalent value of 4 trillion Yuan[6]. In such a case, American Bank A must buy$600 billion worth of Ripple, which it then sends over the Chinese Bank B who then sells this quantity of Ripple in exchange for 4 trillion Yuan. We can see that in order for this to work, there has to be an existing pool of Ripple (and Ripple/currency traders) worth at least $600 billion.
Now of course our $600 billion of daily transactions wouldn’t be done in one single transaction. It wound instead be done in many thousands of transactions. But the minimum value of the Ripple needed ‘to exist’ in order to effect these transactions though isn’t so much dependent on the quantity of transactions, but rather:
a)     the frequency of transactions and how long they ‘live within the ripple for’
b)     how many Ripple/Currency pairs are traded (in this case, Ripple vs USD, and Ripple vs Yuan)
c)     how many independent dealers are involved in the Ripple-related foreign exchange market
When taking into consideration the prospective details of all these transactions and my own personal experience dealing with trading markets and ‘dealer inventories’, I believe it’s a reasonable assumption that 35% of the ‘average daily volume’ calculated above would be held in the form of ‘working capital/trading inventory’ by all market-making parties. This takes into account an average ‘inventory turn’ of 3+x a day, as well as a recognition of the need for many disparate individual dealers to hold excess inventory to account for intraday demand spikes.
In such a case then, the average ‘inventory hold’ of all Ripple dealers (those facilitating foreign exchange transactions with the banks) would be 35% x $600 billion or $210 billion.
Said another way, under this circumstance a mere $210 billion of inventory would be enough to support annual transactions of $207 trillion – a mere 1/1000th of the gross annual volumes.
But this is assuming that Ripple accounts for 100% of all B2B cross-border transactions which is unrealistic. Let’s instead assume that Ripple has garnered a 35% market share by 2020[7]. This would mean that the ‘dealer inventory value’ of all Ripple would need to be no less than 35% x $210 billion or $73.5 billion.
But we must now adjust for the fact that dealers are not going to be holding all of the Ripple in circulation[8]. Given the presence of investors, speculators and consumer users of this technology, we might expect the dealers to only account for 80% of the extant Ripple coins in circulation. But the fact that the dealers don’t own 100% of the coins in circulation does notchange the fact that the total amount of their inventory must be no less than $73.5 billion to effect their transactions.  Therefore, we can estimate the total value of Ripple in circulation (when taking into account the 20% held by investors, speculators and consumers) to be $73.5 billion / 80% = $91.9 billion. This is then our solution as to what the functional utility floor value is for total circulating Ripple in 2020, if our assumptions prove correct. The only thing left to be determined then is how many XRP will be outstanding for this value to distributing over?
Considering that:
a)     there are currently less than 40 billion XRP outstanding
b)     it is neither in Ripple’s self-interest nor is it consistent with the lockups that have been announced for a substantial amount of XRP to ‘flood’ the market,
I believe a reasonable estimate for XRP outstanding in 2020 to be no more than 65 billion. Therefore, the value of each single XRP would be $91.9 billion divided by 65 billion or $1.43 per XRP or approximately 7x current trading values. From a present value perspective, If we assume a 20% discount rate for 3 years, we arrive at ~$0.83/XRP, or a nearly 4x multiple to where it is currently trading.[9]
If Ripple is successful in establishing itself as the dominant leader in B2B international money transfers, and/or the distribution of XRP/Foreign-Currency traders requires higher ‘dealer inventory holds’, then the value would of course be significantly higher. For example, if Ripple garners 70% of the market (as opposed to our 35%) and the total dealer hold is 50% of forecast daily transactions, then the valuation yields a result nearly triple what we’ve calculated so far.
Furthermore, remember though that this exercise is simply about demonstrating the functional-utility floor value of XRP. If/as the usefulness of XRP in the cross-border payments market is demonstrated, it stands to reason that a significant portion of the investing/speculating population will see XRP as potentially worthy of being considered ‘money’ in its own right. That XRP requires no mining resources as Proof-Of-Work coins do, is likely to have a leg-up in becoming integrated with the ‘everyman’s bank account’, and offers transaction processing speeds of 5-10 seconds argues for potentially significant and widespread adoption (and subsequent value appreciation).














[1] In my experience, the frequent mark of a good idea is that it quickly becomes part of conventional wisdom – so much so that people wonder how it could be that ‘no one thought of it before’.
[2] The currency is typically also accepted as the exclusivemeans with which to discharge economic obligations. If you don’t believe this to be so, try paying your US taxes in Euros.
[3] I recognize that a currency’s use ‘as money’ is technically its own form of functional utility. For the sake of this paper though, I define the term functional utility as excluding traditional money-uses such as being a generalized medium of exchange, unit of account and store of value.
[4]“Global payments 2015: A healthy industry confronts disruption” – by McKinsey and Co.
[5]It’s for these reasons that I am skeptical of Stellar’s competing platform. They appear to be at a disadvantage relative to Ripple in signing up banks, who are the largest near-intermediate term users of the service. That there is quite a bit of ‘soap-opera’ drama behind the founding of Stellar doesn’t help in that regard. Banks generally would prefer to choose a known and stable quantity over a brilliant but potentially volatile option. And while Stellar seems to be trying to market itself more as a libertarian option ‘away from the banks’, I question both the authenticity of their approach as well as the ultimate efficacy of adoption.
[6] We assume a CNY/USD exchange rate of approximately 7:1.
[7]Depending on your perspective, this may seem aggressive (considering the newness of the technology) or conservative (considering the cost and process advantages of the system, as well as potentially exponential adoption rates).
[8]Note also that for this exercise the ultimate‘diluted’ total amount of XRP in the system is not relevant, but rather the outstanding float, as it is only the outstanding float that may be used for the functional purpose of these transactions.
[9]Why a 20% discount rate? Considering both the speculative enthusiasm of the crypto-market, exceedingly low nominal interest rates (thanks central banks), and the real-progress the Ripple organization has made, 20% seems like a reasonable level at which the market may settle.

Is US Manufacturing Really Great Again?

One chart, more than any other, has influenced people's beliefs about the US manufacturing sector, as can be see by this debate here, and here (the latter a link to the Autor/Harrison/DeLong/Krugman debate, all of whom I am enormous fans of). This graph (below) apparently exposes the lie that trade has played a significant roll in hollowing out manufacturing jobs. It shows that manufacturing employment as a share of total non-farm employment has been declining on a fairly steady trend. In fact, in recent years, it has even outperformed this long-run trend. Thus, it seems we can forget the idea that US manufacturing is in any kind of a slump, judging by this. On the contrary, since we are now above trend, it seems that manufacturing is great again!































However, there are several problems with this thesis. The first is that, if we extend this trend far out into the future, it will imply that manufacturing employment should soon comprise a negative share of employment. Obviously, that can't happen. It would be more natural to assume that the decline would flatten out over time, as it eventually heads toward zero at a slower rate. Additionally, in terms of output growth, as Noah Smith notes, the period from 2008 hardly looks like any sort of a renaissance. And if rising above the trend after 2008 in terms of employment share is not evidence of good performance, than staying on the trend can hardly be conclusive evidence that everything was OK before it.

An additional problem is that, imagine for a second that you have a city -- let's call it Detroit -- that loses 80% of its tradable-sector employment. What could theoretically happen is that the city might soon lose 80% of its non-tradable sector employment as well. Thus, one might infer from its unchanging tradable sector employment share that the decline in tradables was not the cause of the overall decline in jobs. (And, yes, as I pointed out in my job-market paper, other tradable sectors beside manufacturing do seem to have been hit in the early 2000s.)

























One example that those who imagine themselves to be sophisticated often use is the decline of agricultural employment. Obviously, one major reason for this is dramatic productivity growth in agriculture over time. We're told then, that the linear decline of manufacturing as a share of total employment is just like agriculture. However, agricultural employment did not continue a linear decline all the way to negative territory. That would be impossible! after all. What happened is that in recent decades the decline as a share of total employment has slowed tremendously. Thus, the question could be why this didn't happen earlier for manufacturing -- why manufacturing was not like agriculture.




















(Note: I believe the steep dropoff in agricultural employment around 2000 was related to a change in the classification system.)

However, I do think it is true that while trade is a major driver of the decline in manufacturing employment (see my own research here and here), and was dominant up until the Great Recession, since then slow overall GDP growth is now likely to be the dominant factor holding back manufacturing. And thus, those who care about the US economy should be more focused on monetary policy than trade. Incidentally, a focus on monetary policy will also weaken the dollar and help solve that problem as well.

In any case, let me plot real manufacturing output relative to trend to make the case that not all is well in this sector. (Frequent readers of this blog or my twitter feed @TradeandMoney are no doubt already familiar.)


And, here is Real GDP relative to the long-run trend.


























Lastly, haven't we heard that manufacturing is declining "everywhere" as a share of GDP? Let's do an international comparison of employment, exports, and value-added in that case (see below). Indeed, one sees problems here as well.

The idea that everything is OK in US manufacturing is a cockroach idea that, no matter how much it is at odds with basic facts, can't seem to die. In a future post, I'll write a bit more about my thesis on what went wrong. Spoiler alert: it has to do with real exchange rates. If true, then a massive tax cut from Trump would be the worst thing to happen to the US manufacturing sector since, well, the last two massive tax cuts.











RFD: the alien abduction prophecy protocol


"It's tough to make predictions, especially about the future."
- variously attributed to Yogi Berra and Niels Bohr




Right. So let's say you are visited by transdimensional space aliens from outer space. There's some old-fashioned probing, but eventually, they get to the point. They outline a series of apocalyptic prophecies, beginning with the surprise 2032 election of Dwayne Elizondo Mountain Dew Herbert Camacho as the President of the United States, followed by a limited-scale nuclear exchange with the Grand Duchy of Ruritania in 2036, and culminating with the extinction of all life due to a series of cascading Y2K38 failures that start at an Ohio pretzel reprocessing plan. Long story short, if you want to save mankind, you have to warn others of what's to come.




But there's a snag: when you wake up in a roadside ditch in Alabama, you realize that nobody is going to believe your story! If you come forward, your professional and social reputation will be instantly destroyed. If you're lucky, the vindication of your claims will come fifteen years later; if not, it might turn out that you were pranked by some space alien frat boys who just wanted to have some cheap space laughs. The bottom line is, you need to be certain before you make your move. You figure this means staying mum until the Election Day of 2032.




But wait, this plan is also not very good! After all, how could your future self convince others that you knew about President Camacho all along? Well... if you work in information security, you are probably familiar with a neat solution: write down your account of events in a text file, calculate a cryptographic hash of this file, and publish the resulting value somewhere permanent. Fifteen years later, reveal the contents of your file and point people to your old announcement. Explain that you must have been in the possession of this very file back in 2017; otherwise, you would not have known its hash. Voila - a commitment scheme!




Although elegant, this approach can be risky: historically, the usable life of cryptographic hash functions seemed to hover at somewhere around 15 years - so even if you pick a very modern algorithm, there is a real risk that future advances in cryptanalysis could severely undermine the strength of your proof. No biggie, though! For extra safety, you could combine several independent hashing functions, or increase the computational complexity of the hash by running it in a loop. There are also some less-known hash functions, such as SPHINCS, that are designed with different trade-offs in mind and may offer longer-term security guarantees.




Of course, the computation of the hash is not enough; it needs to become an immutable part of the public record and remain easy to look up for years to come. There is no guarantee that any particular online publishing outlet is going to stay afloat that long and continue to operate in its current form. The survivability of more specialized and experimental platforms, such as blockchain-based notaries, seems even less clear. Thankfully, you can resort to another kludge: if you publish the hash through a large number of independent online venues, there is a good chance that at least one of them will be around in 2032.




(Offline notarization - whether of the pen-and-paper or the PKI-based variety - offers an interesting alternative. That said, in the absence of an immutable, public ledger, accusations of forgery or collusion would be very easy to make - especially if the fate of the entire planet is at stake.)




Even with this out of the way, there is yet another profound problem with the plan: a current-day scam artist could conceivably generate hundreds or thousands of political predictions, publish the hashes, and then simply discard or delete the ones that do not come true by 2032 - thus creating an illusion of prescience. To convince skeptics that you are not doing just that, you could incorporate a cryptographic proof of work into your approach, attaching a particular CPU time "price tag" to every hash. The future you could then claim that it would have been prohibitively expensive for the former you to attempt the "prediction spam" attack. But this argument seems iffy: a $1,000 proof may already be too costly for a lower middle class abductee, while a determined tech billionaire could easily spend $100,000 to pull off an elaborate prank on the entire world. Not to mention, massive CPU resources can be commandeered with little or no effort by the operators of large botnets and many other actors of this sort.




In the end, my best idea is to rely on an inherently low-bandwidth publication medium, rather than a high-cost one. For example, although a determined hoaxer could place thousands of hash-bearing classifieds in some of the largest-circulation newspapers, such sleigh-of-hand would be trivial for future sleuths to spot (at least compared to combing through the entire Internet for an abandoned hash). Or, as per an anonymous suggestion relayed by Thomas Ptacek: just tattoo the signature on your body, then post some post some pics; there are only so many places for a tattoo to go.




Still, what was supposed to be a nice, scientific proof devolved into a bunch of hand-wavy arguments and poorly-quantified probabilities. For the sake of future abductees: is there a better way?


Hibernate with infinispan tutorial for beginners

This tutorial is for developers who are just beginning to learn hibernate-search and trying to set up a demo project. Most of the codes are copied from the hibernate-search documentation: https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/

What we need:

  • eclipse-neon
  • hibernate-search 5.7.0
  • wildfly 10.1.0.Final
  • infinispan 8.2.6 (infinispan-as-embedded-modules-8.2.6.Final.zip), download this from the infinispan website and extract in your wildfly modules folder - do not forget to do this otherwise you'll have a missing class exception
Note:
I created my project using javaee7 maven archetype.

Since hibernate-search has already explained a lot we will just take note of the most important pieces:
  1. persistence.xml

    <property name="hibernate.show_sql" value="true" />
    <!-- Enables second level cache, call find after insert and no query in the database will be issue -->
    <property name="hibernate.cache.use_second_level_cache" value="false"/>
    <!-- Enable query cache -->
    <property name="hibernate.cache.use_query_cache" value="false"/>
    <!-- optional -->
    <property name="hibernate.search.default.directory_provider"
    value="infinispan" />
    <property name="hibernate.search.infinispan.cache_jndiname"
    value="java:jboss/infinispan/broodcampHibernateSearch" />
    <!-- <property name="hibernate.search.default.directory_provider" -->
    <!-- value="filesystem" /> -->
    <property name="hibernate.search.default.indexBase" value="c:/temp/lucene/indexes" />

    In here we set the directory_provider to infinispan, then we also set the cache JNDI name. So in wildfly's standalone.xml, we must add the cache below:
    <cache-container name="broodcamp" default-cache="broodcamp-hibernate-search">
    <local-cache name="broodcamp-hibernate-search" jndi-name="java:jboss/infinispan/broodcampHibernateSearch">
    <file-store path="c:/temp/lucene/indexes" passivation="true" purge="false"/>
    </local-cache>
    </cache-container>
  2. Create a class Author and Book from hibernate search documentation.
  3. In our pom we must define the following dependencies:
    <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-search-orm</artifactId>
    </dependency>

    <dependency>
    <groupId>org.infinispan</groupId>
    <artifactId>infinispan-directory-provider</artifactId>
    <version>8.2.4.Final</version>
    <scope>provided</scope>
    </dependency>
  4. Now let's create an arquillian test:
    1. arquillian.xml
      <?xml version="1.0" encoding="UTF-8"?>
      <arquillian xmlns="http://jboss.org/schema/arquillian"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://jboss.org/schema/arquillian
      http://jboss.org/schema/arquillian/arquillian_1_0.xsd">

      <defaultProtocol type="Servlet 3.0" />

      <container qualifier="wildfly" default="true">
      <configuration>
      <property name="jbossHome">C:\Java\jboss\wildfly-10.1.0.Final</property>
      </configuration>
      </container>

      <engine>
      <property name="deploymentExportPath">target/deployments</property>
      </engine>

      </arquillian>
      Set jbossHome to the correct value.
    2. Create our arquillian test class:
      /*
      * JBoss, Home of Professional Open Source
      * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual
      * contributors by the @authors tag. See the copyright.txt in the
      * distribution for a full listing of individual contributors.
      *
      * 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 com.broodcamp.hibernatesearch;

      import static org.junit.Assert.assertEquals;

      import java.util.List;
      import java.util.logging.Logger;

      import javax.inject.Inject;
      import javax.persistence.EntityManager;

      import org.hibernate.search.jpa.FullTextEntityManager;
      import org.hibernate.search.jpa.Search;
      import org.hibernate.search.query.dsl.QueryBuilder;
      import org.jboss.arquillian.container.test.api.Deployment;
      import org.jboss.arquillian.junit.Arquillian;
      import org.jboss.shrinkwrap.api.Archive;
      import org.jboss.shrinkwrap.api.ShrinkWrap;
      import org.jboss.shrinkwrap.api.asset.EmptyAsset;
      import org.jboss.shrinkwrap.api.spec.WebArchive;
      import org.junit.Test;
      import org.junit.runner.RunWith;

      @RunWith(Arquillian.class)
      public class HibernateSearchTest {

      private Logger log = Logger.getLogger(this.getClass().getName());

      @Inject
      private EntityManager em;

      @Deployment
      public static Archive<?> createTestArchive() {
      return ShrinkWrap.create(WebArchive.class, "test.war")
      .addClasses(Author.class, Book.class, Resources.class, StartupListener.class)
      .addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml")
      .addAsResource("import.sql", "import.sql").addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
      // Deploy our test datasource
      .addAsWebInfResource("test-ds.xml", "test-ds.xml");
      }

      @SuppressWarnings("unchecked")
      @Test
      public void testSimpleJPALuceneSearch() {
      log.info("testSimpleJPALuceneSearch");

      FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);

      // create native Lucene query using the query DSL
      // alternatively you can write the Lucene query using the Lucene query
      // parser
      // or the Lucene programmatic API. The Hibernate Search DSL is
      // recommended though
      QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Book.class).get();
      org.apache.lucene.search.Query luceneQuery = qb.keyword().onFields("title", "subTitle", "authors.name")
      .matching("Programmers").createQuery();

      // wrap Lucene query in a javax.persistence.Query
      javax.persistence.Query jpaQuery = fullTextEntityManager.createFullTextQuery(luceneQuery, Book.class);

      // execute search
      List<Book> result = (List<Book>) jpaQuery.getResultList();

      log.info("Record found=" + result.size());
      result.forEach(p -> log.info(p.toString()));

      assertEquals(9, result.size());
      }

      @SuppressWarnings("unchecked")
      @Test
      public void testMoreLikeThis() {
      Book book = em.find(Book.class, 14);
      FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);

      QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Book.class).get();
      org.apache.lucene.search.Query luceneQuery = qb.moreLikeThis().comparingFields("subTitle")
      .toEntity(book).createQuery();
      javax.persistence.Query jpaQuery = fullTextEntityManager.createFullTextQuery(luceneQuery, Book.class);

      // execute search
      List<Book> result = (List<Book>) jpaQuery.getResultList();

      log.info("Record found=" + result.size());
      result.forEach(p -> log.info(p.toString()));

      assertEquals(5, result.size());
      }

      }
And we are done. To run the arquillian test execute: mvn clean test -Parq-wildfly-managed. This comes from the javaee7 archetype.

Note: If you want to cache the result of a query, set hint:

TypedQuery query = em.createQuery("from Entity", Entity.class);
query.setHint("org.hibernate.cacheable", Boolean.TRUE);
List events = query.getResultList();


The project code is available at Github repository: https://github.com/czetsuya/hibernate-search-demo.