You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@marmotta.apache.org by wi...@apache.org on 2016/05/02 11:49:38 UTC

[01/50] [abbrv] marmotta git commit: MARMOTTA-621: latest details

Repository: marmotta
Updated Branches:
  refs/heads/MARMOTTA-584 fc5bb28de -> cde06ca13


MARMOTTA-621: latest details


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/27889eb1
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/27889eb1
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/27889eb1

Branch: refs/heads/MARMOTTA-584
Commit: 27889eb173b0bf2c76c6d65047e6f00f07ed8676
Parents: 0eba24f
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Wed Dec 16 13:27:33 2015 +0100
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Wed Dec 16 13:27:33 2015 +0100

----------------------------------------------------------------------
 libraries/ostrich/Dockerfile | 1 +
 libraries/ostrich/README.md  | 2 +-
 2 files changed, 2 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/27889eb1/libraries/ostrich/Dockerfile
----------------------------------------------------------------------
diff --git a/libraries/ostrich/Dockerfile b/libraries/ostrich/Dockerfile
index 887684d..6211776 100644
--- a/libraries/ostrich/Dockerfile
+++ b/libraries/ostrich/Dockerfile
@@ -70,6 +70,7 @@ RUN apt-get -y clean -qq \
     && rm -rf /var/lib/apt/lists/* \
     && rm -rf /src
 
+WORKDIR ${OSTRICH_PATH}
 EXPOSE 10000
 
 CMD ${OSTRICH_PATH}/persistence/marmotta_persistence -db ${DB_PATH} -port ${DB_PORT}

http://git-wip-us.apache.org/repos/asf/marmotta/blob/27889eb1/libraries/ostrich/README.md
----------------------------------------------------------------------
diff --git a/libraries/ostrich/README.md b/libraries/ostrich/README.md
index 6352f21..62db012 100644
--- a/libraries/ostrich/README.md
+++ b/libraries/ostrich/README.md
@@ -78,7 +78,7 @@ on the same machine as follows:
 
     ./backend/build/persistence/marmotta_persistence -db /path/to/shard1 -port 10001
     ./backend/build/persistence/marmotta_persistence -db /path/to/shard2 -port 10002
-    ./sharding/marmotta_sharding --port 10000 --backends localhost:10001,localhost:10002
+    ./backend/build/sharding/marmotta_sharding --port 10000 --backends localhost:10001,localhost:10002
 
 You can then access the sharding server through Marmotta like the persistence server. Running all instances
 on the same host is only useful for testing. In production environments, you would of course run all three


[41/50] [abbrv] marmotta git commit: Merge branch 'develop' of https://git-wip-us.apache.org/repos/asf/marmotta into develop

Posted by wi...@apache.org.
Merge branch 'develop' of https://git-wip-us.apache.org/repos/asf/marmotta into develop


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/c8f067f0
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/c8f067f0
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/c8f067f0

Branch: refs/heads/MARMOTTA-584
Commit: c8f067f0f0d6735015f26bcc386b3edc1c46cd6d
Parents: 28e6dba ff559ea
Author: Thomas Kurz <th...@salzburgresearch.at>
Authored: Wed Apr 20 09:42:56 2016 +0200
Committer: Thomas Kurz <th...@salzburgresearch.at>
Committed: Wed Apr 20 09:42:56 2016 +0200

----------------------------------------------------------------------
 .../services/test/ng/BaseLDCacheTest.java       |  7 +---
 .../test/rdf/TestLinkedDataProvider.java        |  1 +
 parent/pom.xml                                  |  2 +-
 .../src/main/resources/web/admin/about.html     | 41 ++++++--------------
 .../main/resources/web/admin/configuration.html |  7 +---
 .../src/main/resources/web/admin/console.html   |  2 +-
 .../src/main/resources/web/admin/database.html  |  2 +-
 7 files changed, 20 insertions(+), 42 deletions(-)
----------------------------------------------------------------------



[34/50] [abbrv] marmotta git commit: MARMOTTA-631: fixed by forcing to have the default context always, plus added an alternative implementation we may want to switch to

Posted by wi...@apache.org.
MARMOTTA-631: fixed by forcing to have the default context always, plus added an alternative implementation we may want to switch to


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/503cbc8d
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/503cbc8d
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/503cbc8d

Branch: refs/heads/MARMOTTA-584
Commit: 503cbc8daae89641b8f5d60c04274e1dcde012ec
Parents: 8710b7e
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Thu Mar 3 11:36:04 2016 +0100
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Thu Mar 3 11:36:04 2016 +0100

----------------------------------------------------------------------
 .../triplestore/ContextServiceImpl.java         | 82 +++++++++++++++++---
 .../test/triplestore/ContextServiceTest.java    |  2 +-
 2 files changed, 74 insertions(+), 10 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/503cbc8d/platform/marmotta-core/src/main/java/org/apache/marmotta/platform/core/services/triplestore/ContextServiceImpl.java
----------------------------------------------------------------------
diff --git a/platform/marmotta-core/src/main/java/org/apache/marmotta/platform/core/services/triplestore/ContextServiceImpl.java b/platform/marmotta-core/src/main/java/org/apache/marmotta/platform/core/services/triplestore/ContextServiceImpl.java
index 59d9fc2..3b34f4e 100644
--- a/platform/marmotta-core/src/main/java/org/apache/marmotta/platform/core/services/triplestore/ContextServiceImpl.java
+++ b/platform/marmotta-core/src/main/java/org/apache/marmotta/platform/core/services/triplestore/ContextServiceImpl.java
@@ -17,6 +17,8 @@
  */
 package org.apache.marmotta.platform.core.services.triplestore;
 
+import com.google.common.base.Predicate;
+import com.google.common.collect.Collections2;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.marmotta.commons.http.UriUtil;
 import org.apache.marmotta.commons.sesame.repository.ResourceUtils;
@@ -25,6 +27,7 @@ import org.apache.marmotta.platform.core.api.importer.ImportService;
 import org.apache.marmotta.platform.core.api.triplestore.ContextService;
 import org.apache.marmotta.platform.core.api.triplestore.SesameService;
 import org.apache.marmotta.platform.core.api.user.UserService;
+import org.apache.marmotta.platform.core.exception.InvalidArgumentException;
 import org.apache.marmotta.platform.core.exception.io.MarmottaImportException;
 import org.apache.marmotta.platform.core.qualifiers.kspace.ActiveKnowledgeSpaces;
 import org.apache.marmotta.platform.core.qualifiers.kspace.DefaultKnowledgeSpace;
@@ -32,9 +35,11 @@ import org.apache.marmotta.platform.core.qualifiers.kspace.InferredKnowledgeSpac
 import org.apache.marmotta.platform.core.qualifiers.kspace.SystemKnowledgeSpace;
 import org.openrdf.model.Resource;
 import org.openrdf.model.URI;
+import org.openrdf.model.Value;
 import org.openrdf.model.ValueFactory;
 import org.openrdf.model.util.Literals;
 import org.openrdf.model.vocabulary.RDFS;
+import org.openrdf.query.*;
 import org.openrdf.repository.RepositoryConnection;
 import org.openrdf.repository.RepositoryException;
 import org.openrdf.repository.RepositoryResult;
@@ -48,6 +53,7 @@ import javax.inject.Named;
 import java.io.InputStream;
 import java.net.URISyntaxException;
 import java.util.ArrayList;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
 
@@ -108,7 +114,30 @@ public class ContextServiceImpl implements ContextService {
 
     @Override
     public List<URI> listContexts(boolean filter) {
-        List<URI> contexts = new ArrayList<URI>();
+        //TODO: configuration
+        final Set<URI> contexts =  listContextsSesame();
+        //final Set<URI> contexts = listContextsSparql();
+
+        if (filter) {
+            Collections2.filter(contexts, new Predicate<URI>() {
+                @Override
+                public boolean apply(URI uri) {
+                    return uri.stringValue().startsWith(configurationService.getBaseContext());
+                }
+            });
+        }
+
+        return new ArrayList<>(contexts);
+
+    }
+
+    /**
+     * List context using the Sesame native API
+     *
+     * @return
+     */
+    private Set<URI> listContextsSesame() {
+        Set<URI> contexts = new HashSet<>();
         try {
             RepositoryConnection conn = sesameService.getConnection();
             try {
@@ -117,19 +146,54 @@ public class ContextServiceImpl implements ContextService {
                 while(result.hasNext()) {
                     Resource next = result.next();
                     if(next instanceof URI) {
-                        URI uri = (URI)next;
-                        if (filter) {
-                            if (uri.stringValue().startsWith(configurationService.getBaseContext())) {
-                                contexts.add(uri);
-                            }
-                        } else {
-                            contexts.add(uri);
-                        }
+                        contexts.add((URI)next);
                     }
                 }
                 result.close();
+                conn.commit();
             } finally {
+                conn.close();
+            }
+        } catch (RepositoryException e) {
+
+        }
+
+        //MARMOTTA-631: default context should be always there
+        try {
+            contexts.add(getDefaultContext());
+        } catch (URISyntaxException e) {}
+
+        return contexts;
+    }
+
+    /**
+     * Alternative implementation to list contexts using SPARQL
+     *
+     * @return
+     */
+    private Set<URI> listContextsSparql() {
+        Set<URI> contexts = new HashSet<>();
+        try {
+            RepositoryConnection conn = sesameService.getConnection();
+            try {
+                conn.begin();
+                final String query = "SELECT DISTINCT ?graph WHERE { GRAPH ?graph { ?s ?p ?o } }";
+                final TupleQuery sparqlQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query, configurationService.getBaseUri());
+                final TupleQueryResult results = sparqlQuery.evaluate();
+                try {
+                    while (results.hasNext()) {
+                        final Value next = results.next().getValue("graph");
+                        if(next instanceof URI) {
+                            contexts.add((URI)next);
+                        }
+                    }
+                } finally {
+                    results.close();
+                }
                 conn.commit();
+            } catch (MalformedQueryException | QueryEvaluationException e) {
+                log.error("Error evaluating query: {}", e.getMessage());
+            } finally {
                 conn.close();
             }
         } catch (RepositoryException e) {

http://git-wip-us.apache.org/repos/asf/marmotta/blob/503cbc8d/platform/marmotta-core/src/test/java/org/apache/marmotta/platform/core/test/triplestore/ContextServiceTest.java
----------------------------------------------------------------------
diff --git a/platform/marmotta-core/src/test/java/org/apache/marmotta/platform/core/test/triplestore/ContextServiceTest.java b/platform/marmotta-core/src/test/java/org/apache/marmotta/platform/core/test/triplestore/ContextServiceTest.java
index eec0d30..9599180 100644
--- a/platform/marmotta-core/src/test/java/org/apache/marmotta/platform/core/test/triplestore/ContextServiceTest.java
+++ b/platform/marmotta-core/src/test/java/org/apache/marmotta/platform/core/test/triplestore/ContextServiceTest.java
@@ -49,7 +49,7 @@ public class ContextServiceTest {
     @Test
     public void testEmpty() {
         final List<URI> contexts = contextService.listContexts();
-        Assert.assertEquals(0, contexts.size());
+        Assert.assertEquals(1, contexts.size());
     }
 
     @Test


[25/50] [abbrv] marmotta git commit: moved the readme to markdown

Posted by wi...@apache.org.
moved the readme to markdown


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/7eb9bc29
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/7eb9bc29
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/7eb9bc29

Branch: refs/heads/MARMOTTA-584
Commit: 7eb9bc29841bf6e380b99f5e971e10d83c07e65d
Parents: 808403d
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Fri Feb 12 08:53:06 2016 +0100
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Fri Feb 12 08:53:06 2016 +0100

----------------------------------------------------------------------
 README.md  | 109 ++++++++++++++++++++++++++++++++++++++++++++++++++
 README.txt | 120 --------------------------------------------------------
 2 files changed, 109 insertions(+), 120 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/7eb9bc29/README.md
----------------------------------------------------------------------
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..906be16
--- /dev/null
+++ b/README.md
@@ -0,0 +1,109 @@
+# Apache Marmotta
+
+This code repository contains the source-code for [Apache Marmotta](http://marmotta.apache.org/)
+
+
+## Building the Source Distribution
+
+Apache Marmotta uses Maven to build, test, and install the software. A basic
+build requires downloading and installing Maven and then running:
+
+    mvn clean install
+
+This will compile, package and test all Apache Marmotta modules and install
+it in your local Maven repository. In case you want to build your own
+projects based on some of the libraries provided by Apache Marmotta, this
+usually suffices.
+
+The default loglevel for most unit and integration tests executed during the
+build is INFO. To change the loglevel for either more or less output, you
+can pass the loglevel as system property:
+
+    mvn clean install -Droot-level=TRACE|DEBUG|INFO|WARN|ERROR
+
+Note that some of the integration tests start up parts of the Marmotta
+platform during execution. The log level for these tests cannot be
+changed, as Marmotta is taking over the log configuration in these
+cases.
+
+## Building, Running and Deploying the Wep Application
+
+Apache Marmotta also includes a default configuration for building a Java
+Web Application that can be deployed in any Java Application Server. To
+build the web application, first run
+
+    mvn clean install
+
+in the project root. Then change to the launchers/marmotta-webapp directory
+and run
+
+    mvn package
+
+This will create a marmotta.war file in the target/ directory. You can
+deploy this archive to any Java Application Server by copying it into
+its deployment directory; [more details](http://marmotta.apache.org/installation.html).
+
+Alternatively, you can directly startup the Apache Marmotta Web Application
+from Maven with a default configuration suitable for development. To try this
+out, run
+
+    mvn tomcat7:run
+
+wait until the system is started up and point your browser to `http://localhost:8080`
+
+When developing it is sometimes useful to always start with a clean confi-
+guration of the system. Therefore, you can also start up the web application
+as follows:
+
+    mvn clean tomcat7:run -Pcleanall
+
+This command will remove any existing configuration directory before startup.
+
+## Building the Standalone Installer
+
+The build environment also offers to automatically build an installer package
+that guides users through the installation with an easy-to-use installation
+wizard. The installer is based on izPack and dynamically assembled when
+building the package. To build the installer, first run
+
+    mvn clean install
+
+in the project root. Then change to the launchers/marmotta-installer directory
+and run
+
+    mvn package -Pinstaller
+
+The build process will automatically create an appropriate installer confi-
+guration from the Maven dependencies through the Apache Marmotta refpack
+build plugin.
+
+The installer can then be tried out by running
+
+    java -jar target/marmotta-installer-x.x.x.jar
+
+
+## Building with a Clean Repository
+
+Sometimes it is useful to check if the build runs properly on a clean local
+repository, i.e. simulate what happens if a user downloads the source and
+runs the build. This can be achieved by running Maven as follows:
+
+    mvn clean install -Dmaven.repo.local=/tmp/testrepo
+
+The command changes the local repository location from ~/.m2 to the
+directory passed as argument
+
+## Simulating a Release
+
+To test the release build without actually deploying the software, we have
+created a profile that will deploy to the local file system. You can
+simulate the release by running
+
+    mvn clean deploy -Pdist-local,marmotta-release,installer
+
+Please keep in mind that building a release involves creating digital
+signatures, so you will need a GPG key and a proper GPG configuration to run
+this task.
+
+Read more about [our release process](https://wiki.apache.org/marmotta/ReleaseProcess).
+

http://git-wip-us.apache.org/repos/asf/marmotta/blob/7eb9bc29/README.txt
----------------------------------------------------------------------
diff --git a/README.txt b/README.txt
deleted file mode 100644
index fdf536c..0000000
--- a/README.txt
+++ /dev/null
@@ -1,120 +0,0 @@
-Apache Marmotta
-===============
-
-This code repository contains the source-code for Apache Marmotta
-
-
-1. Building the Source Distribution
------------------------------------
-
-Apache Marmotta uses Maven to build, test, and install the software. A basic
-build requires downloading and installing Maven and then running:
-
-mvn clean install
-
-This will compile, package and test all Apache Marmotta modules and install
-it in your local Maven repository. In case you want to build your own
-projects based on some of the libraries provided by Apache Marmotta, this
-usually suffices.
-
-The default loglevel for most unit and integration tests executed during the
-build is INFO. To change the loglevel for either more or less output, you
-can pass the loglevel as system property:
-
-mvn clean install -Droot-level=TRACE|DEBUG|INFO|WARN|ERROR
-
-Note that some of the integration tests start up parts of the Marmotta
-platform during execution. The log level for these tests cannot be
-changed, as Marmotta is taking over the log configuration in these
-cases.
-
-2. Building, Running and Deploying the Wep Application
-------------------------------------------------------
-
-Apache Marmotta also includes a default configuration for building a Java
-Web Application that can be deployed in any Java Application Server. To
-build the web application, first run
-
-mvn clean install
-
-in the project root. Then change to the launchers/marmotta-webapp directory
-and run
-
-mvn package
-
-This will create a marmotta.war file in the target/ directory. You can
-deploy this archive to any Java Application Server by copying it into
-its deployment directory. More details can be found on:
-
-http://marmotta.apache.org/installation.html
-
-
-Alternatively, you can directly startup the Apache Marmotta Web Application
-from Maven with a default configuration suitable for development. To try this
-out, run
-
-mvn tomcat7:run
-
-wait until the system is started up and point your browser to
-http://localhost:8080
-
-When developing it is sometimes useful to always start with a clean confi-
-guration of the system. Therefore, you can also start up the web application
-as follows:
-
-mvn clean tomcat7:run -Pcleanall
-
-This command will remove any existing configuration directory before startup.
-
-
-
-3. Building the Standalone Installer
-------------------------------------
-
-The build environment also offers to automatically build an installer package
-that guides users through the installation with an easy-to-use installation
-wizard. The installer is based on izPack and dynamically assembled when
-building the package. To build the installer, first run
-
-mvn clean install
-
-in the project root. Then change to the launchers/marmotta-installer directory
-and run
-
-mvn package -Pinstaller
-
-The build process will automatically create an appropriate installer confi-
-guration from the Maven dependencies through the Apache Marmotta refpack
-build plugin.
-
-The installer can then be tried out by running
-
-java -jar target/marmotta-installer-x.x.x.jar
-
-
-4. Building with a Clean Repository
------------------------------------
-
-Sometimes it is useful to check if the build runs properly on a clean local
-repository, i.e. simulate what happens if a user downloads the source and
-runs the build. This can be achieved by running Maven as follows:
-
-mvn clean install -Dmaven.repo.local=/tmp/testrepo
-
-The command changes the local repository location from ~/.m2 to the
-directory passed as argument
-
-
-5. Simulating a Release
------------------------
-
-To test the release build without actually deploying the software, we have
-created a profile that will deploy to the local file system. You can
-simulate the release by running
-
-mvn clean deploy -Pdist-local,marmotta-release,installer
-
-Please keep in mind that building a release involves creating digital
-signatures, so you will need a GPG key and a proper GPG configuration to run
-this task.
-


[37/50] [abbrv] marmotta git commit: disabled all tests against rdfohloh until the service gets solved the issues regaring the api migration to openhub

Posted by wi...@apache.org.
disabled all tests against rdfohloh until the service gets solved the issues regaring the api migration to openhub


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/5f248d7c
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/5f248d7c
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/5f248d7c

Branch: refs/heads/MARMOTTA-584
Commit: 5f248d7cb1ca93858d34a400212aa4c42624b00a
Parents: 2932ecf
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Thu Mar 17 11:27:03 2016 +0100
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Thu Mar 17 11:27:03 2016 +0100

----------------------------------------------------------------------
 .../marmotta/ldcache/services/test/ng/BaseLDCacheTest.java    | 7 ++-----
 .../marmotta/ldclient/test/rdf/TestLinkedDataProvider.java    | 1 +
 2 files changed, 3 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/5f248d7c/libraries/ldcache/ldcache-core/src/test/java/org/apache/marmotta/ldcache/services/test/ng/BaseLDCacheTest.java
----------------------------------------------------------------------
diff --git a/libraries/ldcache/ldcache-core/src/test/java/org/apache/marmotta/ldcache/services/test/ng/BaseLDCacheTest.java b/libraries/ldcache/ldcache-core/src/test/java/org/apache/marmotta/ldcache/services/test/ng/BaseLDCacheTest.java
index 725c327..4f0ffea 100644
--- a/libraries/ldcache/ldcache-core/src/test/java/org/apache/marmotta/ldcache/services/test/ng/BaseLDCacheTest.java
+++ b/libraries/ldcache/ldcache-core/src/test/java/org/apache/marmotta/ldcache/services/test/ng/BaseLDCacheTest.java
@@ -38,7 +38,7 @@ import java.io.InputStream;
 import java.io.StringWriter;
 
 /**
- * Add file description here!
+ * Base LDCache test
  *
  * @author Sebastian Schaffert (sschaffert@apache.org)
  */
@@ -53,7 +53,6 @@ public abstract class BaseLDCacheTest {
 
     protected LDCache ldcache;
 
-
     protected ValueFactory valueFactory = ValueFactoryImpl.getInstance();
 
     /**
@@ -63,8 +62,6 @@ public abstract class BaseLDCacheTest {
      */
     protected abstract LDCachingBackend createBackend();
 
-
-
     @Before
     public void setup() {
         ldcache = new LDCache(new CacheConfiguration(), createBackend());
@@ -94,7 +91,7 @@ public abstract class BaseLDCacheTest {
     }
 
     @Test
-    @Ignore("test failing for the moment because the data returned by the service is wrong")
+    @Ignore("test failing for the moment because the issues on the service")
     public void testOHLOH() throws Exception {
         Assume.assumeTrue(existsClass("org.apache.marmotta.ldclient.provider.rdf.LinkedDataProvider"));
 

http://git-wip-us.apache.org/repos/asf/marmotta/blob/5f248d7c/libraries/ldclient/ldclient-provider-rdf/src/test/java/org/apache/marmotta/ldclient/test/rdf/TestLinkedDataProvider.java
----------------------------------------------------------------------
diff --git a/libraries/ldclient/ldclient-provider-rdf/src/test/java/org/apache/marmotta/ldclient/test/rdf/TestLinkedDataProvider.java b/libraries/ldclient/ldclient-provider-rdf/src/test/java/org/apache/marmotta/ldclient/test/rdf/TestLinkedDataProvider.java
index 9ae00d6..4c98534 100644
--- a/libraries/ldclient/ldclient-provider-rdf/src/test/java/org/apache/marmotta/ldclient/test/rdf/TestLinkedDataProvider.java
+++ b/libraries/ldclient/ldclient-provider-rdf/src/test/java/org/apache/marmotta/ldclient/test/rdf/TestLinkedDataProvider.java
@@ -89,6 +89,7 @@ public class TestLinkedDataProvider extends ProviderTestBase {
      *
      */
     @Test
+    @Ignore("test failing for the moment because the issues on the service")
     public void testRDFOhloh() throws Exception {
         testResource(MARMOTTA, "ohloh-marmotta.sparql");
     }


[32/50] [abbrv] marmotta git commit: MARMOTTA-625: merged pr, closes #16

Posted by wi...@apache.org.
MARMOTTA-625: merged pr, closes #16


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/528b3412
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/528b3412
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/528b3412

Branch: refs/heads/MARMOTTA-584
Commit: 528b341299e7f4db79e820839f979c070cd40dc1
Parents: a165b8e
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Mon Feb 15 15:05:53 2016 +0100
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Mon Feb 15 15:05:53 2016 +0100

----------------------------------------------------------------------
 .../kiwi/reasoner/parser/KWRLProgramParser.jj   | 26 ++++++++-----
 .../test/parser/KWRLRuleParserTest.java         | 41 ++++++++++++++++++--
 .../persistence/KWRLProgramPersistenceTest.java |  2 -
 3 files changed, 54 insertions(+), 15 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/528b3412/libraries/kiwi/kiwi-reasoner/src/main/javacc/org/apache/marmotta/kiwi/reasoner/parser/KWRLProgramParser.jj
----------------------------------------------------------------------
diff --git a/libraries/kiwi/kiwi-reasoner/src/main/javacc/org/apache/marmotta/kiwi/reasoner/parser/KWRLProgramParser.jj b/libraries/kiwi/kiwi-reasoner/src/main/javacc/org/apache/marmotta/kiwi/reasoner/parser/KWRLProgramParser.jj
index 67e502f..6044558 100644
--- a/libraries/kiwi/kiwi-reasoner/src/main/javacc/org/apache/marmotta/kiwi/reasoner/parser/KWRLProgramParser.jj
+++ b/libraries/kiwi/kiwi-reasoner/src/main/javacc/org/apache/marmotta/kiwi/reasoner/parser/KWRLProgramParser.jj
@@ -148,6 +148,12 @@ TOKEN : /* OPERATORS */
   	< TYPE: "^^" > 
 }
 
+
+TOKEN : /* JIRA MARMOTTA-625 */
+{
+        < LANG: "@"["a"-"z"]["a"-"z"] >
+}
+
 TOKEN :
 {
   	< LEFTP: "(" > |
@@ -351,19 +357,21 @@ VariableField Variable() : {Token t;}
     }
 }
 
-//TODO language tags
-LiteralField Literal() : {Token literal = null; Token type = null;}
+
+// Modified for MARMOTTA-625
+LiteralField Literal() : {Token literal = null; Token type = null; Token language = null;}
 {
 (
-   literal = <STRLIT>  (<TYPE> type = <URI>)? | "\"\""
-){ //have to remove the leading " character first
+   literal = <STRLIT> (language = <LANG>)? (<TYPE> type = <URI>)? | "\"\""
+){ // have to remove the surrounding quotes ane leading @ characters
+        if (language != null) {
+            return new LiteralField(resolveLiteral(literal.image.substring(1, literal.image.length()-1), 
+                                                   new Locale(language.image.substring(1)), null));
+        }
 	if (type != null) {
-	    return new LiteralField(resolveLiteral(literal.image.substring(1, literal.image.length()-1), Locale.getDefault(), type.image));
+	    return new LiteralField(resolveLiteral(literal.image.substring(1, literal.image.length()-1), null , type.image));
 	}
 	
-	return new LiteralField(resolveLiteral(literal.image.substring(1, literal.image.length()-1), Locale.getDefault(), null));
+	return new LiteralField(resolveLiteral(literal.image.substring(1, literal.image.length()-1), null, null));
   }
-
 }
-
-

http://git-wip-us.apache.org/repos/asf/marmotta/blob/528b3412/libraries/kiwi/kiwi-reasoner/src/test/java/org/apache/marmotta/kiwi/reasoner/test/parser/KWRLRuleParserTest.java
----------------------------------------------------------------------
diff --git a/libraries/kiwi/kiwi-reasoner/src/test/java/org/apache/marmotta/kiwi/reasoner/test/parser/KWRLRuleParserTest.java b/libraries/kiwi/kiwi-reasoner/src/test/java/org/apache/marmotta/kiwi/reasoner/test/parser/KWRLRuleParserTest.java
index 187021e..2f1651c 100644
--- a/libraries/kiwi/kiwi-reasoner/src/test/java/org/apache/marmotta/kiwi/reasoner/test/parser/KWRLRuleParserTest.java
+++ b/libraries/kiwi/kiwi-reasoner/src/test/java/org/apache/marmotta/kiwi/reasoner/test/parser/KWRLRuleParserTest.java
@@ -18,9 +18,9 @@
 package org.apache.marmotta.kiwi.reasoner.test.parser;
 
 import com.google.common.collect.ImmutableMap;
+import org.apache.marmotta.kiwi.reasoner.model.program.LiteralField;
 import org.apache.marmotta.kiwi.reasoner.model.program.Rule;
 import org.apache.marmotta.kiwi.reasoner.parser.KWRLProgramParser;
-import org.apache.marmotta.kiwi.test.RepositoryTest;
 import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
@@ -35,8 +35,8 @@ import org.slf4j.LoggerFactory;
 
 /**
  * Test parsing of individual rules
- * <p/>
- * Author: Sebastian Schaffert (sschaffert@apache.org)
+ *
+ * @author Sebastian Schaffert (sschaffert@apache.org)
  */
 public class KWRLRuleParserTest {
 
@@ -48,7 +48,6 @@ public class KWRLRuleParserTest {
         repository.initialize();
     }
 
-
     @After
     public void shutdown() throws Exception {
         repository.shutDown();
@@ -92,4 +91,38 @@ public class KWRLRuleParserTest {
         Assert.assertTrue(r.getHead().getObject().isVariableField());
     }
 
+    @Test
+    public void testRule3() throws Exception {
+        String rule = "($1 $2 $3) -> ($1 $2 \"Hello\"@en)";
+        Rule r = KWRLProgramParser.parseRule(rule, ImmutableMap.of("rdfs", "http://www.w3.org/2000/01/rdf-schema#"), repository.getValueFactory());
+
+        Assert.assertNotNull(r);
+        Assert.assertEquals(1, r.getBody().size());
+        Assert.assertTrue(r.getBody().get(0).getSubject().isVariableField());
+        Assert.assertTrue(r.getBody().get(0).getObject().isVariableField());
+        Assert.assertTrue(r.getBody().get(0).getProperty().isVariableField());
+        Assert.assertTrue(r.getHead().getSubject().isVariableField());
+        Assert.assertTrue(r.getHead().getProperty().isVariableField());
+        Assert.assertTrue(r.getHead().getObject().isLiteralField());
+        Assert.assertEquals("Hello", ((LiteralField) r.getHead().getObject()).getLiteral().getLabel());
+        Assert.assertEquals("en", ((LiteralField) r.getHead().getObject()).getLiteral().getLanguage());
+    }
+
+    @Test
+    public void testRule4() throws Exception {
+        String rule = "($1 $2 $3) -> ($1 $2 \"Bonjour\"@fr)";
+        Rule r = KWRLProgramParser.parseRule(rule, ImmutableMap.of("rdfs", "http://www.w3.org/2000/01/rdf-schema#"), repository.getValueFactory());
+
+        Assert.assertNotNull(r);
+        Assert.assertEquals(1, r.getBody().size());
+        Assert.assertTrue(r.getBody().get(0).getSubject().isVariableField());
+        Assert.assertTrue(r.getBody().get(0).getObject().isVariableField());
+        Assert.assertTrue(r.getBody().get(0).getProperty().isVariableField());
+        Assert.assertTrue(r.getHead().getSubject().isVariableField());
+        Assert.assertTrue(r.getHead().getProperty().isVariableField());
+        Assert.assertTrue(r.getHead().getObject().isLiteralField());
+        Assert.assertEquals("Bonjour", ((LiteralField)r.getHead().getObject()).getLiteral().getLabel());
+        Assert.assertEquals("fr", ((LiteralField) r.getHead().getObject()).getLiteral().getLanguage());
+    }
+
 }

http://git-wip-us.apache.org/repos/asf/marmotta/blob/528b3412/libraries/kiwi/kiwi-reasoner/src/test/java/org/apache/marmotta/kiwi/reasoner/test/persistence/KWRLProgramPersistenceTest.java
----------------------------------------------------------------------
diff --git a/libraries/kiwi/kiwi-reasoner/src/test/java/org/apache/marmotta/kiwi/reasoner/test/persistence/KWRLProgramPersistenceTest.java b/libraries/kiwi/kiwi-reasoner/src/test/java/org/apache/marmotta/kiwi/reasoner/test/persistence/KWRLProgramPersistenceTest.java
index a24fa5e..773bed7 100644
--- a/libraries/kiwi/kiwi-reasoner/src/test/java/org/apache/marmotta/kiwi/reasoner/test/persistence/KWRLProgramPersistenceTest.java
+++ b/libraries/kiwi/kiwi-reasoner/src/test/java/org/apache/marmotta/kiwi/reasoner/test/persistence/KWRLProgramPersistenceTest.java
@@ -63,13 +63,11 @@ public class KWRLProgramPersistenceTest {
     private Repository repository;
     private final KiWiConfiguration config;
 
-
     public KWRLProgramPersistenceTest(KiWiConfiguration config) {
         this.config = config;
         
     }
 
-
     @Before
     public void initDatabase() throws Exception {
         repository = new SailRepository(new MemoryStore());


[47/50] [abbrv] marmotta git commit: MARMOTTA-636: fixed apt check

Posted by wi...@apache.org.
MARMOTTA-636: fixed apt check


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/48b8a9d2
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/48b8a9d2
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/48b8a9d2

Branch: refs/heads/MARMOTTA-584
Commit: 48b8a9d2fe883281a248e9065d7a2f221001a9ce
Parents: 0bcd029
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Fri Apr 29 17:49:45 2016 +0200
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Fri Apr 29 17:49:45 2016 +0200

----------------------------------------------------------------------
 Dockerfile | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/48b8a9d2/Dockerfile
----------------------------------------------------------------------
diff --git a/Dockerfile b/Dockerfile
index 33f8d60..78b6bd1 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -70,8 +70,8 @@ RUN chown -R tomcat7:tomcat7 "$(dirname $CONF_PATH)"
 # cleanup
 RUN mvn clean \
     && rm -rf ~/.m2 \
-    && apt-get remove maven --purge \
-    && apt-get autoremove \
+    && apt-get remove maven --purge -y \
+    && apt-get autoremove -y \
     && apt-get clean -y \
     && apt-get autoclean -y \
     && apt-get autoremove -y \


[26/50] [abbrv] marmotta git commit: MARMOTTA-628: applied patch by @orinciog from github, closes #18

Posted by wi...@apache.org.
MARMOTTA-628: applied patch by @orinciog from github, closes #18


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/2a6f700c
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/2a6f700c
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/2a6f700c

Branch: refs/heads/MARMOTTA-584
Commit: 2a6f700c3368438acb873dc1040ed83a329cd27c
Parents: 7eb9bc2
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Fri Feb 12 13:21:36 2016 +0100
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Fri Feb 12 13:21:36 2016 +0100

----------------------------------------------------------------------
 .../kiwi/sparql/builder/eval/ValueExpressionEvaluator.java      | 4 ++++
 .../org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java    | 5 ++---
 2 files changed, 6 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/2a6f700c/libraries/kiwi/kiwi-sparql/src/main/java/org/apache/marmotta/kiwi/sparql/builder/eval/ValueExpressionEvaluator.java
----------------------------------------------------------------------
diff --git a/libraries/kiwi/kiwi-sparql/src/main/java/org/apache/marmotta/kiwi/sparql/builder/eval/ValueExpressionEvaluator.java b/libraries/kiwi/kiwi-sparql/src/main/java/org/apache/marmotta/kiwi/sparql/builder/eval/ValueExpressionEvaluator.java
index 2d41ff9..2082164 100644
--- a/libraries/kiwi/kiwi-sparql/src/main/java/org/apache/marmotta/kiwi/sparql/builder/eval/ValueExpressionEvaluator.java
+++ b/libraries/kiwi/kiwi-sparql/src/main/java/org/apache/marmotta/kiwi/sparql/builder/eval/ValueExpressionEvaluator.java
@@ -500,9 +500,13 @@ public class ValueExpressionEvaluator extends QueryModelVisitorBase<RuntimeExcep
             }
 
             optypes.push(ot);
+	    builder.append("(");
             expr.getLeftArg().visit(this);
+	    builder.append(")");
             builder.append(getSQLOperator(expr.getOperator()));
+	    builder.append("(");
             expr.getRightArg().visit(this);
+	    builder.append(")");
             optypes.pop();
         }
     }

http://git-wip-us.apache.org/repos/asf/marmotta/blob/2a6f700c/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java
----------------------------------------------------------------------
diff --git a/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java b/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java
index 1246845..67be368 100644
--- a/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java
+++ b/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java
@@ -296,13 +296,12 @@ public class KiWiSparqlTest {
         }
     }
 
-    /*
-    see https://issues.apache.org/jira/browse/MARMOTTA-628
+    
     @Test
     public void testMarmotta627_1() throws Exception {
         testMarmotta627("SELECT ( (4.5-4.4)*0.1 as ?c )  WHERE {}", 0.01);
     }
-    */
+    
 
     @Test
     public void testMarmotta627_2() throws Exception {


[22/50] [abbrv] marmotta git commit: MARMOTTA-627: temporally disabled test that detected MARMOTTA-628

Posted by wi...@apache.org.
MARMOTTA-627: temporally disabled test that detected MARMOTTA-628


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/1eb00653
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/1eb00653
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/1eb00653

Branch: refs/heads/MARMOTTA-584
Commit: 1eb006530f6070fdce26c970fd77b22f69a960c9
Parents: 1413bb8
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Thu Feb 11 14:40:18 2016 +0100
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Thu Feb 11 14:40:18 2016 +0100

----------------------------------------------------------------------
 .../java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java | 3 +++
 1 file changed, 3 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/1eb00653/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java
----------------------------------------------------------------------
diff --git a/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java b/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java
index 510e504..4a615bc 100644
--- a/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java
+++ b/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java
@@ -297,10 +297,13 @@ public class KiWiSparqlTest {
         }
     }
 
+    /*
+    see https://issues.apache.org/jira/browse/MARMOTTA-628
     @Test
     public void testMarmotta627_1() throws Exception {
         testMarmotta627("SELECT ( (4.5-4.4)*0.1 as ?c )  WHERE {}", 0.01);
     }
+    */
 
     @Test
     public void testMarmotta627_2() throws Exception {


[33/50] [abbrv] marmotta git commit: MARMOTTA-631: added test to reproduce the issue

Posted by wi...@apache.org.
MARMOTTA-631: added test to reproduce the issue


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/8710b7e2
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/8710b7e2
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/8710b7e2

Branch: refs/heads/MARMOTTA-584
Commit: 8710b7e26934c78fc3c2813f61dc1611b0e90359
Parents: 528b341
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Thu Mar 3 11:25:32 2016 +0100
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Thu Mar 3 11:25:32 2016 +0100

----------------------------------------------------------------------
 .../test/triplestore/ContextServiceTest.java    | 78 ++++++++++++++++++++
 1 file changed, 78 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/8710b7e2/platform/marmotta-core/src/test/java/org/apache/marmotta/platform/core/test/triplestore/ContextServiceTest.java
----------------------------------------------------------------------
diff --git a/platform/marmotta-core/src/test/java/org/apache/marmotta/platform/core/test/triplestore/ContextServiceTest.java b/platform/marmotta-core/src/test/java/org/apache/marmotta/platform/core/test/triplestore/ContextServiceTest.java
new file mode 100644
index 0000000..eec0d30
--- /dev/null
+++ b/platform/marmotta-core/src/test/java/org/apache/marmotta/platform/core/test/triplestore/ContextServiceTest.java
@@ -0,0 +1,78 @@
+package org.apache.marmotta.platform.core.test.triplestore;
+
+import com.google.common.base.Function;
+import com.google.common.collect.Collections2;
+import com.jayway.restassured.RestAssured;
+import org.apache.marmotta.platform.core.api.config.ConfigurationService;
+import org.apache.marmotta.platform.core.api.importer.ImportService;
+import org.apache.marmotta.platform.core.api.triplestore.ContextService;
+import org.apache.marmotta.platform.core.api.user.UserService;
+import org.apache.marmotta.platform.core.exception.io.MarmottaImportException;
+import org.apache.marmotta.platform.core.test.base.JettyMarmotta;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.openrdf.model.URI;
+
+import java.io.InputStream;
+import java.net.URISyntaxException;
+import java.util.List;
+
+/**
+ * Some basic test for context service
+ *
+ * @author Sergio Fern�ndez
+ */
+public class ContextServiceTest {
+
+    private static JettyMarmotta marmotta;
+    private static ConfigurationService configurationService;
+    private static ContextService contextService;
+
+    @BeforeClass
+    public static void setUp() {
+        marmotta = new JettyMarmotta("/marmotta");
+        configurationService = marmotta.getService(ConfigurationService.class);
+        contextService = marmotta.getService(ContextService.class);
+
+        RestAssured.baseURI = "http://localhost";
+        RestAssured.port = marmotta.getPort();
+        RestAssured.basePath = marmotta.getContext();
+    }
+
+    @AfterClass
+    public static void tearDown() {
+        marmotta.shutdown();
+    }
+
+    @Test
+    public void testEmpty() {
+        final List<URI> contexts = contextService.listContexts();
+        Assert.assertEquals(0, contexts.size());
+    }
+
+    @Test
+    public void testMarmotta631() {
+        final List<URI> contexts = contextService.listContexts();
+        Assert.assertTrue(contexts.size() >= 1);
+        Assert.assertTrue(Collections2.transform(contexts, new Function<URI, String>() {
+            @Override
+            public String apply(URI input) {
+                return input.stringValue();
+            }
+        }).contains(configurationService.getDefaultContext()));
+    }
+
+    @Test
+    public void testMarmotta631AfterImporting() throws URISyntaxException, MarmottaImportException {
+        final ImportService importService = marmotta.getService(ImportService.class);
+        final InputStream is = ContextServiceTest.class.getResourceAsStream("/org/apache/marmotta/platform/core/test/sesame/demo-data.foaf");
+        importService.importData(is, "application/rdf+xml", marmotta.getService(UserService.class).getAnonymousUser(), contextService.getDefaultContext());
+
+        final List<URI> contexts = contextService.listContexts();
+        Assert.assertTrue(contexts.size() >= 1);
+        Assert.assertTrue(contexts.contains(contextService.getDefaultContext()));
+    }
+
+}


[36/50] [abbrv] marmotta git commit: upgraded jsoup to avoid the reported vulnerabilities

Posted by wi...@apache.org.
upgraded jsoup to avoid the reported vulnerabilities


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/2932ecf2
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/2932ecf2
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/2932ecf2

Branch: refs/heads/MARMOTTA-584
Commit: 2932ecf20c1707f0745516fb4be312b0bad05ad3
Parents: 503cbc8
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Tue Mar 15 09:35:15 2016 +0100
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Tue Mar 15 09:35:15 2016 +0100

----------------------------------------------------------------------
 parent/pom.xml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/2932ecf2/parent/pom.xml
----------------------------------------------------------------------
diff --git a/parent/pom.xml b/parent/pom.xml
index 5366e41..81750b9 100644
--- a/parent/pom.xml
+++ b/parent/pom.xml
@@ -1711,7 +1711,7 @@
             <dependency>
                 <groupId>org.jsoup</groupId>
                 <artifactId>jsoup</artifactId>
-                <version>1.7.2</version>
+                <version>1.8.3</version>
             </dependency>
 
             <dependency>


[48/50] [abbrv] marmotta git commit: MARMOTTA-636: last details of documentation

Posted by wi...@apache.org.
MARMOTTA-636: last details of documentation


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/1d204839
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/1d204839
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/1d204839

Branch: refs/heads/MARMOTTA-584
Commit: 1d2048394fcce7a41ef060ff05a6445c824819b8
Parents: 48b8a9d
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Mon May 2 09:09:07 2016 +0200
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Mon May 2 09:09:07 2016 +0200

----------------------------------------------------------------------
 README.md                           | 18 ++++++++++++++++++
 launchers/marmotta-webapp/README.md |  2 +-
 2 files changed, 19 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/1d204839/README.md
----------------------------------------------------------------------
diff --git a/README.md b/README.md
index 906be16..4cf2b8e 100644
--- a/README.md
+++ b/README.md
@@ -82,6 +82,23 @@ The installer can then be tried out by running
     java -jar target/marmotta-installer-x.x.x.jar
 
 
+## Building a Docker image
+
+Marmotta also comes with support for creating a Docker images that you can use for development 
+or testing:
+
+1. Locate at the root of the source repository
+2. Build image: `docker build -t marmotta .`
+3. Run the container: `docker run -p 8080:8080 marmotta`
+4. Access Marmotta at [localhost:8080/marmotta](http://localhost:8080/marmotta) (IP address may 
+   be different, see information bellow).
+
+An official images is [available from Docker Hub](https://hub.docker.com/r/apache/marmotta/) as 
+an automated build, so you just need to pull it from there to replace the second step above: 
+
+    docker pull apache/marmotta
+
+
 ## Building with a Clean Repository
 
 Sometimes it is useful to check if the build runs properly on a clean local
@@ -93,6 +110,7 @@ runs the build. This can be achieved by running Maven as follows:
 The command changes the local repository location from ~/.m2 to the
 directory passed as argument
 
+
 ## Simulating a Release
 
 To test the release build without actually deploying the software, we have

http://git-wip-us.apache.org/repos/asf/marmotta/blob/1d204839/launchers/marmotta-webapp/README.md
----------------------------------------------------------------------
diff --git a/launchers/marmotta-webapp/README.md b/launchers/marmotta-webapp/README.md
index b3bdd21..b377940 100644
--- a/launchers/marmotta-webapp/README.md
+++ b/launchers/marmotta-webapp/README.md
@@ -22,7 +22,7 @@ and you can find the `.deb` file under `target/`.
 
 ## Docker
 
-It also comes with support for creating a Docker images that you can user for developing or testing:
+It also comes with support for creating a Docker images that you can use for development or testing:
 
 1. Locate at the root of the source repository
 2. Build image: `docker build -t marmotta .`


[17/50] [abbrv] marmotta git commit: [MARMOTTA-621] implement a loader backend for Ostrich, experiment with DBPedia gives arounf 45k triples/sec

Posted by wi...@apache.org.
[MARMOTTA-621] implement a loader backend for Ostrich, experiment with DBPedia gives arounf 45k triples/sec


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/8f60cf64
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/8f60cf64
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/8f60cf64

Branch: refs/heads/MARMOTTA-584
Commit: 8f60cf64dc8b8e99d89dbf4e54fa81af3635606f
Parents: 4eb074d
Author: Sebastian Schaffert <ss...@apache.org>
Authored: Sun Dec 20 12:40:52 2015 +0100
Committer: Sebastian Schaffert <ss...@apache.org>
Committed: Sun Dec 20 12:40:52 2015 +0100

----------------------------------------------------------------------
 libraries/ostrich/backend/CMakeLists.txt        |   2 +-
 .../ostrich/sail/OstrichSailConnection.java     |  14 +-
 loader/marmotta-loader-ostrich/pom.xml          |  83 ++++++++++
 .../loader/ostrich/OstrichLoaderBackend.java    | 100 ++++++++++++
 .../loader/ostrich/OstrichLoaderHandler.java    | 156 +++++++++++++++++++
 ...org.apache.marmotta.loader.api.LoaderBackend |  18 +++
 .../src/main/resources/logback.xml              |  32 ++++
 loader/pom.xml                                  |  10 ++
 8 files changed, 407 insertions(+), 8 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/8f60cf64/libraries/ostrich/backend/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/CMakeLists.txt b/libraries/ostrich/backend/CMakeLists.txt
index 5a8f110..61156a5 100644
--- a/libraries/ostrich/backend/CMakeLists.txt
+++ b/libraries/ostrich/backend/CMakeLists.txt
@@ -17,7 +17,7 @@ find_package (GLog REQUIRED)
 find_package (Boost 1.54.0 COMPONENTS iostreams filesystem system)
 find_package (Tcmalloc)
 
-#add_definitions(-DNDEBUG)
+add_definitions(-DNDEBUG)
 
 if (Boost_IOSTREAMS_FOUND)
     message(STATUS "Enabling gzip/bzip2 support (Boost iostreams found)")

http://git-wip-us.apache.org/repos/asf/marmotta/blob/8f60cf64/libraries/ostrich/client/src/main/java/org/apache/marmotta/ostrich/sail/OstrichSailConnection.java
----------------------------------------------------------------------
diff --git a/libraries/ostrich/client/src/main/java/org/apache/marmotta/ostrich/sail/OstrichSailConnection.java b/libraries/ostrich/client/src/main/java/org/apache/marmotta/ostrich/sail/OstrichSailConnection.java
index 93e21ac..e85fdd2 100644
--- a/libraries/ostrich/client/src/main/java/org/apache/marmotta/ostrich/sail/OstrichSailConnection.java
+++ b/libraries/ostrich/client/src/main/java/org/apache/marmotta/ostrich/sail/OstrichSailConnection.java
@@ -107,7 +107,7 @@ public class OstrichSailConnection extends NotifyingSailConnectionBase {
 
     @Override
     protected void addStatementInternal(Resource subj, URI pred, Value obj, Resource... contexts) throws SailException {
-        log.info("Adding statements.");
+        log.debug("Adding statements.");
         ensureTransaction();
 
         if (contexts.length > 0) {
@@ -319,7 +319,7 @@ public class OstrichSailConnection extends NotifyingSailConnectionBase {
 
     @Override
     protected void removeStatementsInternal(Resource subj, URI pred, Value obj, Resource... contexts) throws SailException {
-        log.info("Removing statements.");
+        log.debug("Removing statements.");
         commitForQuery();
         ensureTransaction();
 
@@ -338,7 +338,7 @@ public class OstrichSailConnection extends NotifyingSailConnectionBase {
 
     @Override
     protected void clearInternal(Resource... contexts) throws SailException {
-        log.info("Clearing statements.");
+        log.debug("Clearing statements.");
         commitForQuery();
         ensureTransaction();
 
@@ -357,7 +357,7 @@ public class OstrichSailConnection extends NotifyingSailConnectionBase {
 
     @Override
     protected CloseableIteration<? extends Namespace, SailException> getNamespacesInternal() throws SailException {
-        log.info("Getting namespaces.");
+        log.debug("Getting namespaces.");
         commitForQuery();
 
         Empty pattern = Empty.getDefaultInstance();
@@ -382,7 +382,7 @@ public class OstrichSailConnection extends NotifyingSailConnectionBase {
 
     @Override
     protected void setNamespaceInternal(String prefix, String name) throws SailException {
-        log.info("Setting namespace {} = {}.", prefix, name);
+        log.debug("Setting namespace {} = {}.", prefix, name);
         ensureTransaction();
 
         ProtoNamespace ns = new ProtoNamespace(prefix, name);
@@ -393,7 +393,7 @@ public class OstrichSailConnection extends NotifyingSailConnectionBase {
 
     @Override
     protected void removeNamespaceInternal(String prefix) throws SailException {
-        log.info("Removing namespace {}.", prefix);
+        log.debug("Removing namespace {}.", prefix);
         commitForQuery();
         ensureTransaction();
 
@@ -404,7 +404,7 @@ public class OstrichSailConnection extends NotifyingSailConnectionBase {
 
     @Override
     protected void clearNamespacesInternal() throws SailException {
-        log.info("Clearing namespaces.");
+        log.debug("Clearing namespaces.");
         commitForQuery();
         ensureTransaction();
 

http://git-wip-us.apache.org/repos/asf/marmotta/blob/8f60cf64/loader/marmotta-loader-ostrich/pom.xml
----------------------------------------------------------------------
diff --git a/loader/marmotta-loader-ostrich/pom.xml b/loader/marmotta-loader-ostrich/pom.xml
new file mode 100644
index 0000000..5816b68
--- /dev/null
+++ b/loader/marmotta-loader-ostrich/pom.xml
@@ -0,0 +1,83 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+   Licensed to the Apache Software Foundation (ASF) under one or more
+   contributor license agreements.  See the NOTICE file distributed with
+   this work for additional information regarding copyright ownership.
+   The ASF licenses this file to You 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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+
+    <parent>
+        <groupId>org.apache.marmotta</groupId>
+        <artifactId>marmotta-parent</artifactId>
+        <version>3.4.0-SNAPSHOT</version>
+        <relativePath>../../parent</relativePath>
+    </parent>
+
+    <artifactId>marmotta-loader-ostrich</artifactId>
+    <name>Loader: Ostrich Backend</name>
+
+    <description>
+        Apache Marmotta bulk loader backend for loading large datasets into a Ostrich/LevelDB backend.
+    </description>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-shade-plugin</artifactId>
+                <version>2.2</version>
+                <executions>
+                    <execution>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>shade</goal>
+                        </goals>
+                        <configuration>
+                            <createDependencyReducedPom>false</createDependencyReducedPom>
+                            <transformers>
+                                <transformer implementation="org.apache.maven.plugins.shade.resource.ApacheLicenseResourceTransformer" />
+                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
+                                    <mainClass>org.apache.marmotta.loader.core.MarmottaLoader</mainClass>
+                                </transformer>
+                                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
+                                <transformer implementation="org.apache.maven.plugins.shade.resource.ApacheNoticeResourceTransformer">
+                                    <addHeader>false</addHeader>
+                                </transformer>
+                            </transformers>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.apache.marmotta</groupId>
+            <artifactId>marmotta-loader-core</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.marmotta</groupId>
+            <artifactId>ostrich-model</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.marmotta</groupId>
+            <artifactId>ostrich-client</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+    </dependencies>
+</project>

http://git-wip-us.apache.org/repos/asf/marmotta/blob/8f60cf64/loader/marmotta-loader-ostrich/src/main/java/org/apache/marmotta/loader/ostrich/OstrichLoaderBackend.java
----------------------------------------------------------------------
diff --git a/loader/marmotta-loader-ostrich/src/main/java/org/apache/marmotta/loader/ostrich/OstrichLoaderBackend.java b/loader/marmotta-loader-ostrich/src/main/java/org/apache/marmotta/loader/ostrich/OstrichLoaderBackend.java
new file mode 100644
index 0000000..bd6e49e
--- /dev/null
+++ b/loader/marmotta-loader-ostrich/src/main/java/org/apache/marmotta/loader/ostrich/OstrichLoaderBackend.java
@@ -0,0 +1,100 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.marmotta.loader.ostrich;
+
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.OptionBuilder;
+import org.apache.commons.configuration.Configuration;
+import org.apache.marmotta.loader.api.LoaderBackend;
+import org.apache.marmotta.loader.api.LoaderHandler;
+
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * Ostrich loader backend. Provides configuration for the OstrichLoaderHandler.
+ *
+ * @author Sebastian Schaffert (sschaffert@apache.org)
+ */
+public class OstrichLoaderBackend implements LoaderBackend {
+
+    /**
+     * Create the RDFHandler to be used for bulk-loading, optionally using the configuration passed as argument.
+     *
+     * @param configuration
+     * @return a newly created RDFHandler instance
+     */
+    @Override
+    public LoaderHandler createLoader(Configuration configuration) {
+        return new OstrichLoaderHandler(
+                configuration.getString("backend.ostrich.host", "localhost"),
+                configuration.getInt("backend.ostrich.port", 10000),
+                configuration.getLong("backend.ostrich.batchsize", 500000));
+    }
+
+    /**
+     * Return a unique identifier for the loader; used for identifying the loader to choose on the command line
+     * in case more than one loader implementation is available.
+     * <p/>
+     * Should match with the regular expression [a-z][a-z0-9]*
+     *
+     * @return
+     */
+    @Override
+    public String getIdentifier() {
+        return "ostrich";
+    }
+
+    /**
+     * Return any additional options that this backend offers (e.g. for connecting to a database etc).
+     * If there are no additional options, return an empty collection.
+     *
+     * @return
+     */
+    @Override
+    public Collection<Option> getOptions() {
+        Set<Option> options = new HashSet<>();
+
+        Option host =
+                OptionBuilder.withArgName("host")
+                        .hasArgs(1)
+                        .withDescription("hostname or IP address of Ostrich/LevelDB server")
+                        .withLongOpt("host")
+                        .create('H');
+        options.add(host);
+
+        Option port =
+                OptionBuilder.withArgName("port")
+                        .hasArgs(1)
+                        .withDescription("port used by Ostrich/LevelDB server")
+                        .withLongOpt("port")
+                        .create('P');
+        options.add(port);
+
+        Option batchSize =
+                OptionBuilder.withArgName("batchsize")
+                        .hasArgs(1)
+                        .withDescription("maximum number of statements to commit in one batch")
+                        .withLongOpt("batchsize")
+                        .create('B');
+        options.add(batchSize);
+
+        return options;
+    }
+}

http://git-wip-us.apache.org/repos/asf/marmotta/blob/8f60cf64/loader/marmotta-loader-ostrich/src/main/java/org/apache/marmotta/loader/ostrich/OstrichLoaderHandler.java
----------------------------------------------------------------------
diff --git a/loader/marmotta-loader-ostrich/src/main/java/org/apache/marmotta/loader/ostrich/OstrichLoaderHandler.java b/loader/marmotta-loader-ostrich/src/main/java/org/apache/marmotta/loader/ostrich/OstrichLoaderHandler.java
new file mode 100644
index 0000000..675d25a
--- /dev/null
+++ b/loader/marmotta-loader-ostrich/src/main/java/org/apache/marmotta/loader/ostrich/OstrichLoaderHandler.java
@@ -0,0 +1,156 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.marmotta.loader.ostrich;
+
+import org.apache.marmotta.loader.api.LoaderHandler;
+import org.apache.marmotta.ostrich.sail.OstrichSail;
+import org.openrdf.model.Statement;
+import org.openrdf.rio.RDFHandlerException;
+import org.openrdf.sail.SailConnection;
+import org.openrdf.sail.SailException;
+
+/**
+ * Add file description here!
+ *
+ * @author Sebastian Schaffert (sschaffert@apache.org)
+ */
+public class OstrichLoaderHandler implements LoaderHandler {
+
+    private OstrichSail sail;
+    private SailConnection con;
+
+    long count = 0;
+    long batchSize = 500000;
+
+    public OstrichLoaderHandler(String host, int port, long batchSize) {
+        this.batchSize = batchSize;
+        this.sail      = new OstrichSail(host,port);
+    }
+
+    /**
+     * Initialise the handler, performing any initialisation steps that are necessary before bulk importing can
+     * start (e.g. dropping indexes or establishing a connection).
+     *
+     * @throws RDFHandlerException
+     */
+    @Override
+    public void initialise() throws RDFHandlerException {
+        try {
+            sail.initialize();
+            con = sail.getConnection();
+        } catch (SailException e) {
+            throw new RDFHandlerException("Could not establish Ostrich connection", e);
+        }
+    }
+
+    /**
+     * Peform cleanup on shutdown, e.g. re-creating indexes after import completed or freeing resources acquired by
+     * the handler.
+     */
+    @Override
+    public void shutdown() throws RDFHandlerException {
+        try {
+            con.close();
+            sail.shutDown();
+        } catch (SailException e) {
+            throw new RDFHandlerException("Could not close Ostrich connection", e);
+        }
+
+    }
+
+    /**
+     * Signals the start of the RDF data. This method is called before any data
+     * is reported.
+     *
+     * @throws RDFHandlerException If the RDF handler has encountered an unrecoverable error.
+     */
+    @Override
+    public void startRDF() throws RDFHandlerException {
+        try {
+            con.begin();
+        } catch (SailException e) {
+            throw new RDFHandlerException("Could not start transaction", e);
+        }
+    }
+
+    /**
+     * Signals the end of the RDF data. This method is called when all data has
+     * been reported.
+     *
+     * @throws RDFHandlerException If the RDF handler has encountered an unrecoverable error.
+     */
+    @Override
+    public void endRDF() throws RDFHandlerException {
+        try {
+            con.commit();
+        } catch (SailException e) {
+            throw new RDFHandlerException("Could not commit transaction", e);
+        }
+    }
+
+    /**
+     * Handles a namespace declaration/definition. A namespace declaration
+     * associates a (short) prefix string with the namespace's URI. The prefix
+     * for default namespaces, which do not have an associated prefix, are
+     * represented as empty strings.
+     *
+     * @param prefix The prefix for the namespace, or an empty string in case of a
+     *               default namespace.
+     * @param uri    The URI that the prefix maps to.
+     * @throws RDFHandlerException If the RDF handler has encountered an unrecoverable error.
+     */
+    @Override
+    public void handleNamespace(String prefix, String uri) throws RDFHandlerException {
+        try {
+            con.setNamespace(prefix, uri);
+        } catch (SailException e) {
+            throw new RDFHandlerException("Could not add namespace", e);
+        }
+    }
+
+    /**
+     * Handles a statement.
+     *
+     * @param st The statement.
+     * @throws RDFHandlerException If the RDF handler has encountered an unrecoverable error.
+     */
+    @Override
+    public void handleStatement(Statement st) throws RDFHandlerException {
+        try {
+            con.addStatement(st.getSubject(), st.getPredicate(), st.getObject(), st.getContext());
+
+            if (++count % batchSize == 0) {
+                con.commit();
+                con.begin();
+            }
+        } catch (SailException e) {
+            throw new RDFHandlerException("Could not add statement", e);
+        }
+    }
+
+    /**
+     * Handles a comment.
+     *
+     * @param comment The comment.
+     * @throws RDFHandlerException If the RDF handler has encountered an unrecoverable error.
+     */
+    @Override
+    public void handleComment(String comment) throws RDFHandlerException {
+
+    }
+}

http://git-wip-us.apache.org/repos/asf/marmotta/blob/8f60cf64/loader/marmotta-loader-ostrich/src/main/resources/META-INF/services/org.apache.marmotta.loader.api.LoaderBackend
----------------------------------------------------------------------
diff --git a/loader/marmotta-loader-ostrich/src/main/resources/META-INF/services/org.apache.marmotta.loader.api.LoaderBackend b/loader/marmotta-loader-ostrich/src/main/resources/META-INF/services/org.apache.marmotta.loader.api.LoaderBackend
new file mode 100644
index 0000000..ca1e9a1
--- /dev/null
+++ b/loader/marmotta-loader-ostrich/src/main/resources/META-INF/services/org.apache.marmotta.loader.api.LoaderBackend
@@ -0,0 +1,18 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+org.apache.marmotta.loader.ostrich.OstrichLoaderBackend
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/marmotta/blob/8f60cf64/loader/marmotta-loader-ostrich/src/main/resources/logback.xml
----------------------------------------------------------------------
diff --git a/loader/marmotta-loader-ostrich/src/main/resources/logback.xml b/loader/marmotta-loader-ostrich/src/main/resources/logback.xml
new file mode 100644
index 0000000..ebc7937
--- /dev/null
+++ b/loader/marmotta-loader-ostrich/src/main/resources/logback.xml
@@ -0,0 +1,32 @@
+<!--
+  ~ Licensed to the Apache Software Foundation (ASF) under one or more
+  ~ contributor license agreements.  See the NOTICE file distributed with
+  ~ this work for additional information regarding copyright ownership.
+  ~ The ASF licenses this file to You 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.
+  -->
+
+<configuration>
+    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
+        <encoder>
+            <pattern>%d{HH:mm:ss.SSS} %level %logger{15} - %m%n</pattern>
+        </encoder>
+    </appender>
+
+    <logger name="org.apache.zookeeper" level="WARN" />
+    <logger name="org.apache.hadoop" level="WARN" />
+
+
+    <root level="${root-level:-INFO}">
+        <appender-ref ref="CONSOLE"/>
+    </root>
+</configuration>

http://git-wip-us.apache.org/repos/asf/marmotta/blob/8f60cf64/loader/pom.xml
----------------------------------------------------------------------
diff --git a/loader/pom.xml b/loader/pom.xml
index dbdc0f1..4771f28 100644
--- a/loader/pom.xml
+++ b/loader/pom.xml
@@ -92,4 +92,14 @@
         <module>marmotta-loader-berkeley</module>
     </modules>
 
+    <profiles>
+        <profile>
+            <id>ostrich</id>
+            <modules>
+                <module>marmotta-loader-ostrich</module>
+            </modules>
+        </profile>
+    </profiles>
+
+
 </project>


[13/50] [abbrv] marmotta git commit: code cleanups

Posted by wi...@apache.org.
code cleanups


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/0064d335
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/0064d335
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/0064d335

Branch: refs/heads/MARMOTTA-584
Commit: 0064d3358325a9fcf7d6dcf7b717107fea1356d8
Parents: 5487333
Author: Sebastian Schaffert <ss...@apache.org>
Authored: Sat Dec 19 17:13:49 2015 +0100
Committer: Sebastian Schaffert <ss...@apache.org>
Committed: Sat Dec 19 17:13:49 2015 +0100

----------------------------------------------------------------------
 libraries/ostrich/backend/CMakeLists.txt        |  2 +
 .../backend/persistence/leveldb_persistence.cc  |  4 +-
 libraries/ostrich/backend/test/CMakeLists.txt   |  1 -
 .../ostrich/backend/test/PersistenceTest.cc     | 45 +++++++++++++++++++-
 libraries/ostrich/backend/util/iterator.h       |  2 +-
 5 files changed, 49 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/0064d335/libraries/ostrich/backend/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/CMakeLists.txt b/libraries/ostrich/backend/CMakeLists.txt
index e05c28b..5a8f110 100644
--- a/libraries/ostrich/backend/CMakeLists.txt
+++ b/libraries/ostrich/backend/CMakeLists.txt
@@ -28,6 +28,8 @@ if (Tcmalloc_FOUND)
     message(STATUS "Enabling profiling support (Tcmalloc found)")
 endif (Tcmalloc_FOUND)
 
+enable_testing()
+
 add_subdirectory(util)
 add_subdirectory(model)
 add_subdirectory(sparql)

http://git-wip-us.apache.org/repos/asf/marmotta/blob/0064d335/libraries/ostrich/backend/persistence/leveldb_persistence.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/persistence/leveldb_persistence.cc b/libraries/ostrich/backend/persistence/leveldb_persistence.cc
index f29895c..852f152 100644
--- a/libraries/ostrich/backend/persistence/leveldb_persistence.cc
+++ b/libraries/ostrich/backend/persistence/leveldb_persistence.cc
@@ -170,6 +170,7 @@ class PatternQuery {
         return *this;
     }
 
+    // Returns true in case this query pattern cannot be answered by the index alone.
     bool NeedsFilter() const {
         return needsFilter;
     }
@@ -260,7 +261,8 @@ class StatementRangeIterator : public LevelDBIterator<Statement> {
     char *hiKey;
 };
 
-
+// Return true if the statement matches the pattern. Wildcards (empty fields)
+// in the pattern are ignored.
 bool Matches(const Statement& pattern, const Statement& stmt) {
     // equality operators defined in rdf_model.h
     if (pattern.has_context() && stmt.context() != pattern.context()) {

http://git-wip-us.apache.org/repos/asf/marmotta/blob/0064d335/libraries/ostrich/backend/test/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/test/CMakeLists.txt b/libraries/ostrich/backend/test/CMakeLists.txt
index 660f40f..29491ba 100644
--- a/libraries/ostrich/backend/test/CMakeLists.txt
+++ b/libraries/ostrich/backend/test/CMakeLists.txt
@@ -1,4 +1,3 @@
-enable_testing()
 include_directories(${GTEST_INCLUDE_DIRS})
 include_directories(..)
 include_directories(${CMAKE_CURRENT_BINARY_DIR}/..)

http://git-wip-us.apache.org/repos/asf/marmotta/blob/0064d335/libraries/ostrich/backend/test/PersistenceTest.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/test/PersistenceTest.cc b/libraries/ostrich/backend/test/PersistenceTest.cc
index 1b2cfb2..301692e 100644
--- a/libraries/ostrich/backend/test/PersistenceTest.cc
+++ b/libraries/ostrich/backend/test/PersistenceTest.cc
@@ -73,8 +73,8 @@ TEST_F(PersistenceTest, TestAddStatements) {
     }
 }
 
-
-TEST_F(PersistenceTest, TestGetStatements) {
+// Test pattern queries that can be answered directly by the index.
+TEST_F(PersistenceTest, TestGetStatementsIndexed) {
     std::vector<rdf::proto::Statement> stmts = {
             rdf::Statement(rdf::URI("http://example.com/s1"), rdf::URI("http://example.com/p1"),
                            rdf::URI("http://example.com/o1")).getMessage(),
@@ -121,6 +121,47 @@ TEST_F(PersistenceTest, TestGetStatements) {
     EXPECT_FALSE(it3->hasNext());
 }
 
+// Test pattern queries that trigger filtering because the index alone cannot answer these queries.
+TEST_F(PersistenceTest, TestGetStatementsFiltered) {
+    std::vector<rdf::proto::Statement> stmts = {
+            rdf::Statement(rdf::URI("http://example.com/s1"), rdf::URI("http://example.com/p1"),
+                           rdf::URI("http://example.com/o1")).getMessage(),
+            rdf::Statement(rdf::URI("http://example.com/s1"), rdf::URI("http://example.com/p2"),
+                           rdf::URI("http://example.com/o1")).getMessage(),
+            rdf::Statement(rdf::URI("http://example.com/s1"), rdf::URI("http://example.com/p3"),
+                           rdf::URI("http://example.com/o1")).getMessage(),
+            rdf::Statement(rdf::URI("http://example.com/s2"), rdf::URI("http://example.com/p1"),
+                           rdf::URI("http://example.com/o2")).getMessage(),
+            rdf::Statement(rdf::URI("http://example.com/s2"), rdf::URI("http://example.com/p2"),
+                           rdf::URI("http://example.com/o2")).getMessage(),
+    };
+
+    util::CollectionIterator<rdf::proto::Statement> it(stmts);
+    db->AddStatements(it);
+
+    EXPECT_EQ(5, db->Size());
+
+    rdf::Statement pattern1;
+    pattern1.setSubject(rdf::URI("http://example.com/s1"));
+    pattern1.setObject(rdf::URI("http://example.com/o1"));
+    auto it1 = db->GetStatements(pattern1.getMessage());
+    for (int i=0; i<3; i++) {
+        ASSERT_TRUE(it1->hasNext());
+        EXPECT_THAT(stmts, Contains(it1->next()));
+    }
+    EXPECT_FALSE(it1->hasNext());
+
+    rdf::Statement pattern2;
+    pattern2.setSubject(rdf::URI("http://example.com/s2"));
+    pattern2.setObject(rdf::URI("http://example.com/o2"));
+    auto it2 = db->GetStatements(pattern2.getMessage());
+    for (int i=0; i<2; i++) {
+        ASSERT_TRUE(it2->hasNext());
+        EXPECT_THAT(stmts, Contains(it2->next()));
+    }
+    EXPECT_FALSE(it2->hasNext());
+}
+
 
 }
 }

http://git-wip-us.apache.org/repos/asf/marmotta/blob/0064d335/libraries/ostrich/backend/util/iterator.h
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/util/iterator.h b/libraries/ostrich/backend/util/iterator.h
index 0d34a4b..8ba1497 100644
--- a/libraries/ostrich/backend/util/iterator.h
+++ b/libraries/ostrich/backend/util/iterator.h
@@ -194,7 +194,7 @@ class FilteringIterator : public CloseableIterator<T> {
     bool nextExists;
 
     void findNext() {
-        current_ = next_;
+        current_ = std::move(next_);
         nextExists = false;
 
         while (it->hasNext()) {


[24/50] [abbrv] marmotta git commit: Merge branch 'MARMOTTA-627' into develop

Posted by wi...@apache.org.
Merge branch 'MARMOTTA-627' into develop


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/808403d1
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/808403d1
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/808403d1

Branch: refs/heads/MARMOTTA-584
Commit: 808403d163079271dbc1db0dbf22e6faf0f1b924
Parents: 83be62b 6eb0973
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Thu Feb 11 14:41:24 2016 +0100
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Thu Feb 11 14:41:24 2016 +0100

----------------------------------------------------------------------
 .../builder/eval/ValueExpressionEvaluator.java  |  2 +-
 .../kiwi/sparql/test/KiWiSparqlTest.java        | 55 +++++++++++++++++++-
 2 files changed, 55 insertions(+), 2 deletions(-)
----------------------------------------------------------------------



[44/50] [abbrv] marmotta git commit: Merge branch 'develop' of https://git-wip-us.apache.org/repos/asf/marmotta into develop

Posted by wi...@apache.org.
Merge branch 'develop' of https://git-wip-us.apache.org/repos/asf/marmotta into develop


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/bfe58472
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/bfe58472
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/bfe58472

Branch: refs/heads/MARMOTTA-584
Commit: bfe5847255326338c49c80db23eb662649b15cdd
Parents: 01b2938 9779f36
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Mon Apr 25 09:01:56 2016 +0200
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Mon Apr 25 09:01:56 2016 +0200

----------------------------------------------------------------------
 .../sparql/optimizer/NativeFilterOptimizer.java | 198 +++++++++++++++++++
 .../sparql/sail/KiWiSparqlSailConnection.java   |   5 +-
 .../sparql/test/ComplexKiWiSparqlQueryTest.java |  14 ++
 3 files changed, 215 insertions(+), 2 deletions(-)
----------------------------------------------------------------------



[40/50] [abbrv] marmotta git commit: MARMOTTA-634: fixed cosmetics

Posted by wi...@apache.org.
MARMOTTA-634: fixed cosmetics


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/ff559ea4
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/ff559ea4
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/ff559ea4

Branch: refs/heads/MARMOTTA-584
Commit: ff559ea4f1ff1b2217d2796c263d2e33e2bb4bd0
Parents: aab258e
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Tue Apr 19 09:55:48 2016 +0200
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Tue Apr 19 09:55:48 2016 +0200

----------------------------------------------------------------------
 .../src/main/resources/web/admin/configuration.html           | 7 ++-----
 .../src/main/resources/web/admin/console.html                 | 2 +-
 .../src/main/resources/web/admin/database.html                | 2 +-
 3 files changed, 4 insertions(+), 7 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/ff559ea4/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/configuration.html
----------------------------------------------------------------------
diff --git a/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/configuration.html b/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/configuration.html
index 3957686..0b36d1c 100644
--- a/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/configuration.html
+++ b/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/configuration.html
@@ -16,11 +16,8 @@
   -->
 <html>
 <head>
-<title>Storage Backend: BigData</title>
-<script type="text/javascript">
-	var _SERVER_URL = "http://localhost:8080/LMF/";
-</script>
 <!--###BEGIN_HEAD###-->
+  <title>KiWi Configuration</title>
     <script type="text/javascript" src="../../webjars/jquery/1.8.2/jquery.min.js"></script>
     <script type="text/javascript" src="../../core/public/js/widgets/configurator/configurator.js"></script>
     <link rel="stylesheet" href="style.css" />
@@ -49,4 +46,4 @@
   </div>
   <!--###END_CONTENT###-->
 </body>
-</html>
\ No newline at end of file
+</html>

http://git-wip-us.apache.org/repos/asf/marmotta/blob/ff559ea4/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/console.html
----------------------------------------------------------------------
diff --git a/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/console.html b/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/console.html
index 39b541d..5d32d33 100644
--- a/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/console.html
+++ b/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/console.html
@@ -20,7 +20,7 @@
 <html>
 <head>
     <!--###BEGIN_HEAD###-->
-    <title>Core Module</title>
+    <title>KiWi Console</title>
     <!--###END_HEAD###-->
 </head>
 <body>

http://git-wip-us.apache.org/repos/asf/marmotta/blob/ff559ea4/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/database.html
----------------------------------------------------------------------
diff --git a/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/database.html b/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/database.html
index afa5287..aab3e05 100644
--- a/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/database.html
+++ b/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/database.html
@@ -17,7 +17,7 @@
 <html>
 <head>
 <!--###BEGIN_HEAD###-->
-    <title>Core Module Configuration</title>
+    <title>KiWi Database</title>
     <link type="text/css" rel="stylesheet" href="../../../../../../../marmotta-core/src/main/resources/web/public/js/widgets/configurator/style.css">
     <script type="text/javascript" src="../../webjars/jquery/1.8.2/jquery.min.js"></script>
     <script type="text/javascript" src="js/widgets/database.js"></script>


[04/50] [abbrv] marmotta git commit: refactor iterator implementations, they were broken

Posted by wi...@apache.org.
http://git-wip-us.apache.org/repos/asf/marmotta/blob/2e32da5d/libraries/ostrich/backend/test/gtest.h
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/test/gtest.h b/libraries/ostrich/backend/test/gtest.h
deleted file mode 100644
index 4f3804f..0000000
--- a/libraries/ostrich/backend/test/gtest.h
+++ /dev/null
@@ -1,20061 +0,0 @@
-// Copyright 2005, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-//
-// The Google C++ Testing Framework (Google Test)
-//
-// This header file defines the public API for Google Test.  It should be
-// included by any test program that uses Google Test.
-//
-// IMPORTANT NOTE: Due to limitation of the C++ language, we have to
-// leave some internal implementation details in this header file.
-// They are clearly marked by comments like this:
-//
-//   // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
-//
-// Such code is NOT meant to be used by a user directly, and is subject
-// to CHANGE WITHOUT NOTICE.  Therefore DO NOT DEPEND ON IT in a user
-// program!
-//
-// Acknowledgment: Google Test borrowed the idea of automatic test
-// registration from Barthelemy Dagenais' (barthelemy@prologique.com)
-// easyUnit framework.
-
-#ifndef GTEST_INCLUDE_GTEST_GTEST_H_
-#define GTEST_INCLUDE_GTEST_GTEST_H_
-
-#include <limits>
-#include <ostream>
-#include <vector>
-
-// Copyright 2005, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee)
-//
-// The Google C++ Testing Framework (Google Test)
-//
-// This header file declares functions and macros used internally by
-// Google Test.  They are subject to change without notice.
-
-#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
-
-// Copyright 2005, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Authors: wan@google.com (Zhanyong Wan)
-//
-// Low-level types and utilities for porting Google Test to various
-// platforms.  They are subject to change without notice.  DO NOT USE
-// THEM IN USER CODE.
-//
-// This file is fundamental to Google Test.  All other Google Test source
-// files are expected to #include this.  Therefore, it cannot #include
-// any other Google Test header.
-
-#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
-
-// The user can define the following macros in the build script to
-// control Google Test's behavior.  If the user doesn't define a macro
-// in this list, Google Test will define it.
-//
-//   GTEST_HAS_CLONE          - Define it to 1/0 to indicate that clone(2)
-//                              is/isn't available.
-//   GTEST_HAS_EXCEPTIONS     - Define it to 1/0 to indicate that exceptions
-//                              are enabled.
-//   GTEST_HAS_GLOBAL_STRING  - Define it to 1/0 to indicate that ::string
-//                              is/isn't available (some systems define
-//                              ::string, which is different to std::string).
-//   GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string
-//                              is/isn't available (some systems define
-//                              ::wstring, which is different to std::wstring).
-//   GTEST_HAS_POSIX_RE       - Define it to 1/0 to indicate that POSIX regular
-//                              expressions are/aren't available.
-//   GTEST_HAS_PTHREAD        - Define it to 1/0 to indicate that <pthread.h>
-//                              is/isn't available.
-//   GTEST_HAS_RTTI           - Define it to 1/0 to indicate that RTTI is/isn't
-//                              enabled.
-//   GTEST_HAS_STD_WSTRING    - Define it to 1/0 to indicate that
-//                              std::wstring does/doesn't work (Google Test can
-//                              be used where std::wstring is unavailable).
-//   GTEST_HAS_TR1_TUPLE      - Define it to 1/0 to indicate tr1::tuple
-//                              is/isn't available.
-//   GTEST_HAS_SEH            - Define it to 1/0 to indicate whether the
-//                              compiler supports Microsoft's "Structured
-//                              Exception Handling".
-//   GTEST_HAS_STREAM_REDIRECTION
-//                            - Define it to 1/0 to indicate whether the
-//                              platform supports I/O stream redirection using
-//                              dup() and dup2().
-//   GTEST_USE_OWN_TR1_TUPLE  - Define it to 1/0 to indicate whether Google
-//                              Test's own tr1 tuple implementation should be
-//                              used.  Unused when the user sets
-//                              GTEST_HAS_TR1_TUPLE to 0.
-//   GTEST_LANG_CXX11         - Define it to 1/0 to indicate that Google Test
-//                              is building in C++11/C++98 mode.
-//   GTEST_LINKED_AS_SHARED_LIBRARY
-//                            - Define to 1 when compiling tests that use
-//                              Google Test as a shared library (known as
-//                              DLL on Windows).
-//   GTEST_CREATE_SHARED_LIBRARY
-//                            - Define to 1 when compiling Google Test itself
-//                              as a shared library.
-
-// This header defines the following utilities:
-//
-// Macros indicating the current platform (defined to 1 if compiled on
-// the given platform; otherwise undefined):
-//   GTEST_OS_AIX      - IBM AIX
-//   GTEST_OS_CYGWIN   - Cygwin
-//   GTEST_OS_HPUX     - HP-UX
-//   GTEST_OS_LINUX    - Linux
-//     GTEST_OS_LINUX_ANDROID - Google Android
-//   GTEST_OS_MAC      - Mac OS X
-//     GTEST_OS_IOS    - iOS
-//       GTEST_OS_IOS_SIMULATOR - iOS simulator
-//   GTEST_OS_NACL     - Google Native Client (NaCl)
-//   GTEST_OS_OPENBSD  - OpenBSD
-//   GTEST_OS_QNX      - QNX
-//   GTEST_OS_SOLARIS  - Sun Solaris
-//   GTEST_OS_SYMBIAN  - Symbian
-//   GTEST_OS_WINDOWS  - Windows (Desktop, MinGW, or Mobile)
-//     GTEST_OS_WINDOWS_DESKTOP  - Windows Desktop
-//     GTEST_OS_WINDOWS_MINGW    - MinGW
-//     GTEST_OS_WINDOWS_MOBILE   - Windows Mobile
-//   GTEST_OS_ZOS      - z/OS
-//
-// Among the platforms, Cygwin, Linux, Max OS X, and Windows have the
-// most stable support.  Since core members of the Google Test project
-// don't have access to other platforms, support for them may be less
-// stable.  If you notice any problems on your platform, please notify
-// googletestframework@googlegroups.com (patches for fixing them are
-// even more welcome!).
-//
-// Note that it is possible that none of the GTEST_OS_* macros are defined.
-//
-// Macros indicating available Google Test features (defined to 1 if
-// the corresponding feature is supported; otherwise undefined):
-//   GTEST_HAS_COMBINE      - the Combine() function (for value-parameterized
-//                            tests)
-//   GTEST_HAS_DEATH_TEST   - death tests
-//   GTEST_HAS_PARAM_TEST   - value-parameterized tests
-//   GTEST_HAS_TYPED_TEST   - typed tests
-//   GTEST_HAS_TYPED_TEST_P - type-parameterized tests
-//   GTEST_USES_POSIX_RE    - enhanced POSIX regex is used. Do not confuse with
-//                            GTEST_HAS_POSIX_RE (see above) which users can
-//                            define themselves.
-//   GTEST_USES_SIMPLE_RE   - our own simple regex is used;
-//                            the above two are mutually exclusive.
-//   GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ().
-//
-// Macros for basic C++ coding:
-//   GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning.
-//   GTEST_ATTRIBUTE_UNUSED_  - declares that a class' instances or a
-//                              variable don't have to be used.
-//   GTEST_DISALLOW_ASSIGN_   - disables operator=.
-//   GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=.
-//   GTEST_MUST_USE_RESULT_   - declares that a function's result must be used.
-//
-// Synchronization:
-//   Mutex, MutexLock, ThreadLocal, GetThreadCount()
-//                  - synchronization primitives.
-//   GTEST_IS_THREADSAFE - defined to 1 to indicate that the above
-//                         synchronization primitives have real implementations
-//                         and Google Test is thread-safe; or 0 otherwise.
-//
-// Template meta programming:
-//   is_pointer     - as in TR1; needed on Symbian and IBM XL C/C++ only.
-//   IteratorTraits - partial implementation of std::iterator_traits, which
-//                    is not available in libCstd when compiled with Sun C++.
-//
-// Smart pointers:
-//   scoped_ptr     - as in TR2.
-//
-// Regular expressions:
-//   RE             - a simple regular expression class using the POSIX
-//                    Extended Regular Expression syntax on UNIX-like
-//                    platforms, or a reduced regular exception syntax on
-//                    other platforms, including Windows.
-//
-// Logging:
-//   GTEST_LOG_()   - logs messages at the specified severity level.
-//   LogToStderr()  - directs all log messages to stderr.
-//   FlushInfoLog() - flushes informational log messages.
-//
-// Stdout and stderr capturing:
-//   CaptureStdout()     - starts capturing stdout.
-//   GetCapturedStdout() - stops capturing stdout and returns the captured
-//                         string.
-//   CaptureStderr()     - starts capturing stderr.
-//   GetCapturedStderr() - stops capturing stderr and returns the captured
-//                         string.
-//
-// Integer types:
-//   TypeWithSize   - maps an integer to a int type.
-//   Int32, UInt32, Int64, UInt64, TimeInMillis
-//                  - integers of known sizes.
-//   BiggestInt     - the biggest signed integer type.
-//
-// Command-line utilities:
-//   GTEST_FLAG()       - references a flag.
-//   GTEST_DECLARE_*()  - declares a flag.
-//   GTEST_DEFINE_*()   - defines a flag.
-//   GetInjectableArgvs() - returns the command line as a vector of strings.
-//
-// Environment variable utilities:
-//   GetEnv()             - gets the value of an environment variable.
-//   BoolFromGTestEnv()   - parses a bool environment variable.
-//   Int32FromGTestEnv()  - parses an Int32 environment variable.
-//   StringFromGTestEnv() - parses a string environment variable.
-
-#include <ctype.h>   // for isspace, etc
-#include <stddef.h>  // for ptrdiff_t
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#ifndef _WIN32_WCE
-# include <sys/types.h>
-# include <sys/stat.h>
-#endif  // !_WIN32_WCE
-
-#if defined __APPLE__
-# include <AvailabilityMacros.h>
-# include <TargetConditionals.h>
-#endif
-
-#include <iostream>  // NOLINT
-#include <sstream>  // NOLINT
-#include <string>  // NOLINT
-
-#define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com"
-#define GTEST_FLAG_PREFIX_ "gtest_"
-#define GTEST_FLAG_PREFIX_DASH_ "gtest-"
-#define GTEST_FLAG_PREFIX_UPPER_ "GTEST_"
-#define GTEST_NAME_ "Google Test"
-#define GTEST_PROJECT_URL_ "http://code.google.com/p/googletest/"
-
-// Determines the version of gcc that is used to compile this.
-#ifdef __GNUC__
-// 40302 means version 4.3.2.
-# define GTEST_GCC_VER_ \
-    (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__)
-#endif  // __GNUC__
-
-// Determines the platform on which Google Test is compiled.
-#ifdef __CYGWIN__
-# define GTEST_OS_CYGWIN 1
-#elif defined __SYMBIAN32__
-# define GTEST_OS_SYMBIAN 1
-#elif defined _WIN32
-# define GTEST_OS_WINDOWS 1
-# ifdef _WIN32_WCE
-#  define GTEST_OS_WINDOWS_MOBILE 1
-# elif defined(__MINGW__) || defined(__MINGW32__)
-#  define GTEST_OS_WINDOWS_MINGW 1
-# else
-#  define GTEST_OS_WINDOWS_DESKTOP 1
-# endif  // _WIN32_WCE
-#elif defined __APPLE__
-# define GTEST_OS_MAC 1
-# if TARGET_OS_IPHONE
-#  define GTEST_OS_IOS 1
-#  if TARGET_IPHONE_SIMULATOR
-#   define GTEST_OS_IOS_SIMULATOR 1
-#  endif
-# endif
-#elif defined __linux__
-# define GTEST_OS_LINUX 1
-# if defined __ANDROID__
-#  define GTEST_OS_LINUX_ANDROID 1
-# endif
-#elif defined __MVS__
-# define GTEST_OS_ZOS 1
-#elif defined(__sun) && defined(__SVR4)
-# define GTEST_OS_SOLARIS 1
-#elif defined(_AIX)
-# define GTEST_OS_AIX 1
-#elif defined(__hpux)
-# define GTEST_OS_HPUX 1
-#elif defined __native_client__
-# define GTEST_OS_NACL 1
-#elif defined __OpenBSD__
-# define GTEST_OS_OPENBSD 1
-#elif defined __QNX__
-# define GTEST_OS_QNX 1
-#endif  // __CYGWIN__
-
-#ifndef GTEST_LANG_CXX11
-// gcc and clang define __GXX_EXPERIMENTAL_CXX0X__ when
-// -std={c,gnu}++{0x,11} is passed.  The C++11 standard specifies a
-// value for __cplusplus, and recent versions of clang, gcc, and
-// probably other compilers set that too in C++11 mode.
-# if __GXX_EXPERIMENTAL_CXX0X__ || __cplusplus >= 201103L
-// Compiling in at least C++11 mode.
-#  define GTEST_LANG_CXX11 1
-# else
-#  define GTEST_LANG_CXX11 0
-# endif
-#endif
-
-// Brings in definitions for functions used in the testing::internal::posix
-// namespace (read, write, close, chdir, isatty, stat). We do not currently
-// use them on Windows Mobile.
-#if !GTEST_OS_WINDOWS
-// This assumes that non-Windows OSes provide unistd.h. For OSes where this
-// is not the case, we need to include headers that provide the functions
-// mentioned above.
-# include <unistd.h>
-# include <strings.h>
-#elif !GTEST_OS_WINDOWS_MOBILE
-# include <direct.h>
-# include <io.h>
-#endif
-
-#if GTEST_OS_LINUX_ANDROID
-// Used to define __ANDROID_API__ matching the target NDK API level.
-#  include <android/api-level.h>  // NOLINT
-#endif
-
-// Defines this to true iff Google Test can use POSIX regular expressions.
-#ifndef GTEST_HAS_POSIX_RE
-# if GTEST_OS_LINUX_ANDROID
-// On Android, <regex.h> is only available starting with Gingerbread.
-#  define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9)
-# else
-#  define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS)
-# endif
-#endif
-
-#if GTEST_HAS_POSIX_RE
-
-// On some platforms, <regex.h> needs someone to define size_t, and
-// won't compile otherwise.  We can #include it here as we already
-// included <stdlib.h>, which is guaranteed to define size_t through
-// <stddef.h>.
-# include <regex.h>  // NOLINT
-
-# define GTEST_USES_POSIX_RE 1
-
-#elif GTEST_OS_WINDOWS
-
-// <regex.h> is not available on Windows.  Use our own simple regex
-// implementation instead.
-# define GTEST_USES_SIMPLE_RE 1
-
-#else
-
-// <regex.h> may not be available on this platform.  Use our own
-// simple regex implementation instead.
-# define GTEST_USES_SIMPLE_RE 1
-
-#endif  // GTEST_HAS_POSIX_RE
-
-#ifndef GTEST_HAS_EXCEPTIONS
-// The user didn't tell us whether exceptions are enabled, so we need
-// to figure it out.
-# if defined(_MSC_VER) || defined(__BORLANDC__)
-// MSVC's and C++Builder's implementations of the STL use the _HAS_EXCEPTIONS
-// macro to enable exceptions, so we'll do the same.
-// Assumes that exceptions are enabled by default.
-#  ifndef _HAS_EXCEPTIONS
-#   define _HAS_EXCEPTIONS 1
-#  endif  // _HAS_EXCEPTIONS
-#  define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS
-# elif defined(__GNUC__) && __EXCEPTIONS
-// gcc defines __EXCEPTIONS to 1 iff exceptions are enabled.
-#  define GTEST_HAS_EXCEPTIONS 1
-# elif defined(__SUNPRO_CC)
-// Sun Pro CC supports exceptions.  However, there is no compile-time way of
-// detecting whether they are enabled or not.  Therefore, we assume that
-// they are enabled unless the user tells us otherwise.
-#  define GTEST_HAS_EXCEPTIONS 1
-# elif defined(__IBMCPP__) && __EXCEPTIONS
-// xlC defines __EXCEPTIONS to 1 iff exceptions are enabled.
-#  define GTEST_HAS_EXCEPTIONS 1
-# elif defined(__HP_aCC)
-// Exception handling is in effect by default in HP aCC compiler. It has to
-// be turned of by +noeh compiler option if desired.
-#  define GTEST_HAS_EXCEPTIONS 1
-# else
-// For other compilers, we assume exceptions are disabled to be
-// conservative.
-#  define GTEST_HAS_EXCEPTIONS 0
-# endif  // defined(_MSC_VER) || defined(__BORLANDC__)
-#endif  // GTEST_HAS_EXCEPTIONS
-
-#if !defined(GTEST_HAS_STD_STRING)
-// Even though we don't use this macro any longer, we keep it in case
-// some clients still depend on it.
-# define GTEST_HAS_STD_STRING 1
-#elif !GTEST_HAS_STD_STRING
-// The user told us that ::std::string isn't available.
-# error "Google Test cannot be used where ::std::string isn't available."
-#endif  // !defined(GTEST_HAS_STD_STRING)
-
-#ifndef GTEST_HAS_GLOBAL_STRING
-// The user didn't tell us whether ::string is available, so we need
-// to figure it out.
-
-# define GTEST_HAS_GLOBAL_STRING 0
-
-#endif  // GTEST_HAS_GLOBAL_STRING
-
-#ifndef GTEST_HAS_STD_WSTRING
-// The user didn't tell us whether ::std::wstring is available, so we need
-// to figure it out.
-// TODO(wan@google.com): uses autoconf to detect whether ::std::wstring
-//   is available.
-
-// Cygwin 1.7 and below doesn't support ::std::wstring.
-// Solaris' libc++ doesn't support it either.  Android has
-// no support for it at least as recent as Froyo (2.2).
-# define GTEST_HAS_STD_WSTRING \
-    (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS))
-
-#endif  // GTEST_HAS_STD_WSTRING
-
-#ifndef GTEST_HAS_GLOBAL_WSTRING
-// The user didn't tell us whether ::wstring is available, so we need
-// to figure it out.
-# define GTEST_HAS_GLOBAL_WSTRING \
-    (GTEST_HAS_STD_WSTRING && GTEST_HAS_GLOBAL_STRING)
-#endif  // GTEST_HAS_GLOBAL_WSTRING
-
-// Determines whether RTTI is available.
-#ifndef GTEST_HAS_RTTI
-// The user didn't tell us whether RTTI is enabled, so we need to
-// figure it out.
-
-# ifdef _MSC_VER
-
-#  ifdef _CPPRTTI  // MSVC defines this macro iff RTTI is enabled.
-#   define GTEST_HAS_RTTI 1
-#  else
-#   define GTEST_HAS_RTTI 0
-#  endif
-
-// Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled.
-# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302)
-
-#  ifdef __GXX_RTTI
-// When building against STLport with the Android NDK and with
-// -frtti -fno-exceptions, the build fails at link time with undefined
-// references to __cxa_bad_typeid. Note sure if STL or toolchain bug,
-// so disable RTTI when detected.
-#   if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \
-       !defined(__EXCEPTIONS)
-#    define GTEST_HAS_RTTI 0
-#   else
-#    define GTEST_HAS_RTTI 1
-#   endif  // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS
-#  else
-#   define GTEST_HAS_RTTI 0
-#  endif  // __GXX_RTTI
-
-// Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends
-// using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the
-// first version with C++ support.
-# elif defined(__clang__)
-
-#  define GTEST_HAS_RTTI __has_feature(cxx_rtti)
-
-// Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if
-// both the typeid and dynamic_cast features are present.
-# elif defined(__IBMCPP__) && (__IBMCPP__ >= 900)
-
-#  ifdef __RTTI_ALL__
-#   define GTEST_HAS_RTTI 1
-#  else
-#   define GTEST_HAS_RTTI 0
-#  endif
-
-# else
-
-// For all other compilers, we assume RTTI is enabled.
-#  define GTEST_HAS_RTTI 1
-
-# endif  // _MSC_VER
-
-#endif  // GTEST_HAS_RTTI
-
-// It's this header's responsibility to #include <typeinfo> when RTTI
-// is enabled.
-#if GTEST_HAS_RTTI
-# include <typeinfo>
-#endif
-
-// Determines whether Google Test can use the pthreads library.
-#ifndef GTEST_HAS_PTHREAD
-// The user didn't tell us explicitly, so we assume pthreads support is
-// available on Linux and Mac.
-//
-// To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0
-// to your compiler flags.
-# define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX \
-    || GTEST_OS_QNX)
-#endif  // GTEST_HAS_PTHREAD
-
-#if GTEST_HAS_PTHREAD
-// gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is
-// true.
-# include <pthread.h>  // NOLINT
-
-// For timespec and nanosleep, used below.
-# include <time.h>  // NOLINT
-#endif
-
-// Determines whether Google Test can use tr1/tuple.  You can define
-// this macro to 0 to prevent Google Test from using tuple (any
-// feature depending on tuple with be disabled in this mode).
-#ifndef GTEST_HAS_TR1_TUPLE
-# if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR)
-// STLport, provided with the Android NDK, has neither <tr1/tuple> or <tuple>.
-#  define GTEST_HAS_TR1_TUPLE 0
-# else
-// The user didn't tell us not to do it, so we assume it's OK.
-#  define GTEST_HAS_TR1_TUPLE 1
-# endif
-#endif  // GTEST_HAS_TR1_TUPLE
-
-// Determines whether Google Test's own tr1 tuple implementation
-// should be used.
-#ifndef GTEST_USE_OWN_TR1_TUPLE
-// The user didn't tell us, so we need to figure it out.
-
-// We use our own TR1 tuple if we aren't sure the user has an
-// implementation of it already.  At this time, libstdc++ 4.0.0+ and
-// MSVC 2010 are the only mainstream standard libraries that come
-// with a TR1 tuple implementation.  NVIDIA's CUDA NVCC compiler
-// pretends to be GCC by defining __GNUC__ and friends, but cannot
-// compile GCC's tuple implementation.  MSVC 2008 (9.0) provides TR1
-// tuple in a 323 MB Feature Pack download, which we cannot assume the
-// user has.  QNX's QCC compiler is a modified GCC but it doesn't
-// support TR1 tuple.  libc++ only provides std::tuple, in C++11 mode,
-// and it can be used with some compilers that define __GNUC__.
-# if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000) \
-      && !GTEST_OS_QNX && !defined(_LIBCPP_VERSION)) || _MSC_VER >= 1600
-#  define GTEST_ENV_HAS_TR1_TUPLE_ 1
-# endif
-
-// C++11 specifies that <tuple> provides std::tuple. Use that if gtest is used
-// in C++11 mode and libstdc++ isn't very old (binaries targeting OS X 10.6
-// can build with clang but need to use gcc4.2's libstdc++).
-# if GTEST_LANG_CXX11 && (!defined(__GLIBCXX__) || __GLIBCXX__ > 20110325)
-#  define GTEST_ENV_HAS_STD_TUPLE_ 1
-# endif
-
-# if GTEST_ENV_HAS_TR1_TUPLE_ || GTEST_ENV_HAS_STD_TUPLE_
-#  define GTEST_USE_OWN_TR1_TUPLE 0
-# else
-#  define GTEST_USE_OWN_TR1_TUPLE 1
-# endif
-
-#endif  // GTEST_USE_OWN_TR1_TUPLE
-
-// To avoid conditional compilation everywhere, we make it
-// gtest-port.h's responsibility to #include the header implementing
-// tr1/tuple.
-#if GTEST_HAS_TR1_TUPLE
-
-# if GTEST_USE_OWN_TR1_TUPLE
-// This file was GENERATED by command:
-//     pump.py gtest-tuple.h.pump
-// DO NOT EDIT BY HAND!!!
-
-// Copyright 2009 Google Inc.
-// All Rights Reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-
-// Implements a subset of TR1 tuple needed by Google Test and Google Mock.
-
-#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_
-
-#include <utility>  // For ::std::pair.
-
-// The compiler used in Symbian has a bug that prevents us from declaring the
-// tuple template as a friend (it complains that tuple is redefined).  This
-// hack bypasses the bug by declaring the members that should otherwise be
-// private as public.
-// Sun Studio versions < 12 also have the above bug.
-#if defined(__SYMBIAN32__) || (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590)
-# define GTEST_DECLARE_TUPLE_AS_FRIEND_ public:
-#else
-# define GTEST_DECLARE_TUPLE_AS_FRIEND_ \
-    template <GTEST_10_TYPENAMES_(U)> friend class tuple; \
-   private:
-#endif
-
-// GTEST_n_TUPLE_(T) is the type of an n-tuple.
-#define GTEST_0_TUPLE_(T) tuple<>
-#define GTEST_1_TUPLE_(T) tuple<T##0, void, void, void, void, void, void, \
-    void, void, void>
-#define GTEST_2_TUPLE_(T) tuple<T##0, T##1, void, void, void, void, void, \
-    void, void, void>
-#define GTEST_3_TUPLE_(T) tuple<T##0, T##1, T##2, void, void, void, void, \
-    void, void, void>
-#define GTEST_4_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, void, void, void, \
-    void, void, void>
-#define GTEST_5_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, void, void, \
-    void, void, void>
-#define GTEST_6_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, T##5, void, \
-    void, void, void>
-#define GTEST_7_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, T##5, T##6, \
-    void, void, void>
-#define GTEST_8_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, T##5, T##6, \
-    T##7, void, void>
-#define GTEST_9_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, T##5, T##6, \
-    T##7, T##8, void>
-#define GTEST_10_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, T##5, T##6, \
-    T##7, T##8, T##9>
-
-// GTEST_n_TYPENAMES_(T) declares a list of n typenames.
-#define GTEST_0_TYPENAMES_(T)
-#define GTEST_1_TYPENAMES_(T) typename T##0
-#define GTEST_2_TYPENAMES_(T) typename T##0, typename T##1
-#define GTEST_3_TYPENAMES_(T) typename T##0, typename T##1, typename T##2
-#define GTEST_4_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \
-    typename T##3
-#define GTEST_5_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \
-    typename T##3, typename T##4
-#define GTEST_6_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \
-    typename T##3, typename T##4, typename T##5
-#define GTEST_7_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \
-    typename T##3, typename T##4, typename T##5, typename T##6
-#define GTEST_8_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \
-    typename T##3, typename T##4, typename T##5, typename T##6, typename T##7
-#define GTEST_9_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \
-    typename T##3, typename T##4, typename T##5, typename T##6, \
-    typename T##7, typename T##8
-#define GTEST_10_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \
-    typename T##3, typename T##4, typename T##5, typename T##6, \
-    typename T##7, typename T##8, typename T##9
-
-// In theory, defining stuff in the ::std namespace is undefined
-// behavior.  We can do this as we are playing the role of a standard
-// library vendor.
-namespace std {
-namespace tr1 {
-
-template <typename T0 = void, typename T1 = void, typename T2 = void,
-    typename T3 = void, typename T4 = void, typename T5 = void,
-    typename T6 = void, typename T7 = void, typename T8 = void,
-    typename T9 = void>
-class tuple;
-
-// Anything in namespace gtest_internal is Google Test's INTERNAL
-// IMPLEMENTATION DETAIL and MUST NOT BE USED DIRECTLY in user code.
-namespace gtest_internal {
-
-// ByRef<T>::type is T if T is a reference; otherwise it's const T&.
-template <typename T>
-struct ByRef { typedef const T& type; };  // NOLINT
-template <typename T>
-struct ByRef<T&> { typedef T& type; };  // NOLINT
-
-// A handy wrapper for ByRef.
-#define GTEST_BY_REF_(T) typename ::std::tr1::gtest_internal::ByRef<T>::type
-
-// AddRef<T>::type is T if T is a reference; otherwise it's T&.  This
-// is the same as tr1::add_reference<T>::type.
-template <typename T>
-struct AddRef { typedef T& type; };  // NOLINT
-template <typename T>
-struct AddRef<T&> { typedef T& type; };  // NOLINT
-
-// A handy wrapper for AddRef.
-#define GTEST_ADD_REF_(T) typename ::std::tr1::gtest_internal::AddRef<T>::type
-
-// A helper for implementing get<k>().
-template <int k> class Get;
-
-// A helper for implementing tuple_element<k, T>.  kIndexValid is true
-// iff k < the number of fields in tuple type T.
-template <bool kIndexValid, int kIndex, class Tuple>
-struct TupleElement;
-
-template <GTEST_10_TYPENAMES_(T)>
-struct TupleElement<true, 0, GTEST_10_TUPLE_(T) > {
-  typedef T0 type;
-};
-
-template <GTEST_10_TYPENAMES_(T)>
-struct TupleElement<true, 1, GTEST_10_TUPLE_(T) > {
-  typedef T1 type;
-};
-
-template <GTEST_10_TYPENAMES_(T)>
-struct TupleElement<true, 2, GTEST_10_TUPLE_(T) > {
-  typedef T2 type;
-};
-
-template <GTEST_10_TYPENAMES_(T)>
-struct TupleElement<true, 3, GTEST_10_TUPLE_(T) > {
-  typedef T3 type;
-};
-
-template <GTEST_10_TYPENAMES_(T)>
-struct TupleElement<true, 4, GTEST_10_TUPLE_(T) > {
-  typedef T4 type;
-};
-
-template <GTEST_10_TYPENAMES_(T)>
-struct TupleElement<true, 5, GTEST_10_TUPLE_(T) > {
-  typedef T5 type;
-};
-
-template <GTEST_10_TYPENAMES_(T)>
-struct TupleElement<true, 6, GTEST_10_TUPLE_(T) > {
-  typedef T6 type;
-};
-
-template <GTEST_10_TYPENAMES_(T)>
-struct TupleElement<true, 7, GTEST_10_TUPLE_(T) > {
-  typedef T7 type;
-};
-
-template <GTEST_10_TYPENAMES_(T)>
-struct TupleElement<true, 8, GTEST_10_TUPLE_(T) > {
-  typedef T8 type;
-};
-
-template <GTEST_10_TYPENAMES_(T)>
-struct TupleElement<true, 9, GTEST_10_TUPLE_(T) > {
-  typedef T9 type;
-};
-
-}  // namespace gtest_internal
-
-template <>
-class tuple<> {
- public:
-  tuple() {}
-  tuple(const tuple& /* t */)  {}
-  tuple& operator=(const tuple& /* t */) { return *this; }
-};
-
-template <GTEST_1_TYPENAMES_(T)>
-class GTEST_1_TUPLE_(T) {
- public:
-  template <int k> friend class gtest_internal::Get;
-
-  tuple() : f0_() {}
-
-  explicit tuple(GTEST_BY_REF_(T0) f0) : f0_(f0) {}
-
-  tuple(const tuple& t) : f0_(t.f0_) {}
-
-  template <GTEST_1_TYPENAMES_(U)>
-  tuple(const GTEST_1_TUPLE_(U)& t) : f0_(t.f0_) {}
-
-  tuple& operator=(const tuple& t) { return CopyFrom(t); }
-
-  template <GTEST_1_TYPENAMES_(U)>
-  tuple& operator=(const GTEST_1_TUPLE_(U)& t) {
-    return CopyFrom(t);
-  }
-
-  GTEST_DECLARE_TUPLE_AS_FRIEND_
-
-  template <GTEST_1_TYPENAMES_(U)>
-  tuple& CopyFrom(const GTEST_1_TUPLE_(U)& t) {
-    f0_ = t.f0_;
-    return *this;
-  }
-
-  T0 f0_;
-};
-
-template <GTEST_2_TYPENAMES_(T)>
-class GTEST_2_TUPLE_(T) {
- public:
-  template <int k> friend class gtest_internal::Get;
-
-  tuple() : f0_(), f1_() {}
-
-  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1) : f0_(f0),
-      f1_(f1) {}
-
-  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_) {}
-
-  template <GTEST_2_TYPENAMES_(U)>
-  tuple(const GTEST_2_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_) {}
-  template <typename U0, typename U1>
-  tuple(const ::std::pair<U0, U1>& p) : f0_(p.first), f1_(p.second) {}
-
-  tuple& operator=(const tuple& t) { return CopyFrom(t); }
-
-  template <GTEST_2_TYPENAMES_(U)>
-  tuple& operator=(const GTEST_2_TUPLE_(U)& t) {
-    return CopyFrom(t);
-  }
-  template <typename U0, typename U1>
-  tuple& operator=(const ::std::pair<U0, U1>& p) {
-    f0_ = p.first;
-    f1_ = p.second;
-    return *this;
-  }
-
-  GTEST_DECLARE_TUPLE_AS_FRIEND_
-
-  template <GTEST_2_TYPENAMES_(U)>
-  tuple& CopyFrom(const GTEST_2_TUPLE_(U)& t) {
-    f0_ = t.f0_;
-    f1_ = t.f1_;
-    return *this;
-  }
-
-  T0 f0_;
-  T1 f1_;
-};
-
-template <GTEST_3_TYPENAMES_(T)>
-class GTEST_3_TUPLE_(T) {
- public:
-  template <int k> friend class gtest_internal::Get;
-
-  tuple() : f0_(), f1_(), f2_() {}
-
-  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
-      GTEST_BY_REF_(T2) f2) : f0_(f0), f1_(f1), f2_(f2) {}
-
-  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {}
-
-  template <GTEST_3_TYPENAMES_(U)>
-  tuple(const GTEST_3_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {}
-
-  tuple& operator=(const tuple& t) { return CopyFrom(t); }
-
-  template <GTEST_3_TYPENAMES_(U)>
-  tuple& operator=(const GTEST_3_TUPLE_(U)& t) {
-    return CopyFrom(t);
-  }
-
-  GTEST_DECLARE_TUPLE_AS_FRIEND_
-
-  template <GTEST_3_TYPENAMES_(U)>
-  tuple& CopyFrom(const GTEST_3_TUPLE_(U)& t) {
-    f0_ = t.f0_;
-    f1_ = t.f1_;
-    f2_ = t.f2_;
-    return *this;
-  }
-
-  T0 f0_;
-  T1 f1_;
-  T2 f2_;
-};
-
-template <GTEST_4_TYPENAMES_(T)>
-class GTEST_4_TUPLE_(T) {
- public:
-  template <int k> friend class gtest_internal::Get;
-
-  tuple() : f0_(), f1_(), f2_(), f3_() {}
-
-  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
-      GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3) : f0_(f0), f1_(f1), f2_(f2),
-      f3_(f3) {}
-
-  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_) {}
-
-  template <GTEST_4_TYPENAMES_(U)>
-  tuple(const GTEST_4_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_),
-      f3_(t.f3_) {}
-
-  tuple& operator=(const tuple& t) { return CopyFrom(t); }
-
-  template <GTEST_4_TYPENAMES_(U)>
-  tuple& operator=(const GTEST_4_TUPLE_(U)& t) {
-    return CopyFrom(t);
-  }
-
-  GTEST_DECLARE_TUPLE_AS_FRIEND_
-
-  template <GTEST_4_TYPENAMES_(U)>
-  tuple& CopyFrom(const GTEST_4_TUPLE_(U)& t) {
-    f0_ = t.f0_;
-    f1_ = t.f1_;
-    f2_ = t.f2_;
-    f3_ = t.f3_;
-    return *this;
-  }
-
-  T0 f0_;
-  T1 f1_;
-  T2 f2_;
-  T3 f3_;
-};
-
-template <GTEST_5_TYPENAMES_(T)>
-class GTEST_5_TUPLE_(T) {
- public:
-  template <int k> friend class gtest_internal::Get;
-
-  tuple() : f0_(), f1_(), f2_(), f3_(), f4_() {}
-
-  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
-      GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3,
-      GTEST_BY_REF_(T4) f4) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4) {}
-
-  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_),
-      f4_(t.f4_) {}
-
-  template <GTEST_5_TYPENAMES_(U)>
-  tuple(const GTEST_5_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_),
-      f3_(t.f3_), f4_(t.f4_) {}
-
-  tuple& operator=(const tuple& t) { return CopyFrom(t); }
-
-  template <GTEST_5_TYPENAMES_(U)>
-  tuple& operator=(const GTEST_5_TUPLE_(U)& t) {
-    return CopyFrom(t);
-  }
-
-  GTEST_DECLARE_TUPLE_AS_FRIEND_
-
-  template <GTEST_5_TYPENAMES_(U)>
-  tuple& CopyFrom(const GTEST_5_TUPLE_(U)& t) {
-    f0_ = t.f0_;
-    f1_ = t.f1_;
-    f2_ = t.f2_;
-    f3_ = t.f3_;
-    f4_ = t.f4_;
-    return *this;
-  }
-
-  T0 f0_;
-  T1 f1_;
-  T2 f2_;
-  T3 f3_;
-  T4 f4_;
-};
-
-template <GTEST_6_TYPENAMES_(T)>
-class GTEST_6_TUPLE_(T) {
- public:
-  template <int k> friend class gtest_internal::Get;
-
-  tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_() {}
-
-  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
-      GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4,
-      GTEST_BY_REF_(T5) f5) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4),
-      f5_(f5) {}
-
-  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_),
-      f4_(t.f4_), f5_(t.f5_) {}
-
-  template <GTEST_6_TYPENAMES_(U)>
-  tuple(const GTEST_6_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_),
-      f3_(t.f3_), f4_(t.f4_), f5_(t.f5_) {}
-
-  tuple& operator=(const tuple& t) { return CopyFrom(t); }
-
-  template <GTEST_6_TYPENAMES_(U)>
-  tuple& operator=(const GTEST_6_TUPLE_(U)& t) {
-    return CopyFrom(t);
-  }
-
-  GTEST_DECLARE_TUPLE_AS_FRIEND_
-
-  template <GTEST_6_TYPENAMES_(U)>
-  tuple& CopyFrom(const GTEST_6_TUPLE_(U)& t) {
-    f0_ = t.f0_;
-    f1_ = t.f1_;
-    f2_ = t.f2_;
-    f3_ = t.f3_;
-    f4_ = t.f4_;
-    f5_ = t.f5_;
-    return *this;
-  }
-
-  T0 f0_;
-  T1 f1_;
-  T2 f2_;
-  T3 f3_;
-  T4 f4_;
-  T5 f5_;
-};
-
-template <GTEST_7_TYPENAMES_(T)>
-class GTEST_7_TUPLE_(T) {
- public:
-  template <int k> friend class gtest_internal::Get;
-
-  tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_() {}
-
-  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
-      GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4,
-      GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6) : f0_(f0), f1_(f1), f2_(f2),
-      f3_(f3), f4_(f4), f5_(f5), f6_(f6) {}
-
-  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_),
-      f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {}
-
-  template <GTEST_7_TYPENAMES_(U)>
-  tuple(const GTEST_7_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_),
-      f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {}
-
-  tuple& operator=(const tuple& t) { return CopyFrom(t); }
-
-  template <GTEST_7_TYPENAMES_(U)>
-  tuple& operator=(const GTEST_7_TUPLE_(U)& t) {
-    return CopyFrom(t);
-  }
-
-  GTEST_DECLARE_TUPLE_AS_FRIEND_
-
-  template <GTEST_7_TYPENAMES_(U)>
-  tuple& CopyFrom(const GTEST_7_TUPLE_(U)& t) {
-    f0_ = t.f0_;
-    f1_ = t.f1_;
-    f2_ = t.f2_;
-    f3_ = t.f3_;
-    f4_ = t.f4_;
-    f5_ = t.f5_;
-    f6_ = t.f6_;
-    return *this;
-  }
-
-  T0 f0_;
-  T1 f1_;
-  T2 f2_;
-  T3 f3_;
-  T4 f4_;
-  T5 f5_;
-  T6 f6_;
-};
-
-template <GTEST_8_TYPENAMES_(T)>
-class GTEST_8_TUPLE_(T) {
- public:
-  template <int k> friend class gtest_internal::Get;
-
-  tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_() {}
-
-  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
-      GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4,
-      GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6,
-      GTEST_BY_REF_(T7) f7) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4),
-      f5_(f5), f6_(f6), f7_(f7) {}
-
-  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_),
-      f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {}
-
-  template <GTEST_8_TYPENAMES_(U)>
-  tuple(const GTEST_8_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_),
-      f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {}
-
-  tuple& operator=(const tuple& t) { return CopyFrom(t); }
-
-  template <GTEST_8_TYPENAMES_(U)>
-  tuple& operator=(const GTEST_8_TUPLE_(U)& t) {
-    return CopyFrom(t);
-  }
-
-  GTEST_DECLARE_TUPLE_AS_FRIEND_
-
-  template <GTEST_8_TYPENAMES_(U)>
-  tuple& CopyFrom(const GTEST_8_TUPLE_(U)& t) {
-    f0_ = t.f0_;
-    f1_ = t.f1_;
-    f2_ = t.f2_;
-    f3_ = t.f3_;
-    f4_ = t.f4_;
-    f5_ = t.f5_;
-    f6_ = t.f6_;
-    f7_ = t.f7_;
-    return *this;
-  }
-
-  T0 f0_;
-  T1 f1_;
-  T2 f2_;
-  T3 f3_;
-  T4 f4_;
-  T5 f5_;
-  T6 f6_;
-  T7 f7_;
-};
-
-template <GTEST_9_TYPENAMES_(T)>
-class GTEST_9_TUPLE_(T) {
- public:
-  template <int k> friend class gtest_internal::Get;
-
-  tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_() {}
-
-  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
-      GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4,
-      GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7,
-      GTEST_BY_REF_(T8) f8) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4),
-      f5_(f5), f6_(f6), f7_(f7), f8_(f8) {}
-
-  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_),
-      f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {}
-
-  template <GTEST_9_TYPENAMES_(U)>
-  tuple(const GTEST_9_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_),
-      f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {}
-
-  tuple& operator=(const tuple& t) { return CopyFrom(t); }
-
-  template <GTEST_9_TYPENAMES_(U)>
-  tuple& operator=(const GTEST_9_TUPLE_(U)& t) {
-    return CopyFrom(t);
-  }
-
-  GTEST_DECLARE_TUPLE_AS_FRIEND_
-
-  template <GTEST_9_TYPENAMES_(U)>
-  tuple& CopyFrom(const GTEST_9_TUPLE_(U)& t) {
-    f0_ = t.f0_;
-    f1_ = t.f1_;
-    f2_ = t.f2_;
-    f3_ = t.f3_;
-    f4_ = t.f4_;
-    f5_ = t.f5_;
-    f6_ = t.f6_;
-    f7_ = t.f7_;
-    f8_ = t.f8_;
-    return *this;
-  }
-
-  T0 f0_;
-  T1 f1_;
-  T2 f2_;
-  T3 f3_;
-  T4 f4_;
-  T5 f5_;
-  T6 f6_;
-  T7 f7_;
-  T8 f8_;
-};
-
-template <GTEST_10_TYPENAMES_(T)>
-class tuple {
- public:
-  template <int k> friend class gtest_internal::Get;
-
-  tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_(),
-      f9_() {}
-
-  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
-      GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4,
-      GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7,
-      GTEST_BY_REF_(T8) f8, GTEST_BY_REF_(T9) f9) : f0_(f0), f1_(f1), f2_(f2),
-      f3_(f3), f4_(f4), f5_(f5), f6_(f6), f7_(f7), f8_(f8), f9_(f9) {}
-
-  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_),
-      f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_), f9_(t.f9_) {}
-
-  template <GTEST_10_TYPENAMES_(U)>
-  tuple(const GTEST_10_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_),
-      f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_),
-      f9_(t.f9_) {}
-
-  tuple& operator=(const tuple& t) { return CopyFrom(t); }
-
-  template <GTEST_10_TYPENAMES_(U)>
-  tuple& operator=(const GTEST_10_TUPLE_(U)& t) {
-    return CopyFrom(t);
-  }
-
-  GTEST_DECLARE_TUPLE_AS_FRIEND_
-
-  template <GTEST_10_TYPENAMES_(U)>
-  tuple& CopyFrom(const GTEST_10_TUPLE_(U)& t) {
-    f0_ = t.f0_;
-    f1_ = t.f1_;
-    f2_ = t.f2_;
-    f3_ = t.f3_;
-    f4_ = t.f4_;
-    f5_ = t.f5_;
-    f6_ = t.f6_;
-    f7_ = t.f7_;
-    f8_ = t.f8_;
-    f9_ = t.f9_;
-    return *this;
-  }
-
-  T0 f0_;
-  T1 f1_;
-  T2 f2_;
-  T3 f3_;
-  T4 f4_;
-  T5 f5_;
-  T6 f6_;
-  T7 f7_;
-  T8 f8_;
-  T9 f9_;
-};
-
-// 6.1.3.2 Tuple creation functions.
-
-// Known limitations: we don't support passing an
-// std::tr1::reference_wrapper<T> to make_tuple().  And we don't
-// implement tie().
-
-inline tuple<> make_tuple() { return tuple<>(); }
-
-template <GTEST_1_TYPENAMES_(T)>
-inline GTEST_1_TUPLE_(T) make_tuple(const T0& f0) {
-  return GTEST_1_TUPLE_(T)(f0);
-}
-
-template <GTEST_2_TYPENAMES_(T)>
-inline GTEST_2_TUPLE_(T) make_tuple(const T0& f0, const T1& f1) {
-  return GTEST_2_TUPLE_(T)(f0, f1);
-}
-
-template <GTEST_3_TYPENAMES_(T)>
-inline GTEST_3_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2) {
-  return GTEST_3_TUPLE_(T)(f0, f1, f2);
-}
-
-template <GTEST_4_TYPENAMES_(T)>
-inline GTEST_4_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
-    const T3& f3) {
-  return GTEST_4_TUPLE_(T)(f0, f1, f2, f3);
-}
-
-template <GTEST_5_TYPENAMES_(T)>
-inline GTEST_5_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
-    const T3& f3, const T4& f4) {
-  return GTEST_5_TUPLE_(T)(f0, f1, f2, f3, f4);
-}
-
-template <GTEST_6_TYPENAMES_(T)>
-inline GTEST_6_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
-    const T3& f3, const T4& f4, const T5& f5) {
-  return GTEST_6_TUPLE_(T)(f0, f1, f2, f3, f4, f5);
-}
-
-template <GTEST_7_TYPENAMES_(T)>
-inline GTEST_7_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
-    const T3& f3, const T4& f4, const T5& f5, const T6& f6) {
-  return GTEST_7_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6);
-}
-
-template <GTEST_8_TYPENAMES_(T)>
-inline GTEST_8_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
-    const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7) {
-  return GTEST_8_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7);
-}
-
-template <GTEST_9_TYPENAMES_(T)>
-inline GTEST_9_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
-    const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7,
-    const T8& f8) {
-  return GTEST_9_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8);
-}
-
-template <GTEST_10_TYPENAMES_(T)>
-inline GTEST_10_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
-    const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7,
-    const T8& f8, const T9& f9) {
-  return GTEST_10_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8, f9);
-}
-
-// 6.1.3.3 Tuple helper classes.
-
-template <typename Tuple> struct tuple_size;
-
-template <GTEST_0_TYPENAMES_(T)>
-struct tuple_size<GTEST_0_TUPLE_(T) > {
-  static const int value = 0;
-};
-
-template <GTEST_1_TYPENAMES_(T)>
-struct tuple_size<GTEST_1_TUPLE_(T) > {
-  static const int value = 1;
-};
-
-template <GTEST_2_TYPENAMES_(T)>
-struct tuple_size<GTEST_2_TUPLE_(T) > {
-  static const int value = 2;
-};
-
-template <GTEST_3_TYPENAMES_(T)>
-struct tuple_size<GTEST_3_TUPLE_(T) > {
-  static const int value = 3;
-};
-
-template <GTEST_4_TYPENAMES_(T)>
-struct tuple_size<GTEST_4_TUPLE_(T) > {
-  static const int value = 4;
-};
-
-template <GTEST_5_TYPENAMES_(T)>
-struct tuple_size<GTEST_5_TUPLE_(T) > {
-  static const int value = 5;
-};
-
-template <GTEST_6_TYPENAMES_(T)>
-struct tuple_size<GTEST_6_TUPLE_(T) > {
-  static const int value = 6;
-};
-
-template <GTEST_7_TYPENAMES_(T)>
-struct tuple_size<GTEST_7_TUPLE_(T) > {
-  static const int value = 7;
-};
-
-template <GTEST_8_TYPENAMES_(T)>
-struct tuple_size<GTEST_8_TUPLE_(T) > {
-  static const int value = 8;
-};
-
-template <GTEST_9_TYPENAMES_(T)>
-struct tuple_size<GTEST_9_TUPLE_(T) > {
-  static const int value = 9;
-};
-
-template <GTEST_10_TYPENAMES_(T)>
-struct tuple_size<GTEST_10_TUPLE_(T) > {
-  static const int value = 10;
-};
-
-template <int k, class Tuple>
-struct tuple_element {
-  typedef typename gtest_internal::TupleElement<
-      k < (tuple_size<Tuple>::value), k, Tuple>::type type;
-};
-
-#define GTEST_TUPLE_ELEMENT_(k, Tuple) typename tuple_element<k, Tuple >::type
-
-// 6.1.3.4 Element access.
-
-namespace gtest_internal {
-
-template <>
-class Get<0> {
- public:
-  template <class Tuple>
-  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple))
-  Field(Tuple& t) { return t.f0_; }  // NOLINT
-
-  template <class Tuple>
-  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple))
-  ConstField(const Tuple& t) { return t.f0_; }
-};
-
-template <>
-class Get<1> {
- public:
-  template <class Tuple>
-  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple))
-  Field(Tuple& t) { return t.f1_; }  // NOLINT
-
-  template <class Tuple>
-  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple))
-  ConstField(const Tuple& t) { return t.f1_; }
-};
-
-template <>
-class Get<2> {
- public:
-  template <class Tuple>
-  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple))
-  Field(Tuple& t) { return t.f2_; }  // NOLINT
-
-  template <class Tuple>
-  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple))
-  ConstField(const Tuple& t) { return t.f2_; }
-};
-
-template <>
-class Get<3> {
- public:
-  template <class Tuple>
-  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple))
-  Field(Tuple& t) { return t.f3_; }  // NOLINT
-
-  template <class Tuple>
-  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple))
-  ConstField(const Tuple& t) { return t.f3_; }
-};
-
-template <>
-class Get<4> {
- public:
-  template <class Tuple>
-  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple))
-  Field(Tuple& t) { return t.f4_; }  // NOLINT
-
-  template <class Tuple>
-  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple))
-  ConstField(const Tuple& t) { return t.f4_; }
-};
-
-template <>
-class Get<5> {
- public:
-  template <class Tuple>
-  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple))
-  Field(Tuple& t) { return t.f5_; }  // NOLINT
-
-  template <class Tuple>
-  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple))
-  ConstField(const Tuple& t) { return t.f5_; }
-};
-
-template <>
-class Get<6> {
- public:
-  template <class Tuple>
-  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple))
-  Field(Tuple& t) { return t.f6_; }  // NOLINT
-
-  template <class Tuple>
-  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple))
-  ConstField(const Tuple& t) { return t.f6_; }
-};
-
-template <>
-class Get<7> {
- public:
-  template <class Tuple>
-  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple))
-  Field(Tuple& t) { return t.f7_; }  // NOLINT
-
-  template <class Tuple>
-  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple))
-  ConstField(const Tuple& t) { return t.f7_; }
-};
-
-template <>
-class Get<8> {
- public:
-  template <class Tuple>
-  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple))
-  Field(Tuple& t) { return t.f8_; }  // NOLINT
-
-  template <class Tuple>
-  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple))
-  ConstField(const Tuple& t) { return t.f8_; }
-};
-
-template <>
-class Get<9> {
- public:
-  template <class Tuple>
-  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple))
-  Field(Tuple& t) { return t.f9_; }  // NOLINT
-
-  template <class Tuple>
-  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple))
-  ConstField(const Tuple& t) { return t.f9_; }
-};
-
-}  // namespace gtest_internal
-
-template <int k, GTEST_10_TYPENAMES_(T)>
-GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_10_TUPLE_(T)))
-get(GTEST_10_TUPLE_(T)& t) {
-  return gtest_internal::Get<k>::Field(t);
-}
-
-template <int k, GTEST_10_TYPENAMES_(T)>
-GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(k,  GTEST_10_TUPLE_(T)))
-get(const GTEST_10_TUPLE_(T)& t) {
-  return gtest_internal::Get<k>::ConstField(t);
-}
-
-// 6.1.3.5 Relational operators
-
-// We only implement == and !=, as we don't have a need for the rest yet.
-
-namespace gtest_internal {
-
-// SameSizeTuplePrefixComparator<k, k>::Eq(t1, t2) returns true if the
-// first k fields of t1 equals the first k fields of t2.
-// SameSizeTuplePrefixComparator(k1, k2) would be a compiler error if
-// k1 != k2.
-template <int kSize1, int kSize2>
-struct SameSizeTuplePrefixComparator;
-
-template <>
-struct SameSizeTuplePrefixComparator<0, 0> {
-  template <class Tuple1, class Tuple2>
-  static bool Eq(const Tuple1& /* t1 */, const Tuple2& /* t2 */) {
-    return true;
-  }
-};
-
-template <int k>
-struct SameSizeTuplePrefixComparator<k, k> {
-  template <class Tuple1, class Tuple2>
-  static bool Eq(const Tuple1& t1, const Tuple2& t2) {
-    return SameSizeTuplePrefixComparator<k - 1, k - 1>::Eq(t1, t2) &&
-        ::std::tr1::get<k - 1>(t1) == ::std::tr1::get<k - 1>(t2);
-  }
-};
-
-}  // namespace gtest_internal
-
-template <GTEST_10_TYPENAMES_(T), GTEST_10_TYPENAMES_(U)>
-inline bool operator==(const GTEST_10_TUPLE_(T)& t,
-                       const GTEST_10_TUPLE_(U)& u) {
-  return gtest_internal::SameSizeTuplePrefixComparator<
-      tuple_size<GTEST_10_TUPLE_(T) >::value,
-      tuple_size<GTEST_10_TUPLE_(U) >::value>::Eq(t, u);
-}
-
-template <GTEST_10_TYPENAMES_(T), GTEST_10_TYPENAMES_(U)>
-inline bool operator!=(const GTEST_10_TUPLE_(T)& t,
-                       const GTEST_10_TUPLE_(U)& u) { return !(t == u); }
-
-// 6.1.4 Pairs.
-// Unimplemented.
-
-}  // namespace tr1
-}  // namespace std
-
-#undef GTEST_0_TUPLE_
-#undef GTEST_1_TUPLE_
-#undef GTEST_2_TUPLE_
-#undef GTEST_3_TUPLE_
-#undef GTEST_4_TUPLE_
-#undef GTEST_5_TUPLE_
-#undef GTEST_6_TUPLE_
-#undef GTEST_7_TUPLE_
-#undef GTEST_8_TUPLE_
-#undef GTEST_9_TUPLE_
-#undef GTEST_10_TUPLE_
-
-#undef GTEST_0_TYPENAMES_
-#undef GTEST_1_TYPENAMES_
-#undef GTEST_2_TYPENAMES_
-#undef GTEST_3_TYPENAMES_
-#undef GTEST_4_TYPENAMES_
-#undef GTEST_5_TYPENAMES_
-#undef GTEST_6_TYPENAMES_
-#undef GTEST_7_TYPENAMES_
-#undef GTEST_8_TYPENAMES_
-#undef GTEST_9_TYPENAMES_
-#undef GTEST_10_TYPENAMES_
-
-#undef GTEST_DECLARE_TUPLE_AS_FRIEND_
-#undef GTEST_BY_REF_
-#undef GTEST_ADD_REF_
-#undef GTEST_TUPLE_ELEMENT_
-
-#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_
-# elif GTEST_ENV_HAS_STD_TUPLE_
-#  include <tuple>
-// C++11 puts its tuple into the ::std namespace rather than
-// ::std::tr1.  gtest expects tuple to live in ::std::tr1, so put it there.
-// This causes undefined behavior, but supported compilers react in
-// the way we intend.
-namespace std {
-namespace tr1 {
-using ::std::get;
-using ::std::make_tuple;
-using ::std::tuple;
-using ::std::tuple_element;
-using ::std::tuple_size;
-}
-}
-
-# elif GTEST_OS_SYMBIAN
-
-// On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to
-// use STLport's tuple implementation, which unfortunately doesn't
-// work as the copy of STLport distributed with Symbian is incomplete.
-// By making sure BOOST_HAS_TR1_TUPLE is undefined, we force Boost to
-// use its own tuple implementation.
-#  ifdef BOOST_HAS_TR1_TUPLE
-#   undef BOOST_HAS_TR1_TUPLE
-#  endif  // BOOST_HAS_TR1_TUPLE
-
-// This prevents <boost/tr1/detail/config.hpp>, which defines
-// BOOST_HAS_TR1_TUPLE, from being #included by Boost's <tuple>.
-#  define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED
-#  include <tuple>
-
-# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000)
-// GCC 4.0+ implements tr1/tuple in the <tr1/tuple> header.  This does
-// not conform to the TR1 spec, which requires the header to be <tuple>.
-
-#  if !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302
-// Until version 4.3.2, gcc has a bug that causes <tr1/functional>,
-// which is #included by <tr1/tuple>, to not compile when RTTI is
-// disabled.  _TR1_FUNCTIONAL is the header guard for
-// <tr1/functional>.  Hence the following #define is a hack to prevent
-// <tr1/functional> from being included.
-#   define _TR1_FUNCTIONAL 1
-#   include <tr1/tuple>
-#   undef _TR1_FUNCTIONAL  // Allows the user to #include
-                        // <tr1/functional> if he chooses to.
-#  else
-#   include <tr1/tuple>  // NOLINT
-#  endif  // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302
-
-# else
-// If the compiler is not GCC 4.0+, we assume the user is using a
-// spec-conforming TR1 implementation.
-#  include <tuple>  // NOLINT
-# endif  // GTEST_USE_OWN_TR1_TUPLE
-
-#endif  // GTEST_HAS_TR1_TUPLE
-
-// Determines whether clone(2) is supported.
-// Usually it will only be available on Linux, excluding
-// Linux on the Itanium architecture.
-// Also see http://linux.die.net/man/2/clone.
-#ifndef GTEST_HAS_CLONE
-// The user didn't tell us, so we need to figure it out.
-
-# if GTEST_OS_LINUX && !defined(__ia64__)
-#  if GTEST_OS_LINUX_ANDROID
-// On Android, clone() is only available on ARM starting with Gingerbread.
-#    if defined(__arm__) && __ANDROID_API__ >= 9
-#     define GTEST_HAS_CLONE 1
-#    else
-#     define GTEST_HAS_CLONE 0
-#    endif
-#  else
-#   define GTEST_HAS_CLONE 1
-#  endif
-# else
-#  define GTEST_HAS_CLONE 0
-# endif  // GTEST_OS_LINUX && !defined(__ia64__)
-
-#endif  // GTEST_HAS_CLONE
-
-// Determines whether to support stream redirection. This is used to test
-// output correctness and to implement death tests.
-#ifndef GTEST_HAS_STREAM_REDIRECTION
-// By default, we assume that stream redirection is supported on all
-// platforms except known mobile ones.
-# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN
-#  define GTEST_HAS_STREAM_REDIRECTION 0
-# else
-#  define GTEST_HAS_STREAM_REDIRECTION 1
-# endif  // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN
-#endif  // GTEST_HAS_STREAM_REDIRECTION
-
-// Determines whether to support death tests.
-// Google Test does not support death tests for VC 7.1 and earlier as
-// abort() in a VC 7.1 application compiled as GUI in debug config
-// pops up a dialog window that cannot be suppressed programmatically.
-#if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
-     (GTEST_OS_MAC && !GTEST_OS_IOS) || GTEST_OS_IOS_SIMULATOR || \
-     (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \
-     GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \
-     GTEST_OS_OPENBSD || GTEST_OS_QNX)
-# define GTEST_HAS_DEATH_TEST 1
-# include <vector>  // NOLINT
-#endif
-
-// We don't support MSVC 7.1 with exceptions disabled now.  Therefore
-// all the compilers we care about are adequate for supporting
-// value-parameterized tests.
-#define GTEST_HAS_PARAM_TEST 1
-
-// Determines whether to support type-driven tests.
-
-// Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0,
-// Sun Pro CC, IBM Visual Age, and HP aCC support.
-#if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \
-    defined(__IBMCPP__) || defined(__HP_aCC)
-# define GTEST_HAS_TYPED_TEST 1
-# define GTEST_HAS_TYPED_TEST_P 1
-#endif
-
-// Determines whether to support Combine(). This only makes sense when
-// value-parameterized tests are enabled.  The implementation doesn't
-// work on Sun Studio since it doesn't understand templated conversion
-// operators.
-#if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE && !defined(__SUNPRO_CC)
-# define GTEST_HAS_COMBINE 1
-#endif
-
-// Determines whether the system compiler uses UTF-16 for encoding wide strings.
-#define GTEST_WIDE_STRING_USES_UTF16_ \
-    (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX)
-
-// Determines whether test results can be streamed to a socket.
-#if GTEST_OS_LINUX
-# define GTEST_CAN_STREAM_RESULTS_ 1
-#endif
-
-// Defines some utility macros.
-
-// The GNU compiler emits a warning if nested "if" statements are followed by
-// an "else" statement and braces are not used to explicitly disambiguate the
-// "else" binding.  This leads to problems with code like:
-//
-//   if (gate)
-//     ASSERT_*(condition) << "Some message";
-//
-// The "switch (0) case 0:" idiom is used to suppress this.
-#ifdef __INTEL_COMPILER
-# define GTEST_AMBIGUOUS_ELSE_BLOCKER_
-#else
-# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default:  // NOLINT
-#endif
-
-// Use this annotation at the end of a struct/class definition to
-// prevent the compiler from optimizing away instances that are never
-// used.  This is useful when all interesting logic happens inside the
-// c'tor and / or d'tor.  Example:
-//
-//   struct Foo {
-//     Foo() { ... }
-//   } GTEST_ATTRIBUTE_UNUSED_;
-//
-// Also use it after a variable or parameter declaration to tell the
-// compiler the variable/parameter does not have to be used.
-#if defined(__GNUC__) && !defined(COMPILER_ICC)
-# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
-#else
-# define GTEST_ATTRIBUTE_UNUSED_
-#endif
-
-// A macro to disallow operator=
-// This should be used in the private: declarations for a class.
-#define GTEST_DISALLOW_ASSIGN_(type)\
-  void operator=(type const &)
-
-// A macro to disallow copy constructor and operator=
-// This should be used in the private: declarations for a class.
-#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\
-  type(type const &);\
-  GTEST_DISALLOW_ASSIGN_(type)
-
-// Tell the compiler to warn about unused return values for functions declared
-// with this macro.  The macro should be used on function declarations
-// following the argument list:
-//
-//   Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_;
-#if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC)
-# define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result))
-#else
-# define GTEST_MUST_USE_RESULT_
-#endif  // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC
-
-// Determine whether the compiler supports Microsoft's Structured Exception
-// Handling.  This is supported by several Windows compilers but generally
-// does not exist on any other system.
-#ifndef GTEST_HAS_SEH
-// The user didn't tell us, so we need to figure it out.
-
-# if defined(_MSC_VER) || defined(__BORLANDC__)
-// These two compilers are known to support SEH.
-#  define GTEST_HAS_SEH 1
-# else
-// Assume no SEH.
-#  define GTEST_HAS_SEH 0
-# endif
-
-#endif  // GTEST_HAS_SEH
-
-#ifdef _MSC_VER
-
-# if GTEST_LINKED_AS_SHARED_LIBRARY
-#  define GTEST_API_ __declspec(dllimport)
-# elif GTEST_CREATE_SHARED_LIBRARY
-#  define GTEST_API_ __declspec(dllexport)
-# endif
-
-#endif  // _MSC_VER
-
-#ifndef GTEST_API_
-# define GTEST_API_
-#endif
-
-#ifdef __GNUC__
-// Ask the compiler to never inline a given function.
-# define GTEST_NO_INLINE_ __attribute__((noinline))
-#else
-# define GTEST_NO_INLINE_
-#endif
-
-// _LIBCPP_VERSION is defined by the libc++ library from the LLVM project.
-#if defined(__GLIBCXX__) || defined(_LIBCPP_VERSION)
-# define GTEST_HAS_CXXABI_H_ 1
-#else
-# define GTEST_HAS_CXXABI_H_ 0
-#endif
-
-namespace testing {
-
-class Message;
-
-namespace internal {
-
-// A secret type that Google Test users don't know about.  It has no
-// definition on purpose.  Therefore it's impossible to create a
-// Secret object, which is what we want.
-class Secret;
-
-// The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time
-// expression is true. For example, you could use it to verify the
-// size of a static array:
-//
-//   GTEST_COMPILE_ASSERT_(ARRAYSIZE(content_type_names) == CONTENT_NUM_TYPES,
-//                         content_type_names_incorrect_size);
-//
-// or to make sure a struct is smaller than a certain size:
-//
-//   GTEST_COMPILE_ASSERT_(sizeof(foo) < 128, foo_too_large);
-//
-// The second argument to the macro is the name of the variable. If
-// the expression is false, most compilers will issue a warning/error
-// containing the name of the variable.
-
-template <bool>
-struct CompileAssert {
-};
-
-#define GTEST_COMPILE_ASSERT_(expr, msg) \
-  typedef ::testing::internal::CompileAssert<(static_cast<bool>(expr))> \
-      msg[static_cast<bool>(expr) ? 1 : -1] GTEST_ATTRIBUTE_UNUSED_
-
-// Implementation details of GTEST_COMPILE_ASSERT_:
-//
-// - GTEST_COMPILE_ASSERT_ works by defining an array type that has -1
-//   elements (and thus is invalid) when the expression is false.
-//
-// - The simpler definition
-//
-//    #define GTEST_COMPILE_ASSERT_(expr, msg) typedef char msg[(expr) ? 1 : -1]
-//
-//   does not work, as gcc supports variable-length arrays whose sizes
-//   are determined at run-time (this is gcc's extension and not part
-//   of the C++ standard).  As a result, gcc fails to reject the
-//   following code with the simple definition:
-//
-//     int foo;
-//     GTEST_COMPILE_ASSERT_(foo, msg); // not supposed to compile as foo is
-//                                      // not a compile-time constant.
-//
-// - By using the type CompileAssert<(bool(expr))>, we ensures that
-//   expr is a compile-time constant.  (Template arguments must be
-//   determined at compile-time.)
-//
-// - The outter parentheses in CompileAssert<(bool(expr))> are necessary
-//   to work around a bug in gcc 3.4.4 and 4.0.1.  If we had written
-//
-//     CompileAssert<bool(expr)>
-//
-//   instead, these compilers will refuse to compile
-//
-//     GTEST_COMPILE_ASSERT_(5 > 0, some_message);
-//
-//   (They seem to think the ">" in "5 > 0" marks the end of the
-//   template argument list.)
-//
-// - The array size is (bool(expr) ? 1 : -1), instead of simply
-//
-//     ((expr) ? 1 : -1).
-//
-//   This is to avoid running into a bug in MS VC 7.1, which
-//   causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1.
-
-// StaticAssertTypeEqHelper is used by StaticAssertTypeEq defined in gtest.h.
-//
-// This template is declared, but intentionally undefined.
-template <typename T1, typename T2>
-struct StaticAssertTypeEqHelper;
-
-template <typename T>
-struct StaticAssertTypeEqHelper<T, T> {};
-
-#if GTEST_HAS_GLOBAL_STRING
-typedef ::string string;
-#else
-typedef ::std::string string;
-#endif  // GTEST_HAS_GLOBAL_STRING
-
-#if GTEST_HAS_GLOBAL_WSTRING
-typedef ::wstring wstring;
-#elif GTEST_HAS_STD_WSTRING
-typedef ::std::wstring wstring;
-#endif  // GTEST_HAS_GLOBAL_WSTRING
-
-// A helper for suppressing warnings on constant condition.  It just
-// returns 'condition'.
-GTEST_API_ bool IsTrue(bool condition);
-
-// Defines scoped_ptr.
-
-// This implementation of scoped_ptr is PARTIAL - it only contains
-// enough stuff to satisfy Google Test's need.
-template <typename T>
-class scoped_ptr {
- public:
-  typedef T element_type;
-
-  explicit scoped_ptr(T* p = NULL) : ptr_(p) {}
-  ~scoped_ptr() { reset(); }
-
-  T& operator*() const { return *ptr_; }
-  T* operator->() const { return ptr_; }
-  T* get() const { return ptr_; }
-
-  T* release() {
-    T* const ptr = ptr_;
-    ptr_ = NULL;
-    return ptr;
-  }
-
-  void reset(T* p = NULL) {
-    if (p != ptr_) {
-      if (IsTrue(sizeof(T) > 0)) {  // Makes sure T is a complete type.
-        delete ptr_;
-      }
-      ptr_ = p;
-    }
-  }
-
- private:
-  T* ptr_;
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(scoped_ptr);
-};
-
-// Defines RE.
-
-// A simple C++ wrapper for <regex.h>.  It uses the POSIX Extended
-// Regular Expression syntax.
-class GTEST_API_ RE {
- public:
-  // A copy constructor is required by the Standard to initialize object
-  // references from r-values.
-  RE(const RE& other) { Init(other.pattern()); }
-
-  // Constructs an RE from a string.
-  RE(const ::std::string& regex) { Init(regex.c_str()); }  // NOLINT
-
-#if GTEST_HAS_GLOBAL_STRING
-
-  RE(const ::string& regex) { Init(regex.c_str()); }  // NOLINT
-
-#endif  // GTEST_HAS_GLOBAL_STRING
-
-  RE(const char* regex) { Init(regex); }  // NOLINT
-  ~RE();
-
-  // Returns the string representation of the regex.
-  const char* pattern() const { return pattern_; }
-
-  // FullMatch(str, re) returns true iff regular expression re matches
-  // the entire str.
-  // PartialMatch(str, re) returns true iff regular expression re
-  // matches a substring of str (including str itself).
-  //
-  // TODO(wan@google.com): make FullMatch() and PartialMatch() work
-  // when str contains NUL characters.
-  static bool FullMatch(const ::std::string& str, const RE& re) {
-    return FullMatch(str.c_str(), re);
-  }
-  static bool PartialMatch(const ::std::string& str, const RE& re) {
-    return PartialMatch(str.c_str(), re);
-  }
-
-#if GTEST_HAS_GLOBAL_STRING
-
-  static bool FullMatch(const ::string& str, const RE& re) {
-    return FullMatch(str.c_str(), re);
-  }
-  static bool PartialMatch(const ::string& str, const RE& re) {
-    return PartialMatch(str.c_str(), re);
-  }
-
-#endif  // GTEST_HAS_GLOBAL_STRING
-
-  static bool FullMatch(const char* str, const RE& re);
-  static bool PartialMatch(const char* str, const RE& re);
-
- private:
-  void Init(const char* regex);
-
-  // We use a const char* instead of an std::string, as Google Test used to be
-  // used where std::string is not available.  TODO(wan@google.com): change to
-  // std::string.
-  const char* pattern_;
-  bool is_valid_;
-
-#if GTEST_USES_POSIX_RE
-
-  regex_t full_regex_;     // For FullMatch().
-  regex_t partial_regex_;  // For PartialMatch().
-
-#else  // GTEST_USES_SIMPLE_RE
-
-  const char* full_pattern_;  // For FullMatch();
-
-#endif
-
-  GTEST_DISALLOW_ASSIGN_(RE);
-};
-
-// Formats a source file path and a line number as they would appear
-// in an error message from the compiler used to compile this code.
-GTEST_API_ ::std::string FormatFileLocation(const char* file, int line);
-
-// Formats a file location for compiler-independent XML output.
-// Although this function is not platform dependent, we put it next to
-// FormatFileLocation in order to contrast the two functions.
-GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
-                                                               int line);
-
-// Defines logging utilities:
-//   GTEST_LOG_(severity) - logs messages at the specified severity level. The
-//                          message itself is streamed into the macro.
-//   LogToStderr()  - directs all log messages to stderr.
-//   FlushInfoLog() - flushes informational log messages.
-
-enum GTestLogSeverity {
-  GTEST_INFO,
-  GTEST_WARNING,
-  GTEST_ERROR,
-  GTEST_FATAL
-};
-
-// Formats log entry severity, provides a stream object for streaming the
-// log message, and terminates the message with a newline when going out of
-// scope.
-class GTEST_API_ GTestLog {
- public:
-  GTestLog(GTestLogSeverity severity, const char* file, int line);
-
-  // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
-  ~GTestLog();
-
-  ::std::ostream& GetStream() { return ::std::cerr; }
-
- private:
-  const GTestLogSeverity severity_;
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog);
-};
-
-#define GTEST_LOG_(severity) \
-    ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \
-                                  __FILE__, __LINE__).GetStream()
-
-inline void LogToStderr() {}
-inline void FlushInfoLog() { fflush(NULL); }
-
-// INTERNAL IMPLEMENTATION - DO NOT USE.
-//
-// GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition
-// is not satisfied.
-//  Synopsys:
-//    GTEST_CHECK_(boolean_condition);
-//     or
-//    GTEST_CHECK_(boolean_condition) << "Additional message";
-//
-//    This checks the condition and if the condition is not satisfied
-//    it prints message about the condition violation, including the
-//    condition itself, plus additional message streamed into it, if any,
-//    and then it aborts the program. It aborts the program irrespective of
-//    whether it is built in the debug mode or not.
-#define GTEST_CHECK_(condition) \
-    GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
-    if (::testing::internal::IsTrue(condition)) \
-      ; \
-    else \
-      GTEST_LOG_(FATAL) << "Condition " #condition " failed. "
-
-// An all-mode assert to verify that the given POSIX-style function
-// call returns 0 (indicating success).  Known limitation: this
-// doesn't expand to a balanced 'if' statement, so enclose the macro
-// in {} if you need to use it as the only statement in an 'if'
-// branch.
-#define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \
-  if (const int gtest_error = (posix_call)) \
-    GTEST_LOG_(FATAL) << #posix_call << "failed with error " \
-                      << gtest_error
-
-// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
-//
-// Use ImplicitCast_ as a safe version of static_cast for upcasting in
-// the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a
-// const Foo*).  When you use ImplicitCast_, the compiler checks that
-// the cast is safe.  Such explicit ImplicitCast_s are necessary in
-// surprisingly many situations where C++ demands an exact type match
-// instead of an argument type convertable to a target type.
-//
-// The syntax for using ImplicitCast_ is the same as for static_cast:
-//
-//   ImplicitCast_<ToType>(expr)
-//
-// ImplicitCast_ would have been part of the C++ standard library,
-// but the proposal was submitted too late.  It will probably make
-// its way into the language in the future.
-//
-// This relatively ugly name is intentional. It prevents clashes with
-// similar functions users may have (e.g., implicit_cast). The internal
-// namespace alone is not enough because the function can be found by ADL.
-template<typename To>
-inline To ImplicitCast_(To x) { return x; }
-
-// When you upcast (that is, cast a pointer from type Foo to type
-// SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts
-// always succeed.  When you downcast (that is, cast a pointer from
-// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
-// how do you know the pointer is really of type SubclassOfFoo?  It
-// could be a bare Foo, or of type DifferentSubclassOfFoo.  Thus,
-// when you downcast, you should use this macro.  In debug mode, we
-// use dynamic_cast<> to double-check the downcast is legal (we die
-// if it's not).  In normal mode, we do the efficient static_cast<>
-// instead.  Thus, it's important to test in debug mode to make sure
-// the cast is legal!
-//    This is the only place in the code we should use dynamic_cast<>.
-// In particular, you SHOULDN'T be using dynamic_cast<> in order to
-// do RTTI (eg code like this:
-//    if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);
-//    if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);
-// You should design the code some other way not to need this.
-//
-// This relatively ugly name is intentional. It prevents clashes with
-// similar functions users may have (e.g., down_cast). The internal
-// namespace alone is not enough because the function can be found by ADL.
-template<typename To, typename From>  // use like this: DownCast_<T*>(foo);
-inline To DownCast_(From* f) {  // so we only accept pointers
-  // Ensures that To is a sub-type of From *.  This test is here only
-  // for compile-time type checking, and has no overhead in an
-  // optimized build at run-time, as it will be optimized away
-  // completely.
-  if (false) {
-    const To to = NULL;
-    ::testing::internal::ImplicitCast_<From*>(to);
-  }
-
-#if GTEST_HAS_RTTI
-  // RTTI: debug mode only!
-  GTEST_CHECK_(f == NULL || dynamic_cast<To>(f) != NULL);
-#endif
-  return static_cast<To>(f);
-}
-
-// Downcasts the pointer of type Base to Derived.
-// Derived must be a subclass of Base. The parameter MUST
-// point to a class of type Derived, not any subclass of it.
-// When RTTI is available, the function performs a runtime
-// check to enforce this.
-template <class Derived, class Base>
-Derived* CheckedDowncastToActualType(Base* base) {
-#if GTEST_HAS_RTTI
-  GTEST_CHECK_(typeid(*base) == typeid(Derived));
-  return dynamic_cast<Derived*>(base);  // NOLINT
-#else
-  return static_cast<Derived*>(base);  // Poor man's downcast.
-#endif
-}
-
-#if GTEST_HAS_STREAM_REDIRECTION
-
-// Defines the stderr capturer:
-//   CaptureStdout     - starts capturing stdout.
-//   GetCapturedStdout - stops capturing stdout and returns the captured string.
-//   CaptureStderr     - starts capturing stderr.
-//   GetCapturedStderr - stops capturing stderr and returns the captured string.
-//
-GTEST_API_ void CaptureStdout();
-GTEST_API_ std::string GetCapturedStdout();
-GTEST_API_ void CaptureStderr();
-GTEST_API_ std::string GetCapturedStderr();
-
-#endif  // GTEST_HAS_STREAM_REDIRECTION
-
-
-#if GTEST_HAS_DEATH_TEST
-
-const ::std::vector<testing::internal::string>& GetInjectableArgvs();
-void SetInjectableArgvs(const ::std::vector<testing::internal::string>*
-                             new_argvs);
-
-// A copy of all command line arguments.  Set by InitGoogleTest().
-extern ::std::vector<testing::internal::string> g_argvs;
-
-#endif  // GTEST_HAS_DEATH_TEST
-
-// Defines synchronization primitives.
-
-#if GTEST_HAS_PTHREAD
-
-// Sleeps for (roughly) n milli-seconds.  This function is only for
-// testing Google Test's own constructs.  Don't use it in user tests,
-// either directly or indirectly.
-inline void SleepMilliseconds(int n) {
-  const timespec time = {
-    0,                  // 0 seconds.
-    n * 1000L * 1000L,  // And n ms.
-  };
-  nanosleep(&time, NULL);
-}
-
-// Allows a controller thread to pause execution of newly created
-// threads until notified.  Instances of this class must be created
-// and destroyed in the controller thread.
-//
-// This class is only for testing Google Test's own constructs. Do not
-// use it in user tests, either directly or indirectly.
-class Notification {
- public:
-  Notification() : notified_(false) {
-    GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL));
-  }
-  ~Notification() {
-    pthread_mutex_destroy(&mutex_);
-  }
-
-  // Notifies all threads created with this notification to start. Must
-  // be called from the controller thread.
-  void Notify() {
-    pthread_mutex_lock(&mutex_);
-    notified_ = true;
-    pthread_mutex_unlock(&mutex_);
-  }
-
-  // Blocks until the controller thread notifies. Must be called from a test
-  // thread.
-  void WaitForNotification() {
-    for (;;) {
-      pthread_mutex_lock(&mutex_);
-      const bool notified = notified_;
-      pthread_mutex_unlock(&mutex_);
-      if (notified)
-        break;
-      SleepMilliseconds(10);
-    }
-  }
-
- private:
-  pthread_mutex_t mutex_;
-  bool notified_;
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
-};
-
-// As a C-function, ThreadFuncWithCLinkage cannot be templated itself.
-// Consequently, it cannot select a correct instantiation of ThreadWithParam
-// in order to call its Run(). Introducing ThreadWithParamBase as a
-// non-templated base class for ThreadWithParam allows us to bypass this
-// problem.
-class ThreadWithParamBase {
- public:
-  virtual ~ThreadWithParamBase() {}
-  virtual void Run() = 0;
-};
-
-// pthread_create() accepts a pointer to a function type with the C linkage.
-// According to the Standard (7.5/1), function types with different linkages
-// are different even if they are otherwise identical.  Some compilers (for
-// example, SunStudio) treat them as different types.  Since class methods
-// cannot be defined with C-linkage we need to define a free C-function to
-// pass into pthread_create().
-extern "C" inline void* ThreadFuncWithCLinkage(void* thread) {
-  static_cast<ThreadWithParamBase*>(thread)->Run();
-  return NULL;
-}
-
-// Helper class for testing Google Test's multi-threading constructs.
-// To use it, write:
-//
-//   void ThreadFunc(int param) { /* Do things with param */ }
-//   Notification thread_can_start;
-//   ...
-//   // The thread_can_start parameter is optional; you can supply NULL.
-//   ThreadWithParam<int> thread(&ThreadFunc, 5, &thread_can_start);
-//   thread_can_start.Notify();
-//
-// These classes are only for testing Google Test's own constructs. Do
-// not use them in user tests, either directly or indirectly.
-template <typename T>
-class ThreadWithParam : public ThreadWithParamBase {
- public:
-  typedef void (*UserThreadFunc)(T);
-
-  ThreadWithParam(
-      UserThreadFunc func, T param, Notification* thread_can_start)
-      : func_(func),
-        param_(param),
-        thread_can_start_(thread_can_start),
-        finished_(false) {
-    ThreadWithParamBase* const base = this;
-    // The thread can be created only after all fields except thread_
-    // have been initialized.
-    GTEST_CHECK_POSIX_SUCCESS_(
-        pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base));
-  }
-  ~ThreadWithParam() { Join(); }
-
-  void Join() {
-    if (!finished_) {
-      GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, 0));
-      finished_ = true;
-    }
-  }
-
-  virtual void Run() {
-    if (thread_can_start_ != NULL)
-      thread_can_start_->WaitForNotification();
-    func_(param_);
-  }
-
- private:
-  const UserThreadFunc func_;  // User-supplied thread function.
-  const T param_;  // User-supplied parameter to the thread function.
-  // When non-NULL, used to block execution until the controller thread
-  // notifies.
-  Notification* const thread_can_start_;
-  bool finished_;  // true iff we know that the thread function has finished.
-  pthread_t thread_;  // The native thread object.
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
-};
-
-// MutexBase and Mutex implement mutex on pthreads-based platforms. They
-// are used in conjunction with class MutexLock:
-//
-//   Mutex mutex;
-//   ...
-//   MutexLock lock(&mutex);  // Acquires the mutex and releases it at the end
-//                            // of the current scope.
-//
-// MutexBase implements behavior for both statically and dynamically
-// allocated mutexes.  Do not use MutexBase directly.  Instead, write
-// the following to define a static mutex:
-//
-//   GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex);
-//
-// You can forward declare a static mutex like this:
-//
-//   GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex);
-//
-// To create a dynamic mutex, just define an object of type Mutex.
-class MutexBase {
- public:
-  // Acquires this mutex.
-  void Lock() {
-    GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_));
-    owner_ = pthread_self();
-    has_owner_ = true;
-  }
-
-  // Releases this mutex.
-  void Unlock() {
-    // Since the lock is being released the owner_ field should no longer be
-    // considered valid. We don't protect writing to has_owner_ here, as it's
-    // the caller's responsibility to ensure that the current thread holds the
-    // mutex when this is called.
-    has_owner_ = false;
-    GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_));
-  }
-
-  // Does nothing if the current thread holds the mutex. Otherwise, crashes
-  // with high probability.
-  void AssertHeld() const {
-    GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self()))
-        << "The current thread is not holding the mutex @" << this;
-  }
-
-  // A static mutex may be used before main() is entered.  It may even
-  // be used before the dynamic initialization stage.  Therefore we
-  // must be able to initialize a static mutex object at link time.
-  // This means MutexBase has to be a POD and its member variables
-  // have to be public.
- public:
-  pthread_mutex_t mutex_;  // The underlying pthread mutex.
-  // has_owner_ indicates whether the owner_ field below contains a valid thread
-  // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All
-  // accesses to the owner_ field should be protected by a check of this field.
-  // An alternative might be to memset() owner_ to all zeros, but there's no
-  // guarantee that a zero'd pthread_t is necessarily invalid or even different
-  // from pthread_self().
-  bool has_owner_;
-  pthread_t owner_;  // The thread holding the mutex.
-};
-
-// Forward-declares a static mutex.
-# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
-    extern ::testing::internal::MutexBase mutex
-
-// Defines and statically (i.e. at link time) initializes a static mutex.
-// The initialization list here does not explicitly initialize each field,
-// instead relying on default initialization for the unspecified fields. In
-// particular, the owner_ field (a pthread_t) is not explicitly initialized.
-// This allows initialization to work whether pthread_t is a scalar or struct.
-// The flag -Wmissing-field-initializers must not be specified for this to work.
-# define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
-    ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, false }
-
-// The Mutex class can only be used for mutexes created at runtime. It
-// shares its API with MutexBase otherwise.
-class Mutex : public MutexBase {
- public:
-  Mutex() {
-    GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL));
-    has_owner_ = false;
-  }
-  ~Mutex() {
-    GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_));
-  }
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
-};
-
-// We cannot name this class MutexLock as the ctor declaration would
-// conflict with a macro named MutexLock, which is defined on some
-// platforms.  Hence the typedef trick below.
-class GTestMutexLock {
- public:
-  explicit GTestMutexLock(MutexBase* mutex)
-      : mutex_(mutex) { mutex_->Lock(); }
-
-  ~GTestMutexLock() { mutex_->Unlock(); }
-
- private:
-  MutexBase* const mutex_;
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
-};
-
-typedef GTestMutexLock MutexLock;
-
-// Helpers for ThreadLocal.
-
-// pthread_key_create() requires DeleteThreadLocalValue() to have
-// C-linkage.  Therefore it cannot be templatized to access
-// ThreadLocal<T>.  Hence the need for class
-// ThreadLocalValueHolderBase.
-class ThreadLocalValueHolderBase {
- public:
-  virtual ~ThreadLocalValueHolderBase() {}
-};
-
-// Called by pthread to delete thread-local data stored by
-// pthread_setspecific().
-extern "C" inline void DeleteThreadLocalValue(void* value_holder) {
-  delete static_cast<ThreadLocalValueHolderBase*>(value_holder);
-}
-
-// Implements thread-local storage on pthreads-based systems.
-//
-//   // Thread 1
-//   ThreadLocal<int> tl(100);  // 100 is the default value for each thread.
-//
-//   // Thread 2
-//   tl.set(150);  // Changes the value for thread 2 only.
-//   EXPECT_EQ(150, tl.get());
-//
-//   // Thread 1
-//   EXPECT_EQ(100, tl.get());  // In thread 1, tl has the original value.
-//   tl.set(200);
-//   EXPECT_EQ(200, tl.get());
-//
-// The template type argument T must have a public copy constructor.
-// In addition, the default ThreadLocal constructor requires T to have
-// a public default constructor.
-//
-// An object managed for a thread by a ThreadLocal instance is deleted
-// when the thread exits.  Or, if the ThreadLocal instance dies in
-// that thread, when the ThreadLocal dies.  It's the user's
-// responsibility to ensure that all other threads using a ThreadLocal
-// have exited when it dies, or the per-thread objects for those
-// threads will not be deleted.
-//
-// Google Test only uses global ThreadLocal objects.  That means they
-// will die after main() has returned.  Therefore, no per-thread
-// object managed by Google Test will be leaked as long as all threads
-// using Google Test have exited when main() returns.
-template <typename T>
-class ThreadLocal {
- public:
-  ThreadLocal() : key_(CreateKey()),
-                  default_() {}
-  explicit ThreadLocal(const T& value) : key_(CreateKey()),
-                                         default_(value) {}
-
-  ~ThreadLocal() {
-    // Destroys the managed object for the current thread, if any.
-    DeleteThreadLocalValue(pthread_getspecific(key_));
-
-    // Releases resources associated with the key.  This will *not*
-    // delete 

<TRUNCATED>

[31/50] [abbrv] marmotta git commit: - code cleanups, better reuse

Posted by wi...@apache.org.
- code cleanups, better reuse


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/a165b8e4
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/a165b8e4
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/a165b8e4

Branch: refs/heads/MARMOTTA-584
Commit: a165b8e494619da77697c98b814cda87654f902b
Parents: 4ab20b3
Author: Sebastian Schaffert <ss...@apache.org>
Authored: Sat Feb 13 18:00:36 2016 +0100
Committer: Sebastian Schaffert <ss...@apache.org>
Committed: Sat Feb 13 18:00:36 2016 +0100

----------------------------------------------------------------------
 libraries/ostrich/backend/CMakeLists.txt        |   2 +-
 libraries/ostrich/backend/parser/rdf_parser.cc  |  26 +++-
 libraries/ostrich/backend/parser/rdf_parser.h   |   2 +
 .../backend/persistence/marmotta_updatedb.cc    |  12 +-
 .../ostrich/backend/serializer/CMakeLists.txt   |  10 +-
 .../backend/serializer/serializer_base.cc       |  16 ++-
 .../backend/serializer/serializer_raptor.cc     | 125 +++----------------
 libraries/ostrich/backend/util/raptor_util.cc   |  64 ++++++++++
 libraries/ostrich/backend/util/raptor_util.h    |   6 +-
 9 files changed, 134 insertions(+), 129 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/a165b8e4/libraries/ostrich/backend/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/CMakeLists.txt b/libraries/ostrich/backend/CMakeLists.txt
index 5a8f110..61156a5 100644
--- a/libraries/ostrich/backend/CMakeLists.txt
+++ b/libraries/ostrich/backend/CMakeLists.txt
@@ -17,7 +17,7 @@ find_package (GLog REQUIRED)
 find_package (Boost 1.54.0 COMPONENTS iostreams filesystem system)
 find_package (Tcmalloc)
 
-#add_definitions(-DNDEBUG)
+add_definitions(-DNDEBUG)
 
 if (Boost_IOSTREAMS_FOUND)
     message(STATUS "Enabling gzip/bzip2 support (Boost iostreams found)")

http://git-wip-us.apache.org/repos/asf/marmotta/blob/a165b8e4/libraries/ostrich/backend/parser/rdf_parser.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/parser/rdf_parser.cc b/libraries/ostrich/backend/parser/rdf_parser.cc
index cf2dc4d..ebfdc6b 100644
--- a/libraries/ostrich/backend/parser/rdf_parser.cc
+++ b/libraries/ostrich/backend/parser/rdf_parser.cc
@@ -18,15 +18,18 @@
 #include "rdf_parser.h"
 #include <raptor2/raptor2.h>
 #include <util/raptor_util.h>
+#include <glog/logging.h>
 
 namespace marmotta {
 namespace parser {
+
 Parser::Parser(const rdf::URI& baseUri, Format format)
         : stmt_handler([](const rdf::Statement& stmt) { })
         , ns_handler([](const rdf::Namespace& ns) { })
 {
     world = raptor_new_world();
     base  = raptor_new_uri(world, (unsigned char const *) baseUri.getUri().c_str());
+    raptor_world_set_log_handler(world, this, raptor_error_handler);
 
     switch (format) {
         case RDFXML:
@@ -79,15 +82,34 @@ void Parser::raptor_ns_handler(void *user_data, raptor_namespace *nspace) {
             (const char*)raptor_uri_as_string(raptor_namespace_get_uri(nspace))));
 }
 
+void Parser::raptor_error_handler(void *user_data, raptor_log_message* message) {
+    Parser* p = static_cast<Parser*>(user_data);
+    p->error = std::string("parse error (")
+               + std::to_string(message->locator->line) + ":"
+               + std::to_string(message->locator->column) + "): "
+               + message->text;
+
+    LOG(ERROR) << p->error;
+}
+
+
 void Parser::parse(std::istream &in) {
     if(in) {
         raptor_parser_parse_start(parser, base);
 
+        int status = 0;
+
         char buffer[8192];
         while (in.read(buffer, 8192)) {
-            raptor_parser_parse_chunk(parser, (unsigned char const *) buffer, in.gcount(), 0);
+            status = raptor_parser_parse_chunk(parser, (unsigned char const *) buffer, in.gcount(), 0);
+            if (status != 0) {
+                throw ParseError(error);
+            }
+        }
+        status = raptor_parser_parse_chunk(parser, (unsigned char const *) buffer, in.gcount(), 1);
+        if (status != 0) {
+            throw ParseError(error);
         }
-        raptor_parser_parse_chunk(parser, (unsigned char const *) buffer, in.gcount(), 1);
     }
 }
 

http://git-wip-us.apache.org/repos/asf/marmotta/blob/a165b8e4/libraries/ostrich/backend/parser/rdf_parser.h
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/parser/rdf_parser.h b/libraries/ostrich/backend/parser/rdf_parser.h
index de2ebdf..b4ff346 100644
--- a/libraries/ostrich/backend/parser/rdf_parser.h
+++ b/libraries/ostrich/backend/parser/rdf_parser.h
@@ -66,12 +66,14 @@ class Parser {
     raptor_parser* parser;
     raptor_world*  world;
     raptor_uri*    base;
+    std::string    error;
 
     std::function<void(const rdf::Statement&)> stmt_handler;
     std::function<void(const rdf::Namespace&)> ns_handler;
 
     static void raptor_stmt_handler(void* user_data, raptor_statement* statement);
     static void raptor_ns_handler(void* user_data, raptor_namespace *nspace);
+    static void raptor_error_handler(void *user_data, raptor_log_message* message);
 };
 
 class ParseError : std::exception {

http://git-wip-us.apache.org/repos/asf/marmotta/blob/a165b8e4/libraries/ostrich/backend/persistence/marmotta_updatedb.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/persistence/marmotta_updatedb.cc b/libraries/ostrich/backend/persistence/marmotta_updatedb.cc
index b26b019..f29bef9 100644
--- a/libraries/ostrich/backend/persistence/marmotta_updatedb.cc
+++ b/libraries/ostrich/backend/persistence/marmotta_updatedb.cc
@@ -118,17 +118,7 @@ class MarmottaClient {
     }
 
     int64_t size() {
-        /*
-        ClientContext context;
-        google::protobuf::Int64Value result;
-
-        Status status = stub_->Size(&context, r, &result);
-        if (status.ok()) {
-            return result.value();
-        } else {
-            return -1;
-        }
-         */
+        return db->Size();
     }
  private:
     marmotta::persistence::LevelDBPersistence* db;

http://git-wip-us.apache.org/repos/asf/marmotta/blob/a165b8e4/libraries/ostrich/backend/serializer/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/serializer/CMakeLists.txt b/libraries/ostrich/backend/serializer/CMakeLists.txt
index 0fe9c4c..b050fb9 100644
--- a/libraries/ostrich/backend/serializer/CMakeLists.txt
+++ b/libraries/ostrich/backend/serializer/CMakeLists.txt
@@ -1,4 +1,10 @@
 include_directories(.. ${CMAKE_CURRENT_BINARY_DIR}/..)
 
-add_library(marmotta_serializer serializer_raptor.h serializer_raptor.cc serializer_raptor.cc serializer_proto.cc serializer_proto.h serializer_base.cc serializer_base.h serializer.cc serializer.h)
-target_link_libraries(marmotta_serializer marmotta_model ${CMAKE_THREAD_LIBS_INIT} ${RAPTOR_LIBRARY})
\ No newline at end of file
+add_library(marmotta_serializer
+        serializer_raptor.h serializer_raptor.cc
+        serializer_proto.cc serializer_proto.h
+        serializer_base.cc serializer_base.h
+        serializer.cc serializer.h)
+target_link_libraries(marmotta_serializer
+        marmotta_model marmotta_raptor_util
+        ${CMAKE_THREAD_LIBS_INIT} ${RAPTOR_LIBRARY})
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/marmotta/blob/a165b8e4/libraries/ostrich/backend/serializer/serializer_base.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/serializer/serializer_base.cc b/libraries/ostrich/backend/serializer/serializer_base.cc
index 4b3e86d..c168dae 100644
--- a/libraries/ostrich/backend/serializer/serializer_base.cc
+++ b/libraries/ostrich/backend/serializer/serializer_base.cc
@@ -21,6 +21,14 @@ namespace marmotta {
 namespace serializer {
 
 namespace {
+
+const std::map<std::string, rdf::URI> kDefaultNamespaces = {
+        {"skos", "http://www.w3.org/2004/02/skos/core#"},
+        {"rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"},
+        {"rdfs", "http://www.w3.org/2000/01/rdf-schema#"},
+        {"owl", "http://www.w3.org/2002/07/owl#"},
+};
+
 static std::map<std::string, rdf::URI> namespacesMap(std::vector<rdf::Namespace> list) {
     std::map<std::string, rdf::URI> result;
     for (auto it = list.cbegin(); it != list.cend(); it++) {
@@ -54,10 +62,14 @@ Format FormatFromString(const std::string &name) {
 }
 
 SerializerBase::SerializerBase(const rdf::URI& baseUri, Format format, std::vector<rdf::Namespace> namespaces)
-        : baseUri(baseUri), format(format), namespaces(namespacesMap(namespaces)) { }
+        : baseUri(baseUri), format(format), namespaces(namespacesMap(namespaces)) {
+    this->namespaces.insert(kDefaultNamespaces.cbegin(), kDefaultNamespaces.cend());
+}
 
 SerializerBase::SerializerBase(const rdf::URI& baseUri, Format format, std::map<std::string, rdf::URI> namespaces)
-        : baseUri(baseUri), format(format), namespaces(namespaces) { }
+        : baseUri(baseUri), format(format), namespaces(namespaces) {
+    this->namespaces.insert(kDefaultNamespaces.cbegin(), kDefaultNamespaces.cend());
+}
 
 
 }  // namespace serializer

http://git-wip-us.apache.org/repos/asf/marmotta/blob/a165b8e4/libraries/ostrich/backend/serializer/serializer_raptor.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/serializer/serializer_raptor.cc b/libraries/ostrich/backend/serializer/serializer_raptor.cc
index ff37691..f7788fb 100644
--- a/libraries/ostrich/backend/serializer/serializer_raptor.cc
+++ b/libraries/ostrich/backend/serializer/serializer_raptor.cc
@@ -16,6 +16,11 @@
  * limitations under the License.
  */
 #include "serializer_raptor.h"
+#include <raptor2/raptor2.h>
+#include <util/raptor_util.h>
+
+#define STR(s) (const unsigned char*)s.c_str()
+#define CPSTR(s) (const unsigned char*)strdup(s.c_str())
 
 namespace marmotta {
 namespace serializer {
@@ -97,7 +102,7 @@ RaptorSerializer::RaptorSerializer(const rdf::URI& baseUri, Format format)
         : SerializerBase(baseUri, format) {
 
     world = raptor_new_world();
-    base  = raptor_new_uri(world, (unsigned char const *) baseUri.getUri().c_str());
+    base  = raptor_new_uri(world, STR(baseUri.getUri()));
     initRaptor();
 }
 
@@ -105,7 +110,7 @@ RaptorSerializer::RaptorSerializer(const rdf::URI& baseUri, Format format, std::
         : SerializerBase(baseUri, format, namespaces) {
 
     world = raptor_new_world();
-    base  = raptor_new_uri(world, (unsigned char const *) baseUri.getUri().c_str());
+    base  = raptor_new_uri(world, STR(baseUri.getUri()));
     initRaptor();
 }
 
@@ -113,77 +118,30 @@ RaptorSerializer::RaptorSerializer(const rdf::URI& baseUri, Format format, std::
         : SerializerBase(baseUri, format, namespaces) {
 
     world = raptor_new_world();
-    base  = raptor_new_uri(world, (unsigned char const *) baseUri.getUri().c_str());
+    base  = raptor_new_uri(world, STR(baseUri.getUri()));
     initRaptor();
 }
 
 
 RaptorSerializer::~RaptorSerializer() {
     // check for NULL in case a move operation has set the fields to a null pointer
-    if(serializer != NULL)
+    if(serializer != nullptr)
         raptor_free_serializer(serializer);
 
-    if(base != NULL)
+    if(base != nullptr)
         raptor_free_uri(base);
 
-    if(world != NULL)
+    if(world != nullptr)
         raptor_free_world(world);
 
 }
 
-/*
-RaptorSerializer::RaptorSerializer(const RaptorSerializer &other) {
-    format = other.format;
-    namespaces = other.namespaces;
-
-    world = raptor_new_world();
-    base  = raptor_new_uri(world, raptor_uri_as_string(other.base));
-    initRaptor();
-}
-
-RaptorSerializer::RaptorSerializer(RaptorSerializer &&other) {
-    format = other.format;
-    namespaces = other.namespaces;
-    base = other.base;
-    world = other.world;
-    serializer = other.serializer;
-
-    other.serializer = NULL;
-    other.base = NULL;
-    other.world = NULL;
-}
-
-RaptorSerializer &RaptorSerializer::operator=(const RaptorSerializer &other) {
-    format = other.format;
-    namespaces = other.namespaces;
-
-    world = raptor_new_world();
-    base  = raptor_new_uri(world, raptor_uri_as_string(other.base));
-    initRaptor();
-
-    return *this;
-}
-
-RaptorSerializer &RaptorSerializer::operator=(RaptorSerializer &&other) {
-    format = other.format;
-    namespaces = other.namespaces;
-    serializer = other.serializer;
-    base = other.base;
-    world = other.world;
-
-    other.serializer = NULL;
-    other.base = NULL;
-    other.world = NULL;
-
-    return *this;
-}
-*/
 
 void RaptorSerializer::initRaptor() {
     serializer = raptor_new_serializer(world, raptorFormat(format).c_str());
     for(const auto &e : namespaces) {
-        raptor_uri* uri = raptor_new_uri(world, (unsigned char const *) e.second.getUri().c_str());
-        raptor_serializer_set_namespace(serializer, uri, (unsigned char const *) e.first.c_str());
+        raptor_uri* uri = raptor_new_uri(world, STR(e.second.getUri()));
+        raptor_serializer_set_namespace(serializer, uri, CPSTR(e.first));
     }
     raptor_world_set_log_handler(world, this, [](void *user_data, raptor_log_message* message){
         std::cerr << message->level << ": " << message->text << std::endl;
@@ -198,59 +156,10 @@ void RaptorSerializer::prepare(std::ostream &out) {
 void RaptorSerializer::serialize(const rdf::Statement &stmt) {
     raptor_statement* triple = raptor_new_statement(world);
 
-    if (stmt.getMessage().subject().has_uri()) {
-        triple->subject = raptor_new_term_from_uri_string(
-                world, (unsigned char const *) stmt.getMessage().subject().uri().uri().c_str());
-    } else if (stmt.getMessage().subject().has_bnode()) {
-        triple->subject = raptor_new_term_from_blank(
-                world, (unsigned char const *) stmt.getMessage().subject().bnode().id().c_str());
-    } else {
-        throw SerializationError("invalid subject type");
-    }
-
-    triple->predicate = raptor_new_term_from_uri_string(
-            world,  (unsigned char const *) stmt.getMessage().predicate().uri().c_str());
-
-    if (stmt.getMessage().object().has_resource()) {
-        const marmotta::rdf::proto::Resource& r = stmt.getMessage().object().resource();
-        if (r.has_uri()) {
-            triple->object = raptor_new_term_from_uri_string(
-                    world, (unsigned char const *) r.uri().uri().c_str());
-        } else if(r.has_bnode()) {
-            triple->object = raptor_new_term_from_blank(
-                    world, (unsigned char const *) r.bnode().id().c_str());
-        } else {
-            throw SerializationError("invalid object resource type");
-        }
-    } else if (stmt.getMessage().object().has_literal()) {
-        const marmotta::rdf::proto::Literal& l = stmt.getMessage().object().literal();
-        if (l.has_stringliteral()) {
-            triple->object = raptor_new_term_from_counted_literal(
-                    world,
-                    (unsigned char const *) l.stringliteral().content().c_str(), l.stringliteral().content().size(), NULL,
-                    (unsigned char const *) l.stringliteral().language().c_str(), l.stringliteral().language().size());
-        } else if(l.has_dataliteral()) {
-            triple->object = raptor_new_term_from_counted_literal(
-                    world,
-                    (unsigned char const *) l.dataliteral().content().c_str(), l.dataliteral().content().size(),
-                    raptor_new_uri(world, (unsigned char const *) l.dataliteral().datatype().uri().c_str()),
-                    (unsigned char const *) "", 0);
-        } else {
-            throw SerializationError("invalid object literal type");
-        }
-    } else {
-        throw SerializationError("invalid object type");
-    }
-
-    if (stmt.getMessage().context().has_uri()) {
-        triple->graph = raptor_new_term_from_uri_string(
-                world,  (unsigned char const *) stmt.getMessage().context().uri().uri().c_str());
-    } else if (stmt.getMessage().context().has_bnode()) {
-        triple->graph = raptor_new_term_from_blank(
-                world, (unsigned char const *) stmt.getMessage().context().bnode().id().c_str());
-    } else {
-        triple->graph = nullptr;
-    }
+    triple->subject   = util::raptor::AsTerm(world, stmt.getSubject());
+    triple->predicate = util::raptor::AsTerm(world, stmt.getPredicate());
+    triple->object    = util::raptor::AsTerm(world, stmt.getObject());
+    triple->graph     = util::raptor::AsTerm(world, stmt.getContext());
 
     raptor_serializer_serialize_statement(serializer, triple);
 

http://git-wip-us.apache.org/repos/asf/marmotta/blob/a165b8e4/libraries/ostrich/backend/util/raptor_util.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/util/raptor_util.cc b/libraries/ostrich/backend/util/raptor_util.cc
index bbeaecd..e20b265 100644
--- a/libraries/ostrich/backend/util/raptor_util.cc
+++ b/libraries/ostrich/backend/util/raptor_util.cc
@@ -109,6 +109,70 @@ rdf::Statement ConvertStatement(raptor_statement *triple) {
 
     }
 }
+
+namespace {
+raptor_term *AsStringLiteral(raptor_world* world, const rdf::Value &v) {
+    rdf::StringLiteral l(v.getMessage().literal().stringliteral());
+
+    return raptor_new_term_from_counted_literal(
+            world,
+            STR(l.getContent()), l.getContent().size(),
+            nullptr,
+            STR(l.getLanguage()), l.getLanguage().size());
+}
+
+raptor_term *AsDatatypeLiteral(raptor_world* world, const rdf::Value &v) {
+    rdf::DatatypeLiteral l(v.getMessage().literal().dataliteral());
+
+    return raptor_new_term_from_counted_literal(
+            world,
+            STR(l.getContent()), l.getContent().size(),
+            raptor_new_uri(world, STR(l.getDatatype().getUri())),
+            (unsigned char const *) "", 0);
+}
+}  // namespace
+
+
+/*
+ * Convert a Marmotta Resource into a raptor term.
+ */
+raptor_term* AsTerm(raptor_world* world, const rdf::Resource& r) {
+    switch (r.type) {
+        case rdf::Resource::URI:
+            return raptor_new_term_from_uri_string(world, STR(r.stringValue()));
+        case rdf::Resource::BNODE:
+            return raptor_new_term_from_blank(world, STR(r.stringValue()));
+        default:
+            return nullptr;
+    }
+}
+
+/*
+ * Convert a Marmotta Value into a raptor term.
+ */
+raptor_term* AsTerm(raptor_world* world, const rdf::Value& v) {
+    switch (v.type) {
+        case rdf::Value::URI:
+            return raptor_new_term_from_uri_string(world, STR(v.stringValue()));
+        case rdf::Value::BNODE:
+            return raptor_new_term_from_blank(world, STR(v.stringValue()));
+        case rdf::Value::STRING_LITERAL:
+            return AsStringLiteral(world, v);
+        case rdf::Value::DATATYPE_LITERAL:
+            return AsDatatypeLiteral(world, v);
+        default:
+            return nullptr;
+    }
+
+}
+
+/*
+ * Convert a Marmotta URI into a raptor term.
+ */
+raptor_term* AsTerm(raptor_world* world, const rdf::URI& u) {
+    return raptor_new_term_from_uri_string(world, STR(u.stringValue()));
+}
+
 }  // namespace raptor
 }  // namespace util
 }  // namespace marmotta

http://git-wip-us.apache.org/repos/asf/marmotta/blob/a165b8e4/libraries/ostrich/backend/util/raptor_util.h
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/util/raptor_util.h b/libraries/ostrich/backend/util/raptor_util.h
index 1899235..445d61e 100644
--- a/libraries/ostrich/backend/util/raptor_util.h
+++ b/libraries/ostrich/backend/util/raptor_util.h
@@ -54,17 +54,17 @@ rdf::Statement ConvertStatement(raptor_statement* triple);
 /*
  * Convert a Marmotta Resource into a raptor term.
  */
-raptor_term* AsLiteral(raptor_world* world, const rdf::Resource& r);
+raptor_term* AsTerm(raptor_world* world, const rdf::Resource& r);
 
 /*
  * Convert a Marmotta Value into a raptor term.
  */
-raptor_term* AsLiteral(raptor_world* world, const rdf::Value& v);
+raptor_term* AsTerm(raptor_world* world, const rdf::Value& v);
 
 /*
  * Convert a Marmotta URI into a raptor term.
  */
-raptor_term* AsLiteral(raptor_world* world, const rdf::URI& u);
+raptor_term* AsTerm(raptor_world* world, const rdf::URI& u);
 
 }  // namespace raptor
 }  // namespace util


[03/50] [abbrv] marmotta git commit: refactor iterator implementations, they were broken

Posted by wi...@apache.org.
http://git-wip-us.apache.org/repos/asf/marmotta/blob/2e32da5d/libraries/ostrich/backend/test/gtest/gtest.h
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/test/gtest/gtest.h b/libraries/ostrich/backend/test/gtest/gtest.h
new file mode 100644
index 0000000..6b2219d
--- /dev/null
+++ b/libraries/ostrich/backend/test/gtest/gtest.h
@@ -0,0 +1,21197 @@
+// Copyright 2005, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+// Author: wan@google.com (Zhanyong Wan)
+//
+// The Google C++ Testing Framework (Google Test)
+//
+// This header file defines the public API for Google Test.  It should be
+// included by any test program that uses Google Test.
+//
+// IMPORTANT NOTE: Due to limitation of the C++ language, we have to
+// leave some internal implementation details in this header file.
+// They are clearly marked by comments like this:
+//
+//   // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
+//
+// Such code is NOT meant to be used by a user directly, and is subject
+// to CHANGE WITHOUT NOTICE.  Therefore DO NOT DEPEND ON IT in a user
+// program!
+//
+// Acknowledgment: Google Test borrowed the idea of automatic test
+// registration from Barthelemy Dagenais' (barthelemy@prologique.com)
+// easyUnit framework.
+
+#ifndef GTEST_INCLUDE_GTEST_GTEST_H_
+#define GTEST_INCLUDE_GTEST_GTEST_H_
+
+#include <limits>
+#include <ostream>
+#include <vector>
+
+// Copyright 2005, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee)
+//
+// The Google C++ Testing Framework (Google Test)
+//
+// This header file declares functions and macros used internally by
+// Google Test.  They are subject to change without notice.
+
+#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
+#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
+
+// Copyright 2005, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+// Authors: wan@google.com (Zhanyong Wan)
+//
+// Low-level types and utilities for porting Google Test to various
+// platforms.  All macros ending with _ and symbols defined in an
+// internal namespace are subject to change without notice.  Code
+// outside Google Test MUST NOT USE THEM DIRECTLY.  Macros that don't
+// end with _ are part of Google Test's public API and can be used by
+// code outside Google Test.
+//
+// This file is fundamental to Google Test.  All other Google Test source
+// files are expected to #include this.  Therefore, it cannot #include
+// any other Google Test header.
+
+#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
+#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
+
+// Environment-describing macros
+// -----------------------------
+//
+// Google Test can be used in many different environments.  Macros in
+// this section tell Google Test what kind of environment it is being
+// used in, such that Google Test can provide environment-specific
+// features and implementations.
+//
+// Google Test tries to automatically detect the properties of its
+// environment, so users usually don't need to worry about these
+// macros.  However, the automatic detection is not perfect.
+// Sometimes it's necessary for a user to define some of the following
+// macros in the build script to override Google Test's decisions.
+//
+// If the user doesn't define a macro in the list, Google Test will
+// provide a default definition.  After this header is #included, all
+// macros in this list will be defined to either 1 or 0.
+//
+// Notes to maintainers:
+//   - Each macro here is a user-tweakable knob; do not grow the list
+//     lightly.
+//   - Use #if to key off these macros.  Don't use #ifdef or "#if
+//     defined(...)", which will not work as these macros are ALWAYS
+//     defined.
+//
+//   GTEST_HAS_CLONE          - Define it to 1/0 to indicate that clone(2)
+//                              is/isn't available.
+//   GTEST_HAS_EXCEPTIONS     - Define it to 1/0 to indicate that exceptions
+//                              are enabled.
+//   GTEST_HAS_GLOBAL_STRING  - Define it to 1/0 to indicate that ::string
+//                              is/isn't available (some systems define
+//                              ::string, which is different to std::string).
+//   GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string
+//                              is/isn't available (some systems define
+//                              ::wstring, which is different to std::wstring).
+//   GTEST_HAS_POSIX_RE       - Define it to 1/0 to indicate that POSIX regular
+//                              expressions are/aren't available.
+//   GTEST_HAS_PTHREAD        - Define it to 1/0 to indicate that <pthread.h>
+//                              is/isn't available.
+//   GTEST_HAS_RTTI           - Define it to 1/0 to indicate that RTTI is/isn't
+//                              enabled.
+//   GTEST_HAS_STD_WSTRING    - Define it to 1/0 to indicate that
+//                              std::wstring does/doesn't work (Google Test can
+//                              be used where std::wstring is unavailable).
+//   GTEST_HAS_TR1_TUPLE      - Define it to 1/0 to indicate tr1::tuple
+//                              is/isn't available.
+//   GTEST_HAS_SEH            - Define it to 1/0 to indicate whether the
+//                              compiler supports Microsoft's "Structured
+//                              Exception Handling".
+//   GTEST_HAS_STREAM_REDIRECTION
+//                            - Define it to 1/0 to indicate whether the
+//                              platform supports I/O stream redirection using
+//                              dup() and dup2().
+//   GTEST_USE_OWN_TR1_TUPLE  - Define it to 1/0 to indicate whether Google
+//                              Test's own tr1 tuple implementation should be
+//                              used.  Unused when the user sets
+//                              GTEST_HAS_TR1_TUPLE to 0.
+//   GTEST_LANG_CXX11         - Define it to 1/0 to indicate that Google Test
+//                              is building in C++11/C++98 mode.
+//   GTEST_LINKED_AS_SHARED_LIBRARY
+//                            - Define to 1 when compiling tests that use
+//                              Google Test as a shared library (known as
+//                              DLL on Windows).
+//   GTEST_CREATE_SHARED_LIBRARY
+//                            - Define to 1 when compiling Google Test itself
+//                              as a shared library.
+
+// Platform-indicating macros
+// --------------------------
+//
+// Macros indicating the platform on which Google Test is being used
+// (a macro is defined to 1 if compiled on the given platform;
+// otherwise UNDEFINED -- it's never defined to 0.).  Google Test
+// defines these macros automatically.  Code outside Google Test MUST
+// NOT define them.
+//
+//   GTEST_OS_AIX      - IBM AIX
+//   GTEST_OS_CYGWIN   - Cygwin
+//   GTEST_OS_FREEBSD  - FreeBSD
+//   GTEST_OS_HPUX     - HP-UX
+//   GTEST_OS_LINUX    - Linux
+//     GTEST_OS_LINUX_ANDROID - Google Android
+//   GTEST_OS_MAC      - Mac OS X
+//     GTEST_OS_IOS    - iOS
+//   GTEST_OS_NACL     - Google Native Client (NaCl)
+//   GTEST_OS_OPENBSD  - OpenBSD
+//   GTEST_OS_QNX      - QNX
+//   GTEST_OS_SOLARIS  - Sun Solaris
+//   GTEST_OS_SYMBIAN  - Symbian
+//   GTEST_OS_WINDOWS  - Windows (Desktop, MinGW, or Mobile)
+//     GTEST_OS_WINDOWS_DESKTOP  - Windows Desktop
+//     GTEST_OS_WINDOWS_MINGW    - MinGW
+//     GTEST_OS_WINDOWS_MOBILE   - Windows Mobile
+//     GTEST_OS_WINDOWS_PHONE    - Windows Phone
+//     GTEST_OS_WINDOWS_RT       - Windows Store App/WinRT
+//   GTEST_OS_ZOS      - z/OS
+//
+// Among the platforms, Cygwin, Linux, Max OS X, and Windows have the
+// most stable support.  Since core members of the Google Test project
+// don't have access to other platforms, support for them may be less
+// stable.  If you notice any problems on your platform, please notify
+// googletestframework@googlegroups.com (patches for fixing them are
+// even more welcome!).
+//
+// It is possible that none of the GTEST_OS_* macros are defined.
+
+// Feature-indicating macros
+// -------------------------
+//
+// Macros indicating which Google Test features are available (a macro
+// is defined to 1 if the corresponding feature is supported;
+// otherwise UNDEFINED -- it's never defined to 0.).  Google Test
+// defines these macros automatically.  Code outside Google Test MUST
+// NOT define them.
+//
+// These macros are public so that portable tests can be written.
+// Such tests typically surround code using a feature with an #if
+// which controls that code.  For example:
+//
+// #if GTEST_HAS_DEATH_TEST
+//   EXPECT_DEATH(DoSomethingDeadly());
+// #endif
+//
+//   GTEST_HAS_COMBINE      - the Combine() function (for value-parameterized
+//                            tests)
+//   GTEST_HAS_DEATH_TEST   - death tests
+//   GTEST_HAS_PARAM_TEST   - value-parameterized tests
+//   GTEST_HAS_TYPED_TEST   - typed tests
+//   GTEST_HAS_TYPED_TEST_P - type-parameterized tests
+//   GTEST_IS_THREADSAFE    - Google Test is thread-safe.
+//   GTEST_USES_POSIX_RE    - enhanced POSIX regex is used. Do not confuse with
+//                            GTEST_HAS_POSIX_RE (see above) which users can
+//                            define themselves.
+//   GTEST_USES_SIMPLE_RE   - our own simple regex is used;
+//                            the above two are mutually exclusive.
+//   GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ().
+
+// Misc public macros
+// ------------------
+//
+//   GTEST_FLAG(flag_name)  - references the variable corresponding to
+//                            the given Google Test flag.
+
+// Internal utilities
+// ------------------
+//
+// The following macros and utilities are for Google Test's INTERNAL
+// use only.  Code outside Google Test MUST NOT USE THEM DIRECTLY.
+//
+// Macros for basic C++ coding:
+//   GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning.
+//   GTEST_ATTRIBUTE_UNUSED_  - declares that a class' instances or a
+//                              variable don't have to be used.
+//   GTEST_DISALLOW_ASSIGN_   - disables operator=.
+//   GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=.
+//   GTEST_MUST_USE_RESULT_   - declares that a function's result must be used.
+//   GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is
+//                                        suppressed (constant conditional).
+//   GTEST_INTENTIONAL_CONST_COND_POP_  - finish code section where MSVC C4127
+//                                        is suppressed.
+//
+// C++11 feature wrappers:
+//
+//   testing::internal::move  - portability wrapper for std::move.
+//
+// Synchronization:
+//   Mutex, MutexLock, ThreadLocal, GetThreadCount()
+//                            - synchronization primitives.
+//
+// Template meta programming:
+//   is_pointer     - as in TR1; needed on Symbian and IBM XL C/C++ only.
+//   IteratorTraits - partial implementation of std::iterator_traits, which
+//                    is not available in libCstd when compiled with Sun C++.
+//
+// Smart pointers:
+//   scoped_ptr     - as in TR2.
+//
+// Regular expressions:
+//   RE             - a simple regular expression class using the POSIX
+//                    Extended Regular Expression syntax on UNIX-like
+//                    platforms, or a reduced regular exception syntax on
+//                    other platforms, including Windows.
+//
+// Logging:
+//   GTEST_LOG_()   - logs messages at the specified severity level.
+//   LogToStderr()  - directs all log messages to stderr.
+//   FlushInfoLog() - flushes informational log messages.
+//
+// Stdout and stderr capturing:
+//   CaptureStdout()     - starts capturing stdout.
+//   GetCapturedStdout() - stops capturing stdout and returns the captured
+//                         string.
+//   CaptureStderr()     - starts capturing stderr.
+//   GetCapturedStderr() - stops capturing stderr and returns the captured
+//                         string.
+//
+// Integer types:
+//   TypeWithSize   - maps an integer to a int type.
+//   Int32, UInt32, Int64, UInt64, TimeInMillis
+//                  - integers of known sizes.
+//   BiggestInt     - the biggest signed integer type.
+//
+// Command-line utilities:
+//   GTEST_DECLARE_*()  - declares a flag.
+//   GTEST_DEFINE_*()   - defines a flag.
+//   GetInjectableArgvs() - returns the command line as a vector of strings.
+//
+// Environment variable utilities:
+//   GetEnv()             - gets the value of an environment variable.
+//   BoolFromGTestEnv()   - parses a bool environment variable.
+//   Int32FromGTestEnv()  - parses an Int32 environment variable.
+//   StringFromGTestEnv() - parses a string environment variable.
+
+#include <ctype.h>   // for isspace, etc
+#include <stddef.h>  // for ptrdiff_t
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#ifndef _WIN32_WCE
+# include <sys/types.h>
+# include <sys/stat.h>
+#endif  // !_WIN32_WCE
+
+#if defined __APPLE__
+# include <AvailabilityMacros.h>
+# include <TargetConditionals.h>
+#endif
+
+#include <algorithm>  // NOLINT
+#include <iostream>  // NOLINT
+#include <sstream>  // NOLINT
+#include <string>  // NOLINT
+#include <utility>
+#include <vector>  // NOLINT
+
+// Copyright 2015, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+// The Google C++ Testing Framework (Google Test)
+//
+// This header file defines the GTEST_OS_* macro.
+// It is separate from gtest-port.h so that custom/gtest-port.h can include it.
+
+#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
+#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
+
+// Determines the platform on which Google Test is compiled.
+#ifdef __CYGWIN__
+# define GTEST_OS_CYGWIN 1
+#elif defined __SYMBIAN32__
+# define GTEST_OS_SYMBIAN 1
+#elif defined _WIN32
+# define GTEST_OS_WINDOWS 1
+# ifdef _WIN32_WCE
+#  define GTEST_OS_WINDOWS_MOBILE 1
+# elif defined(__MINGW__) || defined(__MINGW32__)
+#  define GTEST_OS_WINDOWS_MINGW 1
+# elif defined(WINAPI_FAMILY)
+#  include <winapifamily.h>
+#  if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
+#   define GTEST_OS_WINDOWS_DESKTOP 1
+#  elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
+#   define GTEST_OS_WINDOWS_PHONE 1
+#  elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
+#   define GTEST_OS_WINDOWS_RT 1
+#  else
+    // WINAPI_FAMILY defined but no known partition matched.
+    // Default to desktop.
+#   define GTEST_OS_WINDOWS_DESKTOP 1
+#  endif
+# else
+#  define GTEST_OS_WINDOWS_DESKTOP 1
+# endif  // _WIN32_WCE
+#elif defined __APPLE__
+# define GTEST_OS_MAC 1
+# if TARGET_OS_IPHONE
+#  define GTEST_OS_IOS 1
+# endif
+#elif defined __FreeBSD__
+# define GTEST_OS_FREEBSD 1
+#elif defined __linux__
+# define GTEST_OS_LINUX 1
+# if defined __ANDROID__
+#  define GTEST_OS_LINUX_ANDROID 1
+# endif
+#elif defined __MVS__
+# define GTEST_OS_ZOS 1
+#elif defined(__sun) && defined(__SVR4)
+# define GTEST_OS_SOLARIS 1
+#elif defined(_AIX)
+# define GTEST_OS_AIX 1
+#elif defined(__hpux)
+# define GTEST_OS_HPUX 1
+#elif defined __native_client__
+# define GTEST_OS_NACL 1
+#elif defined __OpenBSD__
+# define GTEST_OS_OPENBSD 1
+#elif defined __QNX__
+# define GTEST_OS_QNX 1
+#endif  // __CYGWIN__
+
+#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
+// Copyright 2015, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+// Injection point for custom user configurations.
+// The following macros can be defined:
+//
+//   Flag related macros:
+//     GTEST_FLAG(flag_name)
+//     GTEST_USE_OWN_FLAGFILE_FLAG_  - Define to 0 when the system provides its
+//                                     own flagfile flag parsing.
+//     GTEST_DECLARE_bool_(name)
+//     GTEST_DECLARE_int32_(name)
+//     GTEST_DECLARE_string_(name)
+//     GTEST_DEFINE_bool_(name, default_val, doc)
+//     GTEST_DEFINE_int32_(name, default_val, doc)
+//     GTEST_DEFINE_string_(name, default_val, doc)
+//
+//   Test filtering:
+//     GTEST_TEST_FILTER_ENV_VAR_ - The name of an environment variable that
+//                                  will be used if --GTEST_FLAG(test_filter)
+//                                  is not provided.
+//
+//   Logging:
+//     GTEST_LOG_(severity)
+//     GTEST_CHECK_(condition)
+//     Functions LogToStderr() and FlushInfoLog() have to be provided too.
+//
+//   Threading:
+//     GTEST_HAS_NOTIFICATION_ - Enabled if Notification is already provided.
+//     GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ - Enabled if Mutex and ThreadLocal are
+//                                         already provided.
+//     Must also provide GTEST_DECLARE_STATIC_MUTEX_(mutex) and
+//     GTEST_DEFINE_STATIC_MUTEX_(mutex)
+//
+//     GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
+//     GTEST_LOCK_EXCLUDED_(locks)
+//
+// ** Custom implementation starts here **
+
+#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
+#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
+
+#endif  // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
+
+#if !defined(GTEST_DEV_EMAIL_)
+# define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com"
+# define GTEST_FLAG_PREFIX_ "gtest_"
+# define GTEST_FLAG_PREFIX_DASH_ "gtest-"
+# define GTEST_FLAG_PREFIX_UPPER_ "GTEST_"
+# define GTEST_NAME_ "Google Test"
+# define GTEST_PROJECT_URL_ "http://code.google.com/p/googletest/"
+#endif  // !defined(GTEST_DEV_EMAIL_)
+
+#if !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
+# define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest"
+#endif  // !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
+
+// Determines the version of gcc that is used to compile this.
+#ifdef __GNUC__
+// 40302 means version 4.3.2.
+# define GTEST_GCC_VER_ \
+    (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__)
+#endif  // __GNUC__
+
+// Macros for disabling Microsoft Visual C++ warnings.
+//
+//   GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385)
+//   /* code that triggers warnings C4800 and C4385 */
+//   GTEST_DISABLE_MSC_WARNINGS_POP_()
+#if _MSC_VER >= 1500
+# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \
+    __pragma(warning(push))                        \
+    __pragma(warning(disable: warnings))
+# define GTEST_DISABLE_MSC_WARNINGS_POP_()          \
+    __pragma(warning(pop))
+#else
+// Older versions of MSVC don't have __pragma.
+# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
+# define GTEST_DISABLE_MSC_WARNINGS_POP_()
+#endif
+
+#ifndef GTEST_LANG_CXX11
+// gcc and clang define __GXX_EXPERIMENTAL_CXX0X__ when
+// -std={c,gnu}++{0x,11} is passed.  The C++11 standard specifies a
+// value for __cplusplus, and recent versions of clang, gcc, and
+// probably other compilers set that too in C++11 mode.
+# if __GXX_EXPERIMENTAL_CXX0X__ || __cplusplus >= 201103L
+// Compiling in at least C++11 mode.
+#  define GTEST_LANG_CXX11 1
+# else
+#  define GTEST_LANG_CXX11 0
+# endif
+#endif
+
+// Distinct from C++11 language support, some environments don't provide
+// proper C++11 library support. Notably, it's possible to build in
+// C++11 mode when targeting Mac OS X 10.6, which has an old libstdc++
+// with no C++11 support.
+//
+// libstdc++ has sufficient C++11 support as of GCC 4.6.0, __GLIBCXX__
+// 20110325, but maintenance releases in the 4.4 and 4.5 series followed
+// this date, so check for those versions by their date stamps.
+// https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html#abi.versioning
+#if GTEST_LANG_CXX11 && \
+    (!defined(__GLIBCXX__) || ( \
+        __GLIBCXX__ >= 20110325ul &&  /* GCC >= 4.6.0 */ \
+        /* Blacklist of patch releases of older branches: */ \
+        __GLIBCXX__ != 20110416ul &&  /* GCC 4.4.6 */ \
+        __GLIBCXX__ != 20120313ul &&  /* GCC 4.4.7 */ \
+        __GLIBCXX__ != 20110428ul &&  /* GCC 4.5.3 */ \
+        __GLIBCXX__ != 20120702ul))   /* GCC 4.5.4 */
+# define GTEST_STDLIB_CXX11 1
+#endif
+
+// Only use C++11 library features if the library provides them.
+#if GTEST_STDLIB_CXX11
+# define GTEST_HAS_STD_BEGIN_AND_END_ 1
+# define GTEST_HAS_STD_FORWARD_LIST_ 1
+# define GTEST_HAS_STD_FUNCTION_ 1
+# define GTEST_HAS_STD_INITIALIZER_LIST_ 1
+# define GTEST_HAS_STD_MOVE_ 1
+# define GTEST_HAS_STD_SHARED_PTR_ 1
+# define GTEST_HAS_STD_TYPE_TRAITS_ 1
+# define GTEST_HAS_STD_UNIQUE_PTR_ 1
+#endif
+
+// C++11 specifies that <tuple> provides std::tuple.
+// Some platforms still might not have it, however.
+#if GTEST_LANG_CXX11
+# define GTEST_HAS_STD_TUPLE_ 1
+# if defined(__clang__)
+// Inspired by http://clang.llvm.org/docs/LanguageExtensions.html#__has_include
+#  if defined(__has_include) && !__has_include(<tuple>)
+#   undef GTEST_HAS_STD_TUPLE_
+#  endif
+# elif defined(_MSC_VER)
+// Inspired by boost/config/stdlib/dinkumware.hpp
+#  if defined(_CPPLIB_VER) && _CPPLIB_VER < 520
+#   undef GTEST_HAS_STD_TUPLE_
+#  endif
+# elif defined(__GLIBCXX__)
+// Inspired by boost/config/stdlib/libstdcpp3.hpp,
+// http://gcc.gnu.org/gcc-4.2/changes.html and
+// http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt01ch01.html#manual.intro.status.standard.200x
+#  if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)
+#   undef GTEST_HAS_STD_TUPLE_
+#  endif
+# endif
+#endif
+
+// Brings in definitions for functions used in the testing::internal::posix
+// namespace (read, write, close, chdir, isatty, stat). We do not currently
+// use them on Windows Mobile.
+#if GTEST_OS_WINDOWS
+# if !GTEST_OS_WINDOWS_MOBILE
+#  include <direct.h>
+#  include <io.h>
+# endif
+// In order to avoid having to include <windows.h>, use forward declaration
+// assuming CRITICAL_SECTION is a typedef of _RTL_CRITICAL_SECTION.
+// This assumption is verified by
+// WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION.
+struct _RTL_CRITICAL_SECTION;
+#else
+// This assumes that non-Windows OSes provide unistd.h. For OSes where this
+// is not the case, we need to include headers that provide the functions
+// mentioned above.
+# include <unistd.h>
+# include <strings.h>
+#endif  // GTEST_OS_WINDOWS
+
+#if GTEST_OS_LINUX_ANDROID
+// Used to define __ANDROID_API__ matching the target NDK API level.
+#  include <android/api-level.h>  // NOLINT
+#endif
+
+// Defines this to true iff Google Test can use POSIX regular expressions.
+#ifndef GTEST_HAS_POSIX_RE
+# if GTEST_OS_LINUX_ANDROID
+// On Android, <regex.h> is only available starting with Gingerbread.
+#  define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9)
+# else
+#  define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS)
+# endif
+#endif
+
+#if GTEST_USES_PCRE
+// The appropriate headers have already been included.
+
+#elif GTEST_HAS_POSIX_RE
+
+// On some platforms, <regex.h> needs someone to define size_t, and
+// won't compile otherwise.  We can #include it here as we already
+// included <stdlib.h>, which is guaranteed to define size_t through
+// <stddef.h>.
+# include <regex.h>  // NOLINT
+
+# define GTEST_USES_POSIX_RE 1
+
+#elif GTEST_OS_WINDOWS
+
+// <regex.h> is not available on Windows.  Use our own simple regex
+// implementation instead.
+# define GTEST_USES_SIMPLE_RE 1
+
+#else
+
+// <regex.h> may not be available on this platform.  Use our own
+// simple regex implementation instead.
+# define GTEST_USES_SIMPLE_RE 1
+
+#endif  // GTEST_USES_PCRE
+
+#ifndef GTEST_HAS_EXCEPTIONS
+// The user didn't tell us whether exceptions are enabled, so we need
+// to figure it out.
+# if defined(_MSC_VER) || defined(__BORLANDC__)
+// MSVC's and C++Builder's implementations of the STL use the _HAS_EXCEPTIONS
+// macro to enable exceptions, so we'll do the same.
+// Assumes that exceptions are enabled by default.
+#  ifndef _HAS_EXCEPTIONS
+#   define _HAS_EXCEPTIONS 1
+#  endif  // _HAS_EXCEPTIONS
+#  define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS
+# elif defined(__clang__)
+// clang defines __EXCEPTIONS iff exceptions are enabled before clang 220714,
+// but iff cleanups are enabled after that. In Obj-C++ files, there can be
+// cleanups for ObjC exceptions which also need cleanups, even if C++ exceptions
+// are disabled. clang has __has_feature(cxx_exceptions) which checks for C++
+// exceptions starting at clang r206352, but which checked for cleanups prior to
+// that. To reliably check for C++ exception availability with clang, check for
+// __EXCEPTIONS && __has_feature(cxx_exceptions).
+#  define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions))
+# elif defined(__GNUC__) && __EXCEPTIONS
+// gcc defines __EXCEPTIONS to 1 iff exceptions are enabled.
+#  define GTEST_HAS_EXCEPTIONS 1
+# elif defined(__SUNPRO_CC)
+// Sun Pro CC supports exceptions.  However, there is no compile-time way of
+// detecting whether they are enabled or not.  Therefore, we assume that
+// they are enabled unless the user tells us otherwise.
+#  define GTEST_HAS_EXCEPTIONS 1
+# elif defined(__IBMCPP__) && __EXCEPTIONS
+// xlC defines __EXCEPTIONS to 1 iff exceptions are enabled.
+#  define GTEST_HAS_EXCEPTIONS 1
+# elif defined(__HP_aCC)
+// Exception handling is in effect by default in HP aCC compiler. It has to
+// be turned of by +noeh compiler option if desired.
+#  define GTEST_HAS_EXCEPTIONS 1
+# else
+// For other compilers, we assume exceptions are disabled to be
+// conservative.
+#  define GTEST_HAS_EXCEPTIONS 0
+# endif  // defined(_MSC_VER) || defined(__BORLANDC__)
+#endif  // GTEST_HAS_EXCEPTIONS
+
+#if !defined(GTEST_HAS_STD_STRING)
+// Even though we don't use this macro any longer, we keep it in case
+// some clients still depend on it.
+# define GTEST_HAS_STD_STRING 1
+#elif !GTEST_HAS_STD_STRING
+// The user told us that ::std::string isn't available.
+# error "Google Test cannot be used where ::std::string isn't available."
+#endif  // !defined(GTEST_HAS_STD_STRING)
+
+#ifndef GTEST_HAS_GLOBAL_STRING
+// The user didn't tell us whether ::string is available, so we need
+// to figure it out.
+
+# define GTEST_HAS_GLOBAL_STRING 0
+
+#endif  // GTEST_HAS_GLOBAL_STRING
+
+#ifndef GTEST_HAS_STD_WSTRING
+// The user didn't tell us whether ::std::wstring is available, so we need
+// to figure it out.
+// TODO(wan@google.com): uses autoconf to detect whether ::std::wstring
+//   is available.
+
+// Cygwin 1.7 and below doesn't support ::std::wstring.
+// Solaris' libc++ doesn't support it either.  Android has
+// no support for it at least as recent as Froyo (2.2).
+# define GTEST_HAS_STD_WSTRING \
+    (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS))
+
+#endif  // GTEST_HAS_STD_WSTRING
+
+#ifndef GTEST_HAS_GLOBAL_WSTRING
+// The user didn't tell us whether ::wstring is available, so we need
+// to figure it out.
+# define GTEST_HAS_GLOBAL_WSTRING \
+    (GTEST_HAS_STD_WSTRING && GTEST_HAS_GLOBAL_STRING)
+#endif  // GTEST_HAS_GLOBAL_WSTRING
+
+// Determines whether RTTI is available.
+#ifndef GTEST_HAS_RTTI
+// The user didn't tell us whether RTTI is enabled, so we need to
+// figure it out.
+
+# ifdef _MSC_VER
+
+#  ifdef _CPPRTTI  // MSVC defines this macro iff RTTI is enabled.
+#   define GTEST_HAS_RTTI 1
+#  else
+#   define GTEST_HAS_RTTI 0
+#  endif
+
+// Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled.
+# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302)
+
+#  ifdef __GXX_RTTI
+// When building against STLport with the Android NDK and with
+// -frtti -fno-exceptions, the build fails at link time with undefined
+// references to __cxa_bad_typeid. Note sure if STL or toolchain bug,
+// so disable RTTI when detected.
+#   if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \
+       !defined(__EXCEPTIONS)
+#    define GTEST_HAS_RTTI 0
+#   else
+#    define GTEST_HAS_RTTI 1
+#   endif  // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS
+#  else
+#   define GTEST_HAS_RTTI 0
+#  endif  // __GXX_RTTI
+
+// Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends
+// using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the
+// first version with C++ support.
+# elif defined(__clang__)
+
+#  define GTEST_HAS_RTTI __has_feature(cxx_rtti)
+
+// Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if
+// both the typeid and dynamic_cast features are present.
+# elif defined(__IBMCPP__) && (__IBMCPP__ >= 900)
+
+#  ifdef __RTTI_ALL__
+#   define GTEST_HAS_RTTI 1
+#  else
+#   define GTEST_HAS_RTTI 0
+#  endif
+
+# else
+
+// For all other compilers, we assume RTTI is enabled.
+#  define GTEST_HAS_RTTI 1
+
+# endif  // _MSC_VER
+
+#endif  // GTEST_HAS_RTTI
+
+// It's this header's responsibility to #include <typeinfo> when RTTI
+// is enabled.
+#if GTEST_HAS_RTTI
+# include <typeinfo>
+#endif
+
+// Determines whether Google Test can use the pthreads library.
+#ifndef GTEST_HAS_PTHREAD
+// The user didn't tell us explicitly, so we make reasonable assumptions about
+// which platforms have pthreads support.
+//
+// To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0
+// to your compiler flags.
+# define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX \
+    || GTEST_OS_QNX || GTEST_OS_FREEBSD || GTEST_OS_NACL)
+#endif  // GTEST_HAS_PTHREAD
+
+#if GTEST_HAS_PTHREAD
+// gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is
+// true.
+# include <pthread.h>  // NOLINT
+
+// For timespec and nanosleep, used below.
+# include <time.h>  // NOLINT
+#endif
+
+// Determines if hash_map/hash_set are available.
+// Only used for testing against those containers.
+#if !defined(GTEST_HAS_HASH_MAP_)
+# if _MSC_VER
+#  define GTEST_HAS_HASH_MAP_ 1  // Indicates that hash_map is available.
+#  define GTEST_HAS_HASH_SET_ 1  // Indicates that hash_set is available.
+# endif  // _MSC_VER
+#endif  // !defined(GTEST_HAS_HASH_MAP_)
+
+// Determines whether Google Test can use tr1/tuple.  You can define
+// this macro to 0 to prevent Google Test from using tuple (any
+// feature depending on tuple with be disabled in this mode).
+#ifndef GTEST_HAS_TR1_TUPLE
+# if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR)
+// STLport, provided with the Android NDK, has neither <tr1/tuple> or <tuple>.
+#  define GTEST_HAS_TR1_TUPLE 0
+# else
+// The user didn't tell us not to do it, so we assume it's OK.
+#  define GTEST_HAS_TR1_TUPLE 1
+# endif
+#endif  // GTEST_HAS_TR1_TUPLE
+
+// Determines whether Google Test's own tr1 tuple implementation
+// should be used.
+#ifndef GTEST_USE_OWN_TR1_TUPLE
+// The user didn't tell us, so we need to figure it out.
+
+// We use our own TR1 tuple if we aren't sure the user has an
+// implementation of it already.  At this time, libstdc++ 4.0.0+ and
+// MSVC 2010 are the only mainstream standard libraries that come
+// with a TR1 tuple implementation.  NVIDIA's CUDA NVCC compiler
+// pretends to be GCC by defining __GNUC__ and friends, but cannot
+// compile GCC's tuple implementation.  MSVC 2008 (9.0) provides TR1
+// tuple in a 323 MB Feature Pack download, which we cannot assume the
+// user has.  QNX's QCC compiler is a modified GCC but it doesn't
+// support TR1 tuple.  libc++ only provides std::tuple, in C++11 mode,
+// and it can be used with some compilers that define __GNUC__.
+# if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000) \
+      && !GTEST_OS_QNX && !defined(_LIBCPP_VERSION)) || _MSC_VER >= 1600
+#  define GTEST_ENV_HAS_TR1_TUPLE_ 1
+# endif
+
+// C++11 specifies that <tuple> provides std::tuple. Use that if gtest is used
+// in C++11 mode and libstdc++ isn't very old (binaries targeting OS X 10.6
+// can build with clang but need to use gcc4.2's libstdc++).
+# if GTEST_LANG_CXX11 && (!defined(__GLIBCXX__) || __GLIBCXX__ > 20110325)
+#  define GTEST_ENV_HAS_STD_TUPLE_ 1
+# endif
+
+# if GTEST_ENV_HAS_TR1_TUPLE_ || GTEST_ENV_HAS_STD_TUPLE_
+#  define GTEST_USE_OWN_TR1_TUPLE 0
+# else
+#  define GTEST_USE_OWN_TR1_TUPLE 1
+# endif
+
+#endif  // GTEST_USE_OWN_TR1_TUPLE
+
+// To avoid conditional compilation everywhere, we make it
+// gtest-port.h's responsibility to #include the header implementing
+// tuple.
+#if GTEST_HAS_STD_TUPLE_
+# include <tuple>  // IWYU pragma: export
+# define GTEST_TUPLE_NAMESPACE_ ::std
+#endif  // GTEST_HAS_STD_TUPLE_
+
+// We include tr1::tuple even if std::tuple is available to define printers for
+// them.
+#if GTEST_HAS_TR1_TUPLE
+# ifndef GTEST_TUPLE_NAMESPACE_
+#  define GTEST_TUPLE_NAMESPACE_ ::std::tr1
+# endif  // GTEST_TUPLE_NAMESPACE_
+
+# if GTEST_USE_OWN_TR1_TUPLE
+// This file was GENERATED by command:
+//     pump.py gtest-tuple.h.pump
+// DO NOT EDIT BY HAND!!!
+
+// Copyright 2009 Google Inc.
+// All Rights Reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+// Author: wan@google.com (Zhanyong Wan)
+
+// Implements a subset of TR1 tuple needed by Google Test and Google Mock.
+
+#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_
+#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_
+
+#include <utility>  // For ::std::pair.
+
+// The compiler used in Symbian has a bug that prevents us from declaring the
+// tuple template as a friend (it complains that tuple is redefined).  This
+// hack bypasses the bug by declaring the members that should otherwise be
+// private as public.
+// Sun Studio versions < 12 also have the above bug.
+#if defined(__SYMBIAN32__) || (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590)
+# define GTEST_DECLARE_TUPLE_AS_FRIEND_ public:
+#else
+# define GTEST_DECLARE_TUPLE_AS_FRIEND_ \
+    template <GTEST_10_TYPENAMES_(U)> friend class tuple; \
+   private:
+#endif
+
+// Visual Studio 2010, 2012, and 2013 define symbols in std::tr1 that conflict
+// with our own definitions. Therefore using our own tuple does not work on
+// those compilers.
+#if defined(_MSC_VER) && _MSC_VER >= 1600  /* 1600 is Visual Studio 2010 */
+# error "gtest's tuple doesn't compile on Visual Studio 2010 or later. \
+GTEST_USE_OWN_TR1_TUPLE must be set to 0 on those compilers."
+#endif
+
+// GTEST_n_TUPLE_(T) is the type of an n-tuple.
+#define GTEST_0_TUPLE_(T) tuple<>
+#define GTEST_1_TUPLE_(T) tuple<T##0, void, void, void, void, void, void, \
+    void, void, void>
+#define GTEST_2_TUPLE_(T) tuple<T##0, T##1, void, void, void, void, void, \
+    void, void, void>
+#define GTEST_3_TUPLE_(T) tuple<T##0, T##1, T##2, void, void, void, void, \
+    void, void, void>
+#define GTEST_4_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, void, void, void, \
+    void, void, void>
+#define GTEST_5_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, void, void, \
+    void, void, void>
+#define GTEST_6_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, T##5, void, \
+    void, void, void>
+#define GTEST_7_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, T##5, T##6, \
+    void, void, void>
+#define GTEST_8_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, T##5, T##6, \
+    T##7, void, void>
+#define GTEST_9_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, T##5, T##6, \
+    T##7, T##8, void>
+#define GTEST_10_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, T##5, T##6, \
+    T##7, T##8, T##9>
+
+// GTEST_n_TYPENAMES_(T) declares a list of n typenames.
+#define GTEST_0_TYPENAMES_(T)
+#define GTEST_1_TYPENAMES_(T) typename T##0
+#define GTEST_2_TYPENAMES_(T) typename T##0, typename T##1
+#define GTEST_3_TYPENAMES_(T) typename T##0, typename T##1, typename T##2
+#define GTEST_4_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \
+    typename T##3
+#define GTEST_5_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \
+    typename T##3, typename T##4
+#define GTEST_6_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \
+    typename T##3, typename T##4, typename T##5
+#define GTEST_7_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \
+    typename T##3, typename T##4, typename T##5, typename T##6
+#define GTEST_8_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \
+    typename T##3, typename T##4, typename T##5, typename T##6, typename T##7
+#define GTEST_9_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \
+    typename T##3, typename T##4, typename T##5, typename T##6, \
+    typename T##7, typename T##8
+#define GTEST_10_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \
+    typename T##3, typename T##4, typename T##5, typename T##6, \
+    typename T##7, typename T##8, typename T##9
+
+// In theory, defining stuff in the ::std namespace is undefined
+// behavior.  We can do this as we are playing the role of a standard
+// library vendor.
+namespace std {
+namespace tr1 {
+
+template <typename T0 = void, typename T1 = void, typename T2 = void,
+    typename T3 = void, typename T4 = void, typename T5 = void,
+    typename T6 = void, typename T7 = void, typename T8 = void,
+    typename T9 = void>
+class tuple;
+
+// Anything in namespace gtest_internal is Google Test's INTERNAL
+// IMPLEMENTATION DETAIL and MUST NOT BE USED DIRECTLY in user code.
+namespace gtest_internal {
+
+// ByRef<T>::type is T if T is a reference; otherwise it's const T&.
+template <typename T>
+struct ByRef { typedef const T& type; };  // NOLINT
+template <typename T>
+struct ByRef<T&> { typedef T& type; };  // NOLINT
+
+// A handy wrapper for ByRef.
+#define GTEST_BY_REF_(T) typename ::std::tr1::gtest_internal::ByRef<T>::type
+
+// AddRef<T>::type is T if T is a reference; otherwise it's T&.  This
+// is the same as tr1::add_reference<T>::type.
+template <typename T>
+struct AddRef { typedef T& type; };  // NOLINT
+template <typename T>
+struct AddRef<T&> { typedef T& type; };  // NOLINT
+
+// A handy wrapper for AddRef.
+#define GTEST_ADD_REF_(T) typename ::std::tr1::gtest_internal::AddRef<T>::type
+
+// A helper for implementing get<k>().
+template <int k> class Get;
+
+// A helper for implementing tuple_element<k, T>.  kIndexValid is true
+// iff k < the number of fields in tuple type T.
+template <bool kIndexValid, int kIndex, class Tuple>
+struct TupleElement;
+
+template <GTEST_10_TYPENAMES_(T)>
+struct TupleElement<true, 0, GTEST_10_TUPLE_(T) > {
+  typedef T0 type;
+};
+
+template <GTEST_10_TYPENAMES_(T)>
+struct TupleElement<true, 1, GTEST_10_TUPLE_(T) > {
+  typedef T1 type;
+};
+
+template <GTEST_10_TYPENAMES_(T)>
+struct TupleElement<true, 2, GTEST_10_TUPLE_(T) > {
+  typedef T2 type;
+};
+
+template <GTEST_10_TYPENAMES_(T)>
+struct TupleElement<true, 3, GTEST_10_TUPLE_(T) > {
+  typedef T3 type;
+};
+
+template <GTEST_10_TYPENAMES_(T)>
+struct TupleElement<true, 4, GTEST_10_TUPLE_(T) > {
+  typedef T4 type;
+};
+
+template <GTEST_10_TYPENAMES_(T)>
+struct TupleElement<true, 5, GTEST_10_TUPLE_(T) > {
+  typedef T5 type;
+};
+
+template <GTEST_10_TYPENAMES_(T)>
+struct TupleElement<true, 6, GTEST_10_TUPLE_(T) > {
+  typedef T6 type;
+};
+
+template <GTEST_10_TYPENAMES_(T)>
+struct TupleElement<true, 7, GTEST_10_TUPLE_(T) > {
+  typedef T7 type;
+};
+
+template <GTEST_10_TYPENAMES_(T)>
+struct TupleElement<true, 8, GTEST_10_TUPLE_(T) > {
+  typedef T8 type;
+};
+
+template <GTEST_10_TYPENAMES_(T)>
+struct TupleElement<true, 9, GTEST_10_TUPLE_(T) > {
+  typedef T9 type;
+};
+
+}  // namespace gtest_internal
+
+template <>
+class tuple<> {
+ public:
+  tuple() {}
+  tuple(const tuple& /* t */)  {}
+  tuple& operator=(const tuple& /* t */) { return *this; }
+};
+
+template <GTEST_1_TYPENAMES_(T)>
+class GTEST_1_TUPLE_(T) {
+ public:
+  template <int k> friend class gtest_internal::Get;
+
+  tuple() : f0_() {}
+
+  explicit tuple(GTEST_BY_REF_(T0) f0) : f0_(f0) {}
+
+  tuple(const tuple& t) : f0_(t.f0_) {}
+
+  template <GTEST_1_TYPENAMES_(U)>
+  tuple(const GTEST_1_TUPLE_(U)& t) : f0_(t.f0_) {}
+
+  tuple& operator=(const tuple& t) { return CopyFrom(t); }
+
+  template <GTEST_1_TYPENAMES_(U)>
+  tuple& operator=(const GTEST_1_TUPLE_(U)& t) {
+    return CopyFrom(t);
+  }
+
+  GTEST_DECLARE_TUPLE_AS_FRIEND_
+
+  template <GTEST_1_TYPENAMES_(U)>
+  tuple& CopyFrom(const GTEST_1_TUPLE_(U)& t) {
+    f0_ = t.f0_;
+    return *this;
+  }
+
+  T0 f0_;
+};
+
+template <GTEST_2_TYPENAMES_(T)>
+class GTEST_2_TUPLE_(T) {
+ public:
+  template <int k> friend class gtest_internal::Get;
+
+  tuple() : f0_(), f1_() {}
+
+  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1) : f0_(f0),
+      f1_(f1) {}
+
+  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_) {}
+
+  template <GTEST_2_TYPENAMES_(U)>
+  tuple(const GTEST_2_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_) {}
+  template <typename U0, typename U1>
+  tuple(const ::std::pair<U0, U1>& p) : f0_(p.first), f1_(p.second) {}
+
+  tuple& operator=(const tuple& t) { return CopyFrom(t); }
+
+  template <GTEST_2_TYPENAMES_(U)>
+  tuple& operator=(const GTEST_2_TUPLE_(U)& t) {
+    return CopyFrom(t);
+  }
+  template <typename U0, typename U1>
+  tuple& operator=(const ::std::pair<U0, U1>& p) {
+    f0_ = p.first;
+    f1_ = p.second;
+    return *this;
+  }
+
+  GTEST_DECLARE_TUPLE_AS_FRIEND_
+
+  template <GTEST_2_TYPENAMES_(U)>
+  tuple& CopyFrom(const GTEST_2_TUPLE_(U)& t) {
+    f0_ = t.f0_;
+    f1_ = t.f1_;
+    return *this;
+  }
+
+  T0 f0_;
+  T1 f1_;
+};
+
+template <GTEST_3_TYPENAMES_(T)>
+class GTEST_3_TUPLE_(T) {
+ public:
+  template <int k> friend class gtest_internal::Get;
+
+  tuple() : f0_(), f1_(), f2_() {}
+
+  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
+      GTEST_BY_REF_(T2) f2) : f0_(f0), f1_(f1), f2_(f2) {}
+
+  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {}
+
+  template <GTEST_3_TYPENAMES_(U)>
+  tuple(const GTEST_3_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {}
+
+  tuple& operator=(const tuple& t) { return CopyFrom(t); }
+
+  template <GTEST_3_TYPENAMES_(U)>
+  tuple& operator=(const GTEST_3_TUPLE_(U)& t) {
+    return CopyFrom(t);
+  }
+
+  GTEST_DECLARE_TUPLE_AS_FRIEND_
+
+  template <GTEST_3_TYPENAMES_(U)>
+  tuple& CopyFrom(const GTEST_3_TUPLE_(U)& t) {
+    f0_ = t.f0_;
+    f1_ = t.f1_;
+    f2_ = t.f2_;
+    return *this;
+  }
+
+  T0 f0_;
+  T1 f1_;
+  T2 f2_;
+};
+
+template <GTEST_4_TYPENAMES_(T)>
+class GTEST_4_TUPLE_(T) {
+ public:
+  template <int k> friend class gtest_internal::Get;
+
+  tuple() : f0_(), f1_(), f2_(), f3_() {}
+
+  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
+      GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3) : f0_(f0), f1_(f1), f2_(f2),
+      f3_(f3) {}
+
+  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_) {}
+
+  template <GTEST_4_TYPENAMES_(U)>
+  tuple(const GTEST_4_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_),
+      f3_(t.f3_) {}
+
+  tuple& operator=(const tuple& t) { return CopyFrom(t); }
+
+  template <GTEST_4_TYPENAMES_(U)>
+  tuple& operator=(const GTEST_4_TUPLE_(U)& t) {
+    return CopyFrom(t);
+  }
+
+  GTEST_DECLARE_TUPLE_AS_FRIEND_
+
+  template <GTEST_4_TYPENAMES_(U)>
+  tuple& CopyFrom(const GTEST_4_TUPLE_(U)& t) {
+    f0_ = t.f0_;
+    f1_ = t.f1_;
+    f2_ = t.f2_;
+    f3_ = t.f3_;
+    return *this;
+  }
+
+  T0 f0_;
+  T1 f1_;
+  T2 f2_;
+  T3 f3_;
+};
+
+template <GTEST_5_TYPENAMES_(T)>
+class GTEST_5_TUPLE_(T) {
+ public:
+  template <int k> friend class gtest_internal::Get;
+
+  tuple() : f0_(), f1_(), f2_(), f3_(), f4_() {}
+
+  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
+      GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3,
+      GTEST_BY_REF_(T4) f4) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4) {}
+
+  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_),
+      f4_(t.f4_) {}
+
+  template <GTEST_5_TYPENAMES_(U)>
+  tuple(const GTEST_5_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_),
+      f3_(t.f3_), f4_(t.f4_) {}
+
+  tuple& operator=(const tuple& t) { return CopyFrom(t); }
+
+  template <GTEST_5_TYPENAMES_(U)>
+  tuple& operator=(const GTEST_5_TUPLE_(U)& t) {
+    return CopyFrom(t);
+  }
+
+  GTEST_DECLARE_TUPLE_AS_FRIEND_
+
+  template <GTEST_5_TYPENAMES_(U)>
+  tuple& CopyFrom(const GTEST_5_TUPLE_(U)& t) {
+    f0_ = t.f0_;
+    f1_ = t.f1_;
+    f2_ = t.f2_;
+    f3_ = t.f3_;
+    f4_ = t.f4_;
+    return *this;
+  }
+
+  T0 f0_;
+  T1 f1_;
+  T2 f2_;
+  T3 f3_;
+  T4 f4_;
+};
+
+template <GTEST_6_TYPENAMES_(T)>
+class GTEST_6_TUPLE_(T) {
+ public:
+  template <int k> friend class gtest_internal::Get;
+
+  tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_() {}
+
+  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
+      GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4,
+      GTEST_BY_REF_(T5) f5) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4),
+      f5_(f5) {}
+
+  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_),
+      f4_(t.f4_), f5_(t.f5_) {}
+
+  template <GTEST_6_TYPENAMES_(U)>
+  tuple(const GTEST_6_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_),
+      f3_(t.f3_), f4_(t.f4_), f5_(t.f5_) {}
+
+  tuple& operator=(const tuple& t) { return CopyFrom(t); }
+
+  template <GTEST_6_TYPENAMES_(U)>
+  tuple& operator=(const GTEST_6_TUPLE_(U)& t) {
+    return CopyFrom(t);
+  }
+
+  GTEST_DECLARE_TUPLE_AS_FRIEND_
+
+  template <GTEST_6_TYPENAMES_(U)>
+  tuple& CopyFrom(const GTEST_6_TUPLE_(U)& t) {
+    f0_ = t.f0_;
+    f1_ = t.f1_;
+    f2_ = t.f2_;
+    f3_ = t.f3_;
+    f4_ = t.f4_;
+    f5_ = t.f5_;
+    return *this;
+  }
+
+  T0 f0_;
+  T1 f1_;
+  T2 f2_;
+  T3 f3_;
+  T4 f4_;
+  T5 f5_;
+};
+
+template <GTEST_7_TYPENAMES_(T)>
+class GTEST_7_TUPLE_(T) {
+ public:
+  template <int k> friend class gtest_internal::Get;
+
+  tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_() {}
+
+  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
+      GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4,
+      GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6) : f0_(f0), f1_(f1), f2_(f2),
+      f3_(f3), f4_(f4), f5_(f5), f6_(f6) {}
+
+  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_),
+      f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {}
+
+  template <GTEST_7_TYPENAMES_(U)>
+  tuple(const GTEST_7_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_),
+      f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {}
+
+  tuple& operator=(const tuple& t) { return CopyFrom(t); }
+
+  template <GTEST_7_TYPENAMES_(U)>
+  tuple& operator=(const GTEST_7_TUPLE_(U)& t) {
+    return CopyFrom(t);
+  }
+
+  GTEST_DECLARE_TUPLE_AS_FRIEND_
+
+  template <GTEST_7_TYPENAMES_(U)>
+  tuple& CopyFrom(const GTEST_7_TUPLE_(U)& t) {
+    f0_ = t.f0_;
+    f1_ = t.f1_;
+    f2_ = t.f2_;
+    f3_ = t.f3_;
+    f4_ = t.f4_;
+    f5_ = t.f5_;
+    f6_ = t.f6_;
+    return *this;
+  }
+
+  T0 f0_;
+  T1 f1_;
+  T2 f2_;
+  T3 f3_;
+  T4 f4_;
+  T5 f5_;
+  T6 f6_;
+};
+
+template <GTEST_8_TYPENAMES_(T)>
+class GTEST_8_TUPLE_(T) {
+ public:
+  template <int k> friend class gtest_internal::Get;
+
+  tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_() {}
+
+  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
+      GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4,
+      GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6,
+      GTEST_BY_REF_(T7) f7) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4),
+      f5_(f5), f6_(f6), f7_(f7) {}
+
+  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_),
+      f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {}
+
+  template <GTEST_8_TYPENAMES_(U)>
+  tuple(const GTEST_8_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_),
+      f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {}
+
+  tuple& operator=(const tuple& t) { return CopyFrom(t); }
+
+  template <GTEST_8_TYPENAMES_(U)>
+  tuple& operator=(const GTEST_8_TUPLE_(U)& t) {
+    return CopyFrom(t);
+  }
+
+  GTEST_DECLARE_TUPLE_AS_FRIEND_
+
+  template <GTEST_8_TYPENAMES_(U)>
+  tuple& CopyFrom(const GTEST_8_TUPLE_(U)& t) {
+    f0_ = t.f0_;
+    f1_ = t.f1_;
+    f2_ = t.f2_;
+    f3_ = t.f3_;
+    f4_ = t.f4_;
+    f5_ = t.f5_;
+    f6_ = t.f6_;
+    f7_ = t.f7_;
+    return *this;
+  }
+
+  T0 f0_;
+  T1 f1_;
+  T2 f2_;
+  T3 f3_;
+  T4 f4_;
+  T5 f5_;
+  T6 f6_;
+  T7 f7_;
+};
+
+template <GTEST_9_TYPENAMES_(T)>
+class GTEST_9_TUPLE_(T) {
+ public:
+  template <int k> friend class gtest_internal::Get;
+
+  tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_() {}
+
+  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
+      GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4,
+      GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7,
+      GTEST_BY_REF_(T8) f8) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4),
+      f5_(f5), f6_(f6), f7_(f7), f8_(f8) {}
+
+  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_),
+      f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {}
+
+  template <GTEST_9_TYPENAMES_(U)>
+  tuple(const GTEST_9_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_),
+      f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {}
+
+  tuple& operator=(const tuple& t) { return CopyFrom(t); }
+
+  template <GTEST_9_TYPENAMES_(U)>
+  tuple& operator=(const GTEST_9_TUPLE_(U)& t) {
+    return CopyFrom(t);
+  }
+
+  GTEST_DECLARE_TUPLE_AS_FRIEND_
+
+  template <GTEST_9_TYPENAMES_(U)>
+  tuple& CopyFrom(const GTEST_9_TUPLE_(U)& t) {
+    f0_ = t.f0_;
+    f1_ = t.f1_;
+    f2_ = t.f2_;
+    f3_ = t.f3_;
+    f4_ = t.f4_;
+    f5_ = t.f5_;
+    f6_ = t.f6_;
+    f7_ = t.f7_;
+    f8_ = t.f8_;
+    return *this;
+  }
+
+  T0 f0_;
+  T1 f1_;
+  T2 f2_;
+  T3 f3_;
+  T4 f4_;
+  T5 f5_;
+  T6 f6_;
+  T7 f7_;
+  T8 f8_;
+};
+
+template <GTEST_10_TYPENAMES_(T)>
+class tuple {
+ public:
+  template <int k> friend class gtest_internal::Get;
+
+  tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_(),
+      f9_() {}
+
+  explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1,
+      GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4,
+      GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7,
+      GTEST_BY_REF_(T8) f8, GTEST_BY_REF_(T9) f9) : f0_(f0), f1_(f1), f2_(f2),
+      f3_(f3), f4_(f4), f5_(f5), f6_(f6), f7_(f7), f8_(f8), f9_(f9) {}
+
+  tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_),
+      f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_), f9_(t.f9_) {}
+
+  template <GTEST_10_TYPENAMES_(U)>
+  tuple(const GTEST_10_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_),
+      f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_),
+      f9_(t.f9_) {}
+
+  tuple& operator=(const tuple& t) { return CopyFrom(t); }
+
+  template <GTEST_10_TYPENAMES_(U)>
+  tuple& operator=(const GTEST_10_TUPLE_(U)& t) {
+    return CopyFrom(t);
+  }
+
+  GTEST_DECLARE_TUPLE_AS_FRIEND_
+
+  template <GTEST_10_TYPENAMES_(U)>
+  tuple& CopyFrom(const GTEST_10_TUPLE_(U)& t) {
+    f0_ = t.f0_;
+    f1_ = t.f1_;
+    f2_ = t.f2_;
+    f3_ = t.f3_;
+    f4_ = t.f4_;
+    f5_ = t.f5_;
+    f6_ = t.f6_;
+    f7_ = t.f7_;
+    f8_ = t.f8_;
+    f9_ = t.f9_;
+    return *this;
+  }
+
+  T0 f0_;
+  T1 f1_;
+  T2 f2_;
+  T3 f3_;
+  T4 f4_;
+  T5 f5_;
+  T6 f6_;
+  T7 f7_;
+  T8 f8_;
+  T9 f9_;
+};
+
+// 6.1.3.2 Tuple creation functions.
+
+// Known limitations: we don't support passing an
+// std::tr1::reference_wrapper<T> to make_tuple().  And we don't
+// implement tie().
+
+inline tuple<> make_tuple() { return tuple<>(); }
+
+template <GTEST_1_TYPENAMES_(T)>
+inline GTEST_1_TUPLE_(T) make_tuple(const T0& f0) {
+  return GTEST_1_TUPLE_(T)(f0);
+}
+
+template <GTEST_2_TYPENAMES_(T)>
+inline GTEST_2_TUPLE_(T) make_tuple(const T0& f0, const T1& f1) {
+  return GTEST_2_TUPLE_(T)(f0, f1);
+}
+
+template <GTEST_3_TYPENAMES_(T)>
+inline GTEST_3_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2) {
+  return GTEST_3_TUPLE_(T)(f0, f1, f2);
+}
+
+template <GTEST_4_TYPENAMES_(T)>
+inline GTEST_4_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
+    const T3& f3) {
+  return GTEST_4_TUPLE_(T)(f0, f1, f2, f3);
+}
+
+template <GTEST_5_TYPENAMES_(T)>
+inline GTEST_5_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
+    const T3& f3, const T4& f4) {
+  return GTEST_5_TUPLE_(T)(f0, f1, f2, f3, f4);
+}
+
+template <GTEST_6_TYPENAMES_(T)>
+inline GTEST_6_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
+    const T3& f3, const T4& f4, const T5& f5) {
+  return GTEST_6_TUPLE_(T)(f0, f1, f2, f3, f4, f5);
+}
+
+template <GTEST_7_TYPENAMES_(T)>
+inline GTEST_7_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
+    const T3& f3, const T4& f4, const T5& f5, const T6& f6) {
+  return GTEST_7_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6);
+}
+
+template <GTEST_8_TYPENAMES_(T)>
+inline GTEST_8_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
+    const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7) {
+  return GTEST_8_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7);
+}
+
+template <GTEST_9_TYPENAMES_(T)>
+inline GTEST_9_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
+    const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7,
+    const T8& f8) {
+  return GTEST_9_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8);
+}
+
+template <GTEST_10_TYPENAMES_(T)>
+inline GTEST_10_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2,
+    const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7,
+    const T8& f8, const T9& f9) {
+  return GTEST_10_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8, f9);
+}
+
+// 6.1.3.3 Tuple helper classes.
+
+template <typename Tuple> struct tuple_size;
+
+template <GTEST_0_TYPENAMES_(T)>
+struct tuple_size<GTEST_0_TUPLE_(T) > {
+  static const int value = 0;
+};
+
+template <GTEST_1_TYPENAMES_(T)>
+struct tuple_size<GTEST_1_TUPLE_(T) > {
+  static const int value = 1;
+};
+
+template <GTEST_2_TYPENAMES_(T)>
+struct tuple_size<GTEST_2_TUPLE_(T) > {
+  static const int value = 2;
+};
+
+template <GTEST_3_TYPENAMES_(T)>
+struct tuple_size<GTEST_3_TUPLE_(T) > {
+  static const int value = 3;
+};
+
+template <GTEST_4_TYPENAMES_(T)>
+struct tuple_size<GTEST_4_TUPLE_(T) > {
+  static const int value = 4;
+};
+
+template <GTEST_5_TYPENAMES_(T)>
+struct tuple_size<GTEST_5_TUPLE_(T) > {
+  static const int value = 5;
+};
+
+template <GTEST_6_TYPENAMES_(T)>
+struct tuple_size<GTEST_6_TUPLE_(T) > {
+  static const int value = 6;
+};
+
+template <GTEST_7_TYPENAMES_(T)>
+struct tuple_size<GTEST_7_TUPLE_(T) > {
+  static const int value = 7;
+};
+
+template <GTEST_8_TYPENAMES_(T)>
+struct tuple_size<GTEST_8_TUPLE_(T) > {
+  static const int value = 8;
+};
+
+template <GTEST_9_TYPENAMES_(T)>
+struct tuple_size<GTEST_9_TUPLE_(T) > {
+  static const int value = 9;
+};
+
+template <GTEST_10_TYPENAMES_(T)>
+struct tuple_size<GTEST_10_TUPLE_(T) > {
+  static const int value = 10;
+};
+
+template <int k, class Tuple>
+struct tuple_element {
+  typedef typename gtest_internal::TupleElement<
+      k < (tuple_size<Tuple>::value), k, Tuple>::type type;
+};
+
+#define GTEST_TUPLE_ELEMENT_(k, Tuple) typename tuple_element<k, Tuple >::type
+
+// 6.1.3.4 Element access.
+
+namespace gtest_internal {
+
+template <>
+class Get<0> {
+ public:
+  template <class Tuple>
+  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple))
+  Field(Tuple& t) { return t.f0_; }  // NOLINT
+
+  template <class Tuple>
+  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple))
+  ConstField(const Tuple& t) { return t.f0_; }
+};
+
+template <>
+class Get<1> {
+ public:
+  template <class Tuple>
+  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple))
+  Field(Tuple& t) { return t.f1_; }  // NOLINT
+
+  template <class Tuple>
+  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple))
+  ConstField(const Tuple& t) { return t.f1_; }
+};
+
+template <>
+class Get<2> {
+ public:
+  template <class Tuple>
+  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple))
+  Field(Tuple& t) { return t.f2_; }  // NOLINT
+
+  template <class Tuple>
+  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple))
+  ConstField(const Tuple& t) { return t.f2_; }
+};
+
+template <>
+class Get<3> {
+ public:
+  template <class Tuple>
+  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple))
+  Field(Tuple& t) { return t.f3_; }  // NOLINT
+
+  template <class Tuple>
+  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple))
+  ConstField(const Tuple& t) { return t.f3_; }
+};
+
+template <>
+class Get<4> {
+ public:
+  template <class Tuple>
+  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple))
+  Field(Tuple& t) { return t.f4_; }  // NOLINT
+
+  template <class Tuple>
+  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple))
+  ConstField(const Tuple& t) { return t.f4_; }
+};
+
+template <>
+class Get<5> {
+ public:
+  template <class Tuple>
+  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple))
+  Field(Tuple& t) { return t.f5_; }  // NOLINT
+
+  template <class Tuple>
+  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple))
+  ConstField(const Tuple& t) { return t.f5_; }
+};
+
+template <>
+class Get<6> {
+ public:
+  template <class Tuple>
+  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple))
+  Field(Tuple& t) { return t.f6_; }  // NOLINT
+
+  template <class Tuple>
+  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple))
+  ConstField(const Tuple& t) { return t.f6_; }
+};
+
+template <>
+class Get<7> {
+ public:
+  template <class Tuple>
+  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple))
+  Field(Tuple& t) { return t.f7_; }  // NOLINT
+
+  template <class Tuple>
+  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple))
+  ConstField(const Tuple& t) { return t.f7_; }
+};
+
+template <>
+class Get<8> {
+ public:
+  template <class Tuple>
+  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple))
+  Field(Tuple& t) { return t.f8_; }  // NOLINT
+
+  template <class Tuple>
+  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple))
+  ConstField(const Tuple& t) { return t.f8_; }
+};
+
+template <>
+class Get<9> {
+ public:
+  template <class Tuple>
+  static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple))
+  Field(Tuple& t) { return t.f9_; }  // NOLINT
+
+  template <class Tuple>
+  static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple))
+  ConstField(const Tuple& t) { return t.f9_; }
+};
+
+}  // namespace gtest_internal
+
+template <int k, GTEST_10_TYPENAMES_(T)>
+GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_10_TUPLE_(T)))
+get(GTEST_10_TUPLE_(T)& t) {
+  return gtest_internal::Get<k>::Field(t);
+}
+
+template <int k, GTEST_10_TYPENAMES_(T)>
+GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(k,  GTEST_10_TUPLE_(T)))
+get(const GTEST_10_TUPLE_(T)& t) {
+  return gtest_internal::Get<k>::ConstField(t);
+}
+
+// 6.1.3.5 Relational operators
+
+// We only implement == and !=, as we don't have a need for the rest yet.
+
+namespace gtest_internal {
+
+// SameSizeTuplePrefixComparator<k, k>::Eq(t1, t2) returns true if the
+// first k fields of t1 equals the first k fields of t2.
+// SameSizeTuplePrefixComparator(k1, k2) would be a compiler error if
+// k1 != k2.
+template <int kSize1, int kSize2>
+struct SameSizeTuplePrefixComparator;
+
+template <>
+struct SameSizeTuplePrefixComparator<0, 0> {
+  template <class Tuple1, class Tuple2>
+  static bool Eq(const Tuple1& /* t1 */, const Tuple2& /* t2 */) {
+    return true;
+  }
+};
+
+template <int k>
+struct SameSizeTuplePrefixComparator<k, k> {
+  template <class Tuple1, class Tuple2>
+  static bool Eq(const Tuple1& t1, const Tuple2& t2) {
+    return SameSizeTuplePrefixComparator<k - 1, k - 1>::Eq(t1, t2) &&
+        ::std::tr1::get<k - 1>(t1) == ::std::tr1::get<k - 1>(t2);
+  }
+};
+
+}  // namespace gtest_internal
+
+template <GTEST_10_TYPENAMES_(T), GTEST_10_TYPENAMES_(U)>
+inline bool operator==(const GTEST_10_TUPLE_(T)& t,
+                       const GTEST_10_TUPLE_(U)& u) {
+  return gtest_internal::SameSizeTuplePrefixComparator<
+      tuple_size<GTEST_10_TUPLE_(T) >::value,
+      tuple_size<GTEST_10_TUPLE_(U) >::value>::Eq(t, u);
+}
+
+template <GTEST_10_TYPENAMES_(T), GTEST_10_TYPENAMES_(U)>
+inline bool operator!=(const GTEST_10_TUPLE_(T)& t,
+                       const GTEST_10_TUPLE_(U)& u) { return !(t == u); }
+
+// 6.1.4 Pairs.
+// Unimplemented.
+
+}  // namespace tr1
+}  // namespace std
+
+#undef GTEST_0_TUPLE_
+#undef GTEST_1_TUPLE_
+#undef GTEST_2_TUPLE_
+#undef GTEST_3_TUPLE_
+#undef GTEST_4_TUPLE_
+#undef GTEST_5_TUPLE_
+#undef GTEST_6_TUPLE_
+#undef GTEST_7_TUPLE_
+#undef GTEST_8_TUPLE_
+#undef GTEST_9_TUPLE_
+#undef GTEST_10_TUPLE_
+
+#undef GTEST_0_TYPENAMES_
+#undef GTEST_1_TYPENAMES_
+#undef GTEST_2_TYPENAMES_
+#undef GTEST_3_TYPENAMES_
+#undef GTEST_4_TYPENAMES_
+#undef GTEST_5_TYPENAMES_
+#undef GTEST_6_TYPENAMES_
+#undef GTEST_7_TYPENAMES_
+#undef GTEST_8_TYPENAMES_
+#undef GTEST_9_TYPENAMES_
+#undef GTEST_10_TYPENAMES_
+
+#undef GTEST_DECLARE_TUPLE_AS_FRIEND_
+#undef GTEST_BY_REF_
+#undef GTEST_ADD_REF_
+#undef GTEST_TUPLE_ELEMENT_
+
+#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_
+# elif GTEST_ENV_HAS_STD_TUPLE_
+#  include <tuple>
+// C++11 puts its tuple into the ::std namespace rather than
+// ::std::tr1.  gtest expects tuple to live in ::std::tr1, so put it there.
+// This causes undefined behavior, but supported compilers react in
+// the way we intend.
+namespace std {
+namespace tr1 {
+using ::std::get;
+using ::std::make_tuple;
+using ::std::tuple;
+using ::std::tuple_element;
+using ::std::tuple_size;
+}
+}
+
+# elif GTEST_OS_SYMBIAN
+
+// On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to
+// use STLport's tuple implementation, which unfortunately doesn't
+// work as the copy of STLport distributed with Symbian is incomplete.
+// By making sure BOOST_HAS_TR1_TUPLE is undefined, we force Boost to
+// use its own tuple implementation.
+#  ifdef BOOST_HAS_TR1_TUPLE
+#   undef BOOST_HAS_TR1_TUPLE
+#  endif  // BOOST_HAS_TR1_TUPLE
+
+// This prevents <boost/tr1/detail/config.hpp>, which defines
+// BOOST_HAS_TR1_TUPLE, from being #included by Boost's <tuple>.
+#  define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED
+#  include <tuple>  // IWYU pragma: export  // NOLINT
+
+# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000)
+// GCC 4.0+ implements tr1/tuple in the <tr1/tuple> header.  This does
+// not conform to the TR1 spec, which requires the header to be <tuple>.
+
+#  if !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302
+// Until version 4.3.2, gcc has a bug that causes <tr1/functional>,
+// which is #included by <tr1/tuple>, to not compile when RTTI is
+// disabled.  _TR1_FUNCTIONAL is the header guard for
+// <tr1/functional>.  Hence the following #define is a hack to prevent
+// <tr1/functional> from being included.
+#   define _TR1_FUNCTIONAL 1
+#   include <tr1/tuple>
+#   undef _TR1_FUNCTIONAL  // Allows the user to #include
+                        // <tr1/functional> if he chooses to.
+#  else
+#   include <tr1/tuple>  // NOLINT
+#  endif  // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302
+
+# else
+// If the compiler is not GCC 4.0+, we assume the user is using a
+// spec-conforming TR1 implementation.
+#  include <tuple>  // IWYU pragma: export  // NOLINT
+# endif  // GTEST_USE_OWN_TR1_TUPLE
+
+#endif  // GTEST_HAS_TR1_TUPLE
+
+// Determines whether clone(2) is supported.
+// Usually it will only be available on Linux, excluding
+// Linux on the Itanium architecture.
+// Also see http://linux.die.net/man/2/clone.
+#ifndef GTEST_HAS_CLONE
+// The user didn't tell us, so we need to figure it out.
+
+# if GTEST_OS_LINUX && !defined(__ia64__)
+#  if GTEST_OS_LINUX_ANDROID
+// On Android, clone() is only available on ARM starting with Gingerbread.
+#    if defined(__arm__) && __ANDROID_API__ >= 9
+#     define GTEST_HAS_CLONE 1
+#    else
+#     define GTEST_HAS_CLONE 0
+#    endif
+#  else
+#   define GTEST_HAS_CLONE 1
+#  endif
+# else
+#  define GTEST_HAS_CLONE 0
+# endif  // GTEST_OS_LINUX && !defined(__ia64__)
+
+#endif  // GTEST_HAS_CLONE
+
+// Determines whether to support stream redirection. This is used to test
+// output correctness and to implement death tests.
+#ifndef GTEST_HAS_STREAM_REDIRECTION
+// By default, we assume that stream redirection is supported on all
+// platforms except known mobile ones.
+# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || \
+    GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
+#  define GTEST_HAS_STREAM_REDIRECTION 0
+# else
+#  define GTEST_HAS_STREAM_REDIRECTION 1
+# endif  // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN
+#endif  // GTEST_HAS_STREAM_REDIRECTION
+
+// Determines whether to support death tests.
+// Google Test does not support death tests for VC 7.1 and earlier as
+// abort() in a VC 7.1 application compiled as GUI in debug config
+// pops up a dialog window that cannot be suppressed programmatically.
+#if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
+     (GTEST_OS_MAC && !GTEST_OS_IOS) || \
+     (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \
+     GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \
+     GTEST_OS_OPENBSD || GTEST_OS_QNX || GTEST_OS_FREEBSD)
+# define GTEST_HAS_DEATH_TEST 1
+#endif
+
+// We don't support MSVC 7.1 with exceptions disabled now.  Therefore
+// all the compilers we care about are adequate for supporting
+// value-parameterized tests.
+#define GTEST_HAS_PARAM_TEST 1
+
+// Determines whether to support type-driven tests.
+
+// Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0,
+// Sun Pro CC, IBM Visual Age, and HP aCC support.
+#if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \
+    defined(__IBMCPP__) || defined(__HP_aCC)
+# define GTEST_HAS_TYPED_TEST 1
+# define GTEST_HAS_TYPED_TEST_P 1
+#endif
+
+// Determines whether to support Combine(). This only makes sense when
+// value-parameterized tests are enabled.  The implementation doesn't
+// work on Sun Studio since it doesn't understand templated conversion
+// operators.
+#if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE && !defined(__SUNPRO_CC)
+# define GTEST_HAS_COMBINE 1
+#endif
+
+// Determines whether the system compiler uses UTF-16 for encoding wide strings.
+#define GTEST_WIDE_STRING_USES_UTF16_ \
+    (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX)
+
+// Determines whether test results can be streamed to a socket.
+#if GTEST_OS_LINUX
+# define GTEST_CAN_STREAM_RESULTS_ 1
+#endif
+
+// Defines some utility macros.
+
+// The GNU compiler emits a warning if nested "if" statements are followed by
+// an "else" statement and braces are not used to explicitly disambiguate the
+// "else" binding.  This leads to problems with code like:
+//
+//   if (gate)
+//     ASSERT_*(condition) << "Some message";
+//
+// The "switch (0) case 0:" idiom is used to suppress this.
+#ifdef __INTEL_COMPILER
+# define GTEST_AMBIGUOUS_ELSE_BLOCKER_
+#else
+# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default:  // NOLINT
+#endif
+
+// Use this annotation at the end of a struct/class definition to
+// prevent the compiler from optimizing away instances that are never
+// used.  This is useful when all interesting logic happens inside the
+// c'tor and / or d'tor.  Example:
+//
+//   struct Foo {
+//     Foo() { ... }
+//   } GTEST_ATTRIBUTE_UNUSED_;
+//
+// Also use it after a variable or parameter declaration to tell the
+// compiler the variable/parameter does not have to be used.
+#if defined(__GNUC__) && !defined(COMPILER_ICC)
+# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
+#elif defined(__clang__)
+# if __has_attribute(unused)
+#  define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
+# endif
+#endif
+#ifndef GTEST_ATTRIBUTE_UNUSED_
+# define GTEST_ATTRIBUTE_UNUSED_
+#endif
+
+// A macro to disallow operator=
+// This should be used in the private: declarations for a class.
+#define GTEST_DISALLOW_ASSIGN_(type)\
+  void operator=(type const &)
+
+// A macro to disallow copy constructor and operator=
+// This should be used in the private: declarations for a class.
+#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\
+  type(type const &);\
+  GTEST_DISALLOW_ASSIGN_(type)
+
+// Tell the compiler to warn about unused return values for functions declared
+// with this macro.  The macro should be used on function declarations
+// following the argument list:
+//
+//   Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_;
+#if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC)
+# define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result))
+#else
+# define GTEST_MUST_USE_RESULT_
+#endif  // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC
+
+// MS C++ compiler emits warning when a conditional expression is compile time
+// constant. In some contexts this warning is false positive and needs to be
+// suppressed. Use the following two macros in such cases:
+//
+// GTEST_INTENTIONAL_CONST_COND_PUSH_()
+// while (true) {
+// GTEST_INTENTIONAL_CONST_COND_POP_()
+// }
+# define GTEST_INTENTIONAL_CONST_COND_PUSH_() \
+    GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127)
+# define GTEST_INTENTIONAL_CONST_COND_POP_() \
+    GTEST_DISABLE_MSC_WARNINGS_POP_()
+
+// Determine whether the compiler supports Microsoft's Structured Exception
+// Handling.  This is supported by several Windows compilers but generally
+// does not exist on any other system.
+#ifndef GTEST_HAS_SEH
+// The user didn't tell us, so we need to figure it out.
+
+# if defined(_MSC_VER) || defined(__BORLANDC__)
+// These two compilers are known to support SEH.
+#  define GTEST_HAS_SEH 1
+# else
+// Assume no SEH.
+#  define GTEST_HAS_SEH 0
+# endif
+
+#define GTEST_IS_THREADSAFE \
+    (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ \
+     || (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) \
+     || GTEST_HAS_PTHREAD)
+
+#endif  // GTEST_HAS_SEH
+
+#ifdef _MSC_VER
+# if GTEST_LINKED_AS_SHARED_LIBRARY
+#  define GTEST_API_ __declspec(dllimport)
+# elif GTEST_CREATE_SHARED_LIBRARY
+#  define GTEST_API_ __declspec(dllexport)
+# endif
+#elif __GNUC__ >= 4 || defined(__clang__)
+# define GTEST_API_ __attribute__((visibility ("default")))
+#endif // _MSC_VER
+
+#ifndef GTEST_API_
+# define GTEST_API_
+#endif
+
+#ifdef __GNUC__
+// Ask the compiler to never inline a given function.
+# define GTEST_NO_INLINE_ __attribute__((noinline))
+#else
+# define GTEST_NO_INLINE_
+#endif
+
+// _LIBCPP_VERSION is defined by the libc++ library from the LLVM project.
+#if defined(__GLIBCXX__) || defined(_LIBCPP_VERSION)
+# define GTEST_HAS_CXXABI_H_ 1
+#else
+# define GTEST_HAS_CXXABI_H_ 0
+#endif
+
+// A function level attribute to disable checking for use of uninitialized
+// memory when built with MemorySanitizer.
+#if defined(__clang__)
+# if __has_feature(memory_sanitizer)
+#  define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \
+       __attribute__((no_sanitize_memory))
+# else
+#  define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
+# endif  // __has_feature(memory_sanitizer)
+#else
+# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
+#endif  // __clang__
+
+// A function level attribute to disable AddressSanitizer instrumentation.
+#if defined(__clang__)
+# if __has_feature(address_sanitizer)
+#  define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \
+       __attribute__((no_sanitize_address))
+# else
+#  define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
+# endif  // __has_feature(address_sanitizer)
+#else
+# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
+#endif  // __clang__
+
+// A function level attribute to disable ThreadSanitizer instrumentation.
+#if defined(__clang__)
+# if __has_feature(thread_sanitizer)
+#  define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \
+       __attribute__((no_sanitize_thread))
+# else
+#  define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
+# endif  // __has_feature(thread_sanitizer)
+#else
+# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
+#endif  // __clang__
+
+namespace testing {
+
+class Message;
+
+#if defined(GTEST_TUPLE_NAMESPACE_)
+// Import tuple and friends into the ::testing namespace.
+// It is part of our interface, having them in ::testing allows us to change
+// their types as needed.
+using GTEST_TUPLE_NAMESPACE_::get;
+using GTEST_TUPLE_NAMESPACE_::make_tuple;
+using GTEST_TUPLE_NAMESPACE_::tuple;
+using GTEST_TUPLE_NAMESPACE_::tuple_size;
+using GTEST_TUPLE_NAMESPACE_::tuple_element;
+#endif  // defined(GTEST_TUPLE_NAMESPACE_)
+
+namespace internal {
+
+// A secret type that Google Test users don't know about.  It has no
+// definition on purpose.  Therefore it's impossible to create a
+// Secret object, which is what we want.
+class Secret;
+
+// The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time
+// expression is true. For example, you could use it to verify the
+// size of a static array:
+//
+//   GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES,
+//                         names_incorrect_size);
+//
+// or to make sure a struct is smaller than a certain size:
+//
+//   GTEST_COMPILE_ASSERT_(sizeof(foo) < 128, foo_too_large);
+//
+// The second argument to the macro is the name of the variable. If
+// the expression is false, most compilers will issue a warning/error
+// containing the name of the variable.
+
+#if GTEST_LANG_CXX11
+# define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg)
+#else  // !GTEST_LANG_CXX11
+template <bool>
+  struct CompileAssert {
+};
+
+# define GTEST_COMPILE_ASSERT_(expr, msg) \
+  typedef ::testing::internal::CompileAssert<(static_cast<bool>(expr))> \
+      msg[static_cast<bool>(expr) ? 1 : -1] GTEST_ATTRIBUTE_UNUSED_
+#endif  // !GTEST_LANG_CXX11
+
+// Implementation details of GTEST_COMPILE_ASSERT_:
+//
+// (In C++11, we simply use static_assert instead of the following)
+//
+// - GTEST_COMPILE_ASSERT_ works by defining an array type that has -1
+//   elements (and thus is invalid) when the expression is false.
+//
+// - The simpler definition
+//
+//    #define GTEST_COMPILE_ASSERT_(expr, msg) typedef char msg[(expr) ? 1 : -1]
+//
+//   does not work, as gcc supports variable-length arrays whose sizes
+//   are determined at run-time (this is gcc's extension and not part
+//   of the C++ standard).  As a result, gcc fails to reject the
+//   following code with the simple definition:
+//
+//     int foo;
+//     GTEST_COMPILE_ASSERT_(foo, msg); // not supposed to compile as foo is
+//                                      // not a compile-time constant.
+//
+// - By using the type CompileAssert<(bool(expr))>, we ensures that
+//   expr is a compile-time constant.  (Template arguments must be
+//   determined at compile-time.)
+//
+// - The outter parentheses in CompileAssert<(bool(expr))> are necessary
+//   to work around a bug in gcc 3.4.4 and 4.0.1.  If we had written
+//
+//     CompileAssert<bool(expr)>
+//
+//   instead, these compilers will refuse to compile
+//
+//     GTEST_COMPILE_ASSERT_(5 > 0, some_message);
+//
+//   (They seem to think the ">" in "5 > 0" marks the end of the
+//   template argument list.)
+//
+// - The array size is (bool(expr) ? 1 : -1), instead of simply
+//
+//     ((expr) ? 1 : -1).
+//
+//   This is to avoid running into a bug in MS VC 7.1, which
+//   causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1.
+
+// StaticAssertTypeEqHelper is used by StaticAssertTypeEq defined in gtest.h.
+//
+// This template is declared, but intentionally undefined.
+template <typename T1, typename T2>
+struct StaticAssertTypeEqHelper;
+
+template <typename T>
+struct StaticAssertTypeEqHelper<T, T> {
+  enum { value = true };
+};
+
+// Evaluates to the number of elements in 'array'.
+#define GTEST_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0]))
+
+#if GTEST_HAS_GLOBAL_STRING
+typedef ::string string;
+#else
+typedef ::std::string string;
+#endif  // GTEST_HAS_GLOBAL_STRING
+
+#if GTEST_HAS_GLOBAL_WSTRING
+typedef ::wstring wstring;
+#elif GTEST_HAS_STD_WSTRING
+typedef ::std::wstring wstring;
+#endif  // GTEST_HAS_GLOBAL_WSTRING
+
+// A helper for suppressing warnings on constant condition.  It just
+// returns 'condition'.
+GTEST_API_ bool IsTrue(bool condition);
+
+// Defines scoped_ptr.
+
+// This implementation of scoped_ptr is PARTIAL - it only contains
+// enough stuff to satisfy Google Test's need.
+template <typename T>
+class scoped_ptr {
+ public:
+  typedef T element_type;
+
+  explicit scoped_ptr(T* p = NULL) : ptr_(p) {}
+  ~scoped_ptr() { reset(); }
+
+  T& operator*() const { return *ptr_; }
+  T* operator->() const { return ptr_; }
+  T* get() const { return ptr_; }
+
+  T* release() {
+    T* const ptr = ptr_;
+    ptr_ = NULL;
+    return ptr;
+  }
+
+  void reset(T* p = NULL) {
+    if (p != ptr_) {
+      if (IsTrue(sizeof(T) > 0)) {  // Makes sure T is a complete type.
+        delete ptr_;
+      }
+      ptr_ = p;
+    }
+  }
+
+  friend void swap(scoped_ptr& a, scoped_ptr& b) {
+    using std::swap;
+    swap(a.ptr_, b.ptr_);
+  }
+
+ private:
+  T* ptr_;
+
+  GTEST_DISALLOW_COPY_AND_ASSIGN_(scoped_ptr);
+};
+
+// Defines RE.
+
+// A simple C++ wrapper for <regex.h>.  It uses the POSIX Extended
+// Regular Expression syntax.
+class GTEST_API_ RE {
+ public:
+  // A copy constructor is required by the Standard to initialize object
+  // references from r-values.
+  RE(const RE& other) { Init(other.pattern()); }
+
+  // Constructs an RE from a string.
+  RE(const ::std::string& regex) { Init(regex.c_str()); }  // NOLINT
+
+#if GTEST_HAS_GLOBAL_STRING
+
+  RE(const ::string& regex) { Init(regex.c_str()); }  // NOLINT
+
+#endif  // GTEST_HAS_GLOBAL_STRING
+
+  RE(const char* regex) { Init(regex); }  // NOLINT
+  ~RE();
+
+  // Returns the string representation of the regex.
+  const char* pattern() const { return pattern_; }
+
+  // FullMatch(str, re) returns true iff regular expression re matches
+  // the entire str.
+  // PartialMatch(str, re) returns true iff regular expression re
+  // matches a substring of str (including str itself).
+  //
+  // TODO(wan@google.com): make FullMatch() and PartialMatch() work
+  // when str contains NUL characters.
+  static bool FullMatch(const ::std::string& str, const RE& re) {
+    return FullMatch(str.c_str(), re);
+  }
+  static bool PartialMatch(const ::std::string& str, const RE& re) {
+    return PartialMatch(str.c_str(), re);
+  }
+
+#if GTEST_HAS_GLOBAL_STRING
+
+  static bool FullMatch(const ::string& str, const RE& re) {
+    return FullMatch(str.c_str(), re);
+  }
+  static bool PartialMatch(const ::string& str, const RE& re) {
+    return PartialMatch(str.c_str(), re);
+  }
+
+#endif  // GTEST_HAS_GLOBAL_STRING
+
+  static bool FullMatch(const char* str, const RE& re);
+  static bool PartialMatch(const char* str, const RE& re);
+
+ private:
+  void Init(const char* regex);
+
+  // We use a const char* instead of an std::string, as Google Test used to be
+  // used where std::string is not available.  TODO(wan@google.com): change to
+  // std::string.
+  const char* pattern_;
+  bool is_valid_;
+
+#if GTEST_USES_POSIX_RE
+
+  regex_t full_regex_;     // For FullMatch().
+  regex_t partial_regex_;  // For PartialMatch().
+
+#else  // GTEST_USES_SIMPLE_RE
+
+  const char* full_pattern_;  // For FullMatch();
+
+#endif
+
+  GTEST_DISALLOW_ASSIGN_(RE);
+};
+
+// Formats a source file path and a line number as they would appear
+// in an error message from the compiler used to compile this code.
+GTEST_API_ ::std::string FormatFileLocation(const char* file, int line);
+
+// Formats a file location for compiler-independent XML output.
+// Although this function is not platform dependent, we put it next to
+// FormatFileLocation in order to contrast the two functions.
+GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
+                                                               int line);
+
+// Defines logging utilities:
+//   GTEST_LOG_(severity) - logs messages at the specified severity level. The
+//                          message itself is streamed into the macro.
+//   LogToStderr()  - directs all log messages to stderr.
+//   FlushInfoLog() - flushes informational log messages.
+
+enum GTestLogSeverity {
+  GTEST_INFO,
+  GTEST_WARNING,
+  GTEST_ERROR,
+  GTEST_FATAL
+};
+
+// Formats log entry severity, provides a stream object for streaming the
+// log message, and terminates the message with a newline when going out of
+// scope.
+class GTEST_API_ GTestLog {
+ public:
+  GTestLog(GTestLogSeverity severity, const char* file, int line);
+
+  // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
+  ~GTestLog();
+
+  ::std::ostream& GetStream() { return ::std::cerr; }
+
+ private:
+  const GTestLogSeverity severity_;
+
+  GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog);
+};
+
+#if !defined(GTEST_LOG_)
+
+# define GTEST_LOG_(severity) \
+    ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \
+                               

<TRUNCATED>

[45/50] [abbrv] marmotta git commit: MARMOTTA-636: fixed Dockerfile

Posted by wi...@apache.org.
MARMOTTA-636: fixed Dockerfile


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/1eb1bceb
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/1eb1bceb
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/1eb1bceb

Branch: refs/heads/MARMOTTA-584
Commit: 1eb1bceb387af2c8ad0049979f217666a3600c95
Parents: bfe5847
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Fri Apr 29 15:51:21 2016 +0200
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Fri Apr 29 15:51:21 2016 +0200

----------------------------------------------------------------------
 .dockerignore                        |  2 +
 Dockerfile                           | 81 +++++++++++++++++++++++++++++++
 launchers/marmotta-webapp/Dockerfile | 72 ---------------------------
 3 files changed, 83 insertions(+), 72 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/1eb1bceb/.dockerignore
----------------------------------------------------------------------
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..f649579
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,2 @@
+**/target
+*~

http://git-wip-us.apache.org/repos/asf/marmotta/blob/1eb1bceb/Dockerfile
----------------------------------------------------------------------
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..33f8d60
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,81 @@
+# Dockerfile for Apache Marmotta
+
+FROM debian:jessie-backports
+MAINTAINER Sergio Fern�ndez <wi...@apache.org>
+
+EXPOSE 8080
+
+WORKDIR /src
+ADD . /src
+
+# configuration
+ENV DEBIAN_FRONTEND noninteractive
+ENV DB_NAME marmotta
+ENV DB_USER marmotta
+ENV DB_PASS s3cr3t
+ENV PG_VERSION 9.4
+ENV WAR_PATH /src/launchers/marmotta-webapp/target/marmotta.war
+ENV CONF_PATH /var/lib/marmotta/system-config.properties
+
+# prepare the environment
+RUN apt-get update \
+    && apt-get upgrade -y \
+    && apt-get install -y \
+		openjdk-8-jdk \
+		maven \
+        tomcat7 \
+    || apt-get install -y -f
+
+# build
+RUN mvn clean install -DskipTests -DskipITs
+RUN test -e $WAR_PATH || exit
+
+# install and configure postgres from the PGDG repo
+RUN apt-get update && apt-get install -y locales apt-utils \
+	&& localedef -i en_US -c -f UTF-8 -A /usr/share/locale/locale.alias en_US.UTF-8
+ENV LANG en_US.utf8
+RUN apt-key adv --keyserver ha.pool.sks-keyservers.net --recv-keys B97B0AFCAA1A47F044F244A07FCC7D46ACCC4CF8
+RUN echo 'deb http://apt.postgresql.org/pub/repos/apt/ jessie-pgdg main' > /etc/apt/sources.list.d/pgdg.list
+RUN apt-get update \
+	&& apt-get install -y postgresql-common \
+	&& sed -ri 's/#(create_main_cluster) .*$/\1 = false/' /etc/postgresql-common/createcluster.conf \
+	&& apt-get install -y \
+		postgresql-$PG_VERSION \
+		postgresql-contrib-$PG_VERSION
+RUN pg_createcluster $PG_VERSION main --start
+USER postgres
+RUN service postgresql start \
+    && psql --command "CREATE USER $DB_USER WITH PASSWORD '$DB_PASS';" \
+    && psql --command "CREATE DATABASE $DB_NAME WITH OWNER $DB_USER;"
+USER root
+RUN service postgresql stop
+RUN echo "host all  all    127.0.0.1/32  md5" >> /etc/postgresql/$PG_VERSION/main/pg_hba.conf
+RUN echo "listen_addresses='*'" >> /etc/postgresql/$PG_VERSION/main/postgresql.conf
+
+# install the webapp
+#RUN dpkg --debug=2000 --install target/marmotta_*_all.deb <-- we'd need to fix the postinst
+RUN mkdir -p /usr/share/marmotta
+RUN cp $WAR_PATH /usr/share/marmotta/
+RUN chown tomcat7:tomcat7 /usr/share/marmotta/marmotta.war
+RUN cp /src/launchers/marmotta-webapp/src/deb/tomcat/marmotta.xml /var/lib/tomcat7/conf/Catalina/localhost/
+RUN chown tomcat7:tomcat7 /var/lib/tomcat7/conf/Catalina/localhost/marmotta.xml
+RUN mkdir -p "$(dirname $CONF_PATH)"
+RUN echo "security.enabled = false" > $CONF_PATH
+RUN echo "database.type = postgres" >> $CONF_PATH
+RUN echo "database.url = jdbc:postgresql://localhost:5432/$DB_NAME?prepareThreshold=3" >> $CONF_PATH
+RUN echo "database.user = $DB_USER" >> $CONF_PATH
+RUN echo "database.password = $DB_PASS" >> $CONF_PATH
+RUN chown -R tomcat7:tomcat7 "$(dirname $CONF_PATH)"
+
+# cleanup
+RUN mvn clean \
+    && rm -rf ~/.m2 \
+    && apt-get remove maven --purge \
+    && apt-get autoremove \
+    && apt-get clean -y \
+    && apt-get autoclean -y \
+    && apt-get autoremove -y \
+    && rm -rf /var/lib/apt/lists/*
+
+ENTRYPOINT ["/marmotta-webapp/src/docker/entrypoint.sh"]
+

http://git-wip-us.apache.org/repos/asf/marmotta/blob/1eb1bceb/launchers/marmotta-webapp/Dockerfile
----------------------------------------------------------------------
diff --git a/launchers/marmotta-webapp/Dockerfile b/launchers/marmotta-webapp/Dockerfile
deleted file mode 100644
index f89585c..0000000
--- a/launchers/marmotta-webapp/Dockerfile
+++ /dev/null
@@ -1,72 +0,0 @@
-# Dockerfile for Apache Marmotta
-
-FROM debian:jessie
-MAINTAINER Sergio Fern�ndez <wi...@apache.org>
-
-EXPOSE 8080
-
-WORKDIR /marmotta-webapp
-ADD . /marmotta-webapp
-
-# configuration
-ENV DEBIAN_FRONTEND noninteractive
-ENV DB_NAME marmotta
-ENV DB_USER marmotta
-ENV DB_PASS s3cr3t
-ENV PG_VERSION 9.4
-ENV WAR_PATH target/marmotta.war
-ENV CONF_PATH /var/lib/marmotta/system-config.properties
-
-# test build
-RUN test -e $WAR_PATH || exit
-
-# install and configure postgres from the PGDG repo
-RUN apt-get update && apt-get install -y locales apt-utils \
-	&& localedef -i en_US -c -f UTF-8 -A /usr/share/locale/locale.alias en_US.UTF-8
-ENV LANG en_US.utf8
-RUN apt-key adv --keyserver ha.pool.sks-keyservers.net --recv-keys B97B0AFCAA1A47F044F244A07FCC7D46ACCC4CF8
-RUN echo 'deb http://apt.postgresql.org/pub/repos/apt/ jessie-pgdg main' > /etc/apt/sources.list.d/pgdg.list
-RUN apt-get update \
-	&& apt-get install -y postgresql-common \
-	&& sed -ri 's/#(create_main_cluster) .*$/\1 = false/' /etc/postgresql-common/createcluster.conf \
-	&& apt-get install -y \
-		postgresql-$PG_VERSION \
-		postgresql-contrib-$PG_VERSION
-RUN pg_createcluster $PG_VERSION main --start
-USER postgres
-RUN service postgresql start \
-    && psql --command "CREATE USER $DB_USER WITH PASSWORD '$DB_PASS';" \
-    && psql --command "CREATE DATABASE $DB_NAME WITH OWNER $DB_USER;"
-USER root
-RUN service postgresql stop
-RUN echo "host all  all    127.0.0.1/32  md5" >> /etc/postgresql/$PG_VERSION/main/pg_hba.conf
-RUN echo "listen_addresses='*'" >> /etc/postgresql/$PG_VERSION/main/postgresql.conf
-
-# base requirements
-RUN apt-get update \
-	&& apt-get install -y \
-		openjdk-7-jre-headless \
-		tomcat7
-RUN service tomcat7 stop
-
-# package from source code and install the webapp
-#RUN dpkg --debug=2000 --install target/marmotta_*_all.deb <-- we'd need to fix the postinst
-RUN mkdir -p /usr/share/marmotta
-RUN cp $WAR_PATH /usr/share/marmotta/
-RUN chown tomcat7:tomcat7 /usr/share/marmotta/marmotta.war
-RUN cp src/deb/tomcat/marmotta.xml /var/lib/tomcat7/conf/Catalina/localhost/
-RUN chown tomcat7:tomcat7 /var/lib/tomcat7/conf/Catalina/localhost/marmotta.xml
-RUN mkdir -p "$(dirname $CONF_PATH)"
-RUN echo "security.enabled = false" > $CONF_PATH
-RUN echo "database.type = postgres" >> $CONF_PATH
-RUN echo "database.url = jdbc:postgresql://localhost:5432/$DB_NAME?prepareThreshold=3" >> $CONF_PATH
-RUN echo "database.user = $DB_USER" >> $CONF_PATH
-RUN echo "database.password = $DB_PASS" >> $CONF_PATH
-RUN chown -R tomcat7:tomcat7 "$(dirname $CONF_PATH)"
-
-# cleanup
-#RUN mvn clean
-RUN apt-get clean -y && apt-get autoclean -y && apt-get autoremove -y && rm -rf /var/lib/apt/lists/*
-
-ENTRYPOINT ["/marmotta-webapp/src/docker/entrypoint.sh"]
-


[38/50] [abbrv] marmotta git commit: MARMOTTA-634: fixed broken link

Posted by wi...@apache.org.
MARMOTTA-634: fixed broken link


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/3e90926e
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/3e90926e
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/3e90926e

Branch: refs/heads/MARMOTTA-584
Commit: 3e90926eac4e40b2245fc7c793144d37e1764889
Parents: 5f248d7
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Tue Apr 19 08:39:13 2016 +0200
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Tue Apr 19 08:39:13 2016 +0200

----------------------------------------------------------------------
 .../marmotta-backend-kiwi/src/main/resources/web/admin/about.html  | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/3e90926e/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/about.html
----------------------------------------------------------------------
diff --git a/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/about.html b/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/about.html
index 78cf913..c6ad6bb 100644
--- a/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/about.html
+++ b/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/about.html
@@ -36,7 +36,7 @@
 </h2>
 <p>You can find all installed features on the module list on the right side. To get a quick access to common functionalities, we listed some links:</p>
 <ul>
-    <li><a href="import.html">Import your data:</a> RDF and non-RDF formats are supported.</li>
+    <li><a href="../../core/admin/import.html">Import your data:</a> RDF and non-RDF formats are supported.</li>
     <li><a href="../../sparql/admin/squebi.html">SPARQL your data:</a> full SPARQL 1.1 support including querying and updates.</li>
     <li><a href="configuration.html">Configure your database:</a> Marmotta comes with h2 embedded; configure your own database to handle bigger data.</li>
     <li><a href="dataview.html">Control your data:</a> the dataview gives an overview on the current data in the system. (Attention: there might be problems with the visualisation if big data sets).</li>


[27/50] [abbrv] marmotta git commit: MARMOTTA-628: added another test

Posted by wi...@apache.org.
MARMOTTA-628: added another test


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/0b07a02b
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/0b07a02b
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/0b07a02b

Branch: refs/heads/MARMOTTA-584
Commit: 0b07a02b04ea5a84a73e834f8aa671bf3fbf9e1f
Parents: 2a6f700
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Fri Feb 12 13:23:57 2016 +0100
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Fri Feb 12 13:23:57 2016 +0100

----------------------------------------------------------------------
 .../marmotta/kiwi/sparql/test/KiWiSparqlTest.java | 18 ++++++++++--------
 1 file changed, 10 insertions(+), 8 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/0b07a02b/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java
----------------------------------------------------------------------
diff --git a/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java b/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java
index 67be368..bb61a5a 100644
--- a/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java
+++ b/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java
@@ -296,32 +296,34 @@ public class KiWiSparqlTest {
         }
     }
 
-    
     @Test
-    public void testMarmotta627_1() throws Exception {
+    public void testMarmotta628_1() throws Exception {
         testMarmotta627("SELECT ( (4.5-4.4)*0.1 as ?c )  WHERE {}", 0.01);
     }
-    
 
     @Test
-    public void testMarmotta627_2() throws Exception {
+    public void testMarmotta628_2() throws Exception {
+        testMarmotta627("SELECT ( (4.5*4.4)*0.1 as ?c )  WHERE {}", 1.98);
+    }
+
+    @Test
+    public void testMarmotta627_1() throws Exception {
         testMarmotta627("SELECT ( 0.1*0.1 as ?c )  WHERE {}", 0.01);
     }
 
     @Test
-    public void testMarmotta627_3() throws Exception {
+    public void testMarmotta627_2() throws Exception {
         testMarmotta627("SELECT ( 0.10*0.01 as ?c )  WHERE {}", 0.001);
     }
 
     @Test
-    public void testMarmotta627_4() throws Exception {
+    public void testMarmotta627_3() throws Exception {
         testMarmotta627("SELECT ( 1.00*3.10 as ?c )  WHERE {}", 3.10);
     }
 
     @Test
-    public void testMarmotta627_5() throws Exception {
+    public void testMarmotta627_4() throws Exception {
         testMarmotta627("SELECT ( 2.00*4.00 as ?c )  WHERE {}", 8.00);
     }
 
-
 }


[05/50] [abbrv] marmotta git commit: refactor iterator implementations, they were broken

Posted by wi...@apache.org.
http://git-wip-us.apache.org/repos/asf/marmotta/blob/2e32da5d/libraries/ostrich/backend/test/gtest-all.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/test/gtest-all.cc b/libraries/ostrich/backend/test/gtest-all.cc
deleted file mode 100644
index ff9e512..0000000
--- a/libraries/ostrich/backend/test/gtest-all.cc
+++ /dev/null
@@ -1,9592 +0,0 @@
-// Copyright 2008, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: mheule@google.com (Markus Heule)
-//
-// Google C++ Testing Framework (Google Test)
-//
-// Sometimes it's desirable to build Google Test by compiling a single file.
-// This file serves this purpose.
-
-// This line ensures that gtest.h can be compiled on its own, even
-// when it's fused.
-#include "gtest.h"
-
-// The following lines pull in the real gtest *.cc files.
-// Copyright 2005, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-//
-// The Google C++ Testing Framework (Google Test)
-
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-//
-// Utilities for testing Google Test itself and code that uses Google Test
-// (e.g. frameworks built on top of Google Test).
-
-#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
-#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
-
-
-namespace testing {
-
-// This helper class can be used to mock out Google Test failure reporting
-// so that we can test Google Test or code that builds on Google Test.
-//
-// An object of this class appends a TestPartResult object to the
-// TestPartResultArray object given in the constructor whenever a Google Test
-// failure is reported. It can either intercept only failures that are
-// generated in the same thread that created this object or it can intercept
-// all generated failures. The scope of this mock object can be controlled with
-// the second argument to the two arguments constructor.
-class GTEST_API_ ScopedFakeTestPartResultReporter
-    : public TestPartResultReporterInterface {
- public:
-  // The two possible mocking modes of this object.
-  enum InterceptMode {
-    INTERCEPT_ONLY_CURRENT_THREAD,  // Intercepts only thread local failures.
-    INTERCEPT_ALL_THREADS           // Intercepts all failures.
-  };
-
-  // The c'tor sets this object as the test part result reporter used
-  // by Google Test.  The 'result' parameter specifies where to report the
-  // results. This reporter will only catch failures generated in the current
-  // thread. DEPRECATED
-  explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
-
-  // Same as above, but you can choose the interception scope of this object.
-  ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
-                                   TestPartResultArray* result);
-
-  // The d'tor restores the previous test part result reporter.
-  virtual ~ScopedFakeTestPartResultReporter();
-
-  // Appends the TestPartResult object to the TestPartResultArray
-  // received in the constructor.
-  //
-  // This method is from the TestPartResultReporterInterface
-  // interface.
-  virtual void ReportTestPartResult(const TestPartResult& result);
- private:
-  void Init();
-
-  const InterceptMode intercept_mode_;
-  TestPartResultReporterInterface* old_reporter_;
-  TestPartResultArray* const result_;
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
-};
-
-namespace internal {
-
-// A helper class for implementing EXPECT_FATAL_FAILURE() and
-// EXPECT_NONFATAL_FAILURE().  Its destructor verifies that the given
-// TestPartResultArray contains exactly one failure that has the given
-// type and contains the given substring.  If that's not the case, a
-// non-fatal failure will be generated.
-class GTEST_API_ SingleFailureChecker {
- public:
-  // The constructor remembers the arguments.
-  SingleFailureChecker(const TestPartResultArray* results,
-                       TestPartResult::Type type,
-                       const string& substr);
-  ~SingleFailureChecker();
- private:
-  const TestPartResultArray* const results_;
-  const TestPartResult::Type type_;
-  const string substr_;
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
-};
-
-}  // namespace internal
-
-}  // namespace testing
-
-// A set of macros for testing Google Test assertions or code that's expected
-// to generate Google Test fatal failures.  It verifies that the given
-// statement will cause exactly one fatal Google Test failure with 'substr'
-// being part of the failure message.
-//
-// There are two different versions of this macro. EXPECT_FATAL_FAILURE only
-// affects and considers failures generated in the current thread and
-// EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
-//
-// The verification of the assertion is done correctly even when the statement
-// throws an exception or aborts the current function.
-//
-// Known restrictions:
-//   - 'statement' cannot reference local non-static variables or
-//     non-static members of the current object.
-//   - 'statement' cannot return a value.
-//   - You cannot stream a failure message to this macro.
-//
-// Note that even though the implementations of the following two
-// macros are much alike, we cannot refactor them to use a common
-// helper macro, due to some peculiarity in how the preprocessor
-// works.  The AcceptsMacroThatExpandsToUnprotectedComma test in
-// gtest_unittest.cc will fail to compile if we do that.
-#define EXPECT_FATAL_FAILURE(statement, substr) \
-  do { \
-    class GTestExpectFatalFailureHelper {\
-     public:\
-      static void Execute() { statement; }\
-    };\
-    ::testing::TestPartResultArray gtest_failures;\
-    ::testing::internal::SingleFailureChecker gtest_checker(\
-        &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
-    {\
-      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
-          ::testing::ScopedFakeTestPartResultReporter:: \
-          INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
-      GTestExpectFatalFailureHelper::Execute();\
-    }\
-  } while (::testing::internal::AlwaysFalse())
-
-#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
-  do { \
-    class GTestExpectFatalFailureHelper {\
-     public:\
-      static void Execute() { statement; }\
-    };\
-    ::testing::TestPartResultArray gtest_failures;\
-    ::testing::internal::SingleFailureChecker gtest_checker(\
-        &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
-    {\
-      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
-          ::testing::ScopedFakeTestPartResultReporter:: \
-          INTERCEPT_ALL_THREADS, &gtest_failures);\
-      GTestExpectFatalFailureHelper::Execute();\
-    }\
-  } while (::testing::internal::AlwaysFalse())
-
-// A macro for testing Google Test assertions or code that's expected to
-// generate Google Test non-fatal failures.  It asserts that the given
-// statement will cause exactly one non-fatal Google Test failure with 'substr'
-// being part of the failure message.
-//
-// There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
-// affects and considers failures generated in the current thread and
-// EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
-//
-// 'statement' is allowed to reference local variables and members of
-// the current object.
-//
-// The verification of the assertion is done correctly even when the statement
-// throws an exception or aborts the current function.
-//
-// Known restrictions:
-//   - You cannot stream a failure message to this macro.
-//
-// Note that even though the implementations of the following two
-// macros are much alike, we cannot refactor them to use a common
-// helper macro, due to some peculiarity in how the preprocessor
-// works.  If we do that, the code won't compile when the user gives
-// EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
-// expands to code containing an unprotected comma.  The
-// AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
-// catches that.
-//
-// For the same reason, we have to write
-//   if (::testing::internal::AlwaysTrue()) { statement; }
-// instead of
-//   GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
-// to avoid an MSVC warning on unreachable code.
-#define EXPECT_NONFATAL_FAILURE(statement, substr) \
-  do {\
-    ::testing::TestPartResultArray gtest_failures;\
-    ::testing::internal::SingleFailureChecker gtest_checker(\
-        &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
-        (substr));\
-    {\
-      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
-          ::testing::ScopedFakeTestPartResultReporter:: \
-          INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
-      if (::testing::internal::AlwaysTrue()) { statement; }\
-    }\
-  } while (::testing::internal::AlwaysFalse())
-
-#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
-  do {\
-    ::testing::TestPartResultArray gtest_failures;\
-    ::testing::internal::SingleFailureChecker gtest_checker(\
-        &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
-        (substr));\
-    {\
-      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
-          ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
-          &gtest_failures);\
-      if (::testing::internal::AlwaysTrue()) { statement; }\
-    }\
-  } while (::testing::internal::AlwaysFalse())
-
-#endif  // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
-
-#include <ctype.h>
-#include <math.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <time.h>
-#include <wchar.h>
-#include <wctype.h>
-
-#include <algorithm>
-#include <iomanip>
-#include <limits>
-#include <ostream>  // NOLINT
-#include <sstream>
-#include <vector>
-
-#if GTEST_OS_LINUX
-
-// TODO(kenton@google.com): Use autoconf to detect availability of
-// gettimeofday().
-# define GTEST_HAS_GETTIMEOFDAY_ 1
-
-# include <fcntl.h>  // NOLINT
-# include <limits.h>  // NOLINT
-# include <sched.h>  // NOLINT
-// Declares vsnprintf().  This header is not available on Windows.
-# include <strings.h>  // NOLINT
-# include <sys/mman.h>  // NOLINT
-# include <sys/time.h>  // NOLINT
-# include <unistd.h>  // NOLINT
-# include <string>
-
-#elif GTEST_OS_SYMBIAN
-# define GTEST_HAS_GETTIMEOFDAY_ 1
-# include <sys/time.h>  // NOLINT
-
-#elif GTEST_OS_ZOS
-# define GTEST_HAS_GETTIMEOFDAY_ 1
-# include <sys/time.h>  // NOLINT
-
-// On z/OS we additionally need strings.h for strcasecmp.
-# include <strings.h>  // NOLINT
-
-#elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.
-
-# include <windows.h>  // NOLINT
-
-#elif GTEST_OS_WINDOWS  // We are on Windows proper.
-
-# include <io.h>  // NOLINT
-# include <sys/timeb.h>  // NOLINT
-# include <sys/types.h>  // NOLINT
-# include <sys/stat.h>  // NOLINT
-
-# if GTEST_OS_WINDOWS_MINGW
-// MinGW has gettimeofday() but not _ftime64().
-// TODO(kenton@google.com): Use autoconf to detect availability of
-//   gettimeofday().
-// TODO(kenton@google.com): There are other ways to get the time on
-//   Windows, like GetTickCount() or GetSystemTimeAsFileTime().  MinGW
-//   supports these.  consider using them instead.
-#  define GTEST_HAS_GETTIMEOFDAY_ 1
-#  include <sys/time.h>  // NOLINT
-# endif  // GTEST_OS_WINDOWS_MINGW
-
-// cpplint thinks that the header is already included, so we want to
-// silence it.
-# include <windows.h>  // NOLINT
-
-#else
-
-// Assume other platforms have gettimeofday().
-// TODO(kenton@google.com): Use autoconf to detect availability of
-//   gettimeofday().
-# define GTEST_HAS_GETTIMEOFDAY_ 1
-
-// cpplint thinks that the header is already included, so we want to
-// silence it.
-# include <sys/time.h>  // NOLINT
-# include <unistd.h>  // NOLINT
-
-#endif  // GTEST_OS_LINUX
-
-#if GTEST_HAS_EXCEPTIONS
-# include <stdexcept>
-#endif
-
-#if GTEST_CAN_STREAM_RESULTS_
-# include <arpa/inet.h>  // NOLINT
-# include <netdb.h>  // NOLINT
-#endif
-
-// Indicates that this translation unit is part of Google Test's
-// implementation.  It must come before gtest-internal-inl.h is
-// included, or there will be a compiler error.  This trick is to
-// prevent a user from accidentally including gtest-internal-inl.h in
-// his code.
-#define GTEST_IMPLEMENTATION_ 1
-// Copyright 2005, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Utility functions and classes used by the Google C++ testing framework.
-//
-// Author: wan@google.com (Zhanyong Wan)
-//
-// This file contains purely Google Test's internal implementation.  Please
-// DO NOT #INCLUDE IT IN A USER PROGRAM.
-
-#ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
-#define GTEST_SRC_GTEST_INTERNAL_INL_H_
-
-// GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
-// part of Google Test's implementation; otherwise it's undefined.
-#if !GTEST_IMPLEMENTATION_
-// A user is trying to include this from his code - just say no.
-# error "gtest-internal-inl.h is part of Google Test's internal implementation."
-# error "It must not be included except by Google Test itself."
-#endif  // GTEST_IMPLEMENTATION_
-
-#ifndef _WIN32_WCE
-# include <errno.h>
-#endif  // !_WIN32_WCE
-#include <stddef.h>
-#include <stdlib.h>  // For strtoll/_strtoul64/malloc/free.
-#include <string.h>  // For memmove.
-
-#include <algorithm>
-#include <string>
-#include <vector>
-
-
-#if GTEST_CAN_STREAM_RESULTS_
-# include <arpa/inet.h>  // NOLINT
-# include <netdb.h>  // NOLINT
-#endif
-
-#if GTEST_OS_WINDOWS
-# include <windows.h>  // NOLINT
-#endif  // GTEST_OS_WINDOWS
-
-
-namespace testing {
-
-// Declares the flags.
-//
-// We don't want the users to modify this flag in the code, but want
-// Google Test's own unit tests to be able to access it. Therefore we
-// declare it here as opposed to in gtest.h.
-GTEST_DECLARE_bool_(death_test_use_fork);
-
-namespace internal {
-
-// The value of GetTestTypeId() as seen from within the Google Test
-// library.  This is solely for testing GetTestTypeId().
-GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
-
-// Names of the flags (needed for parsing Google Test flags).
-const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
-const char kBreakOnFailureFlag[] = "break_on_failure";
-const char kCatchExceptionsFlag[] = "catch_exceptions";
-const char kColorFlag[] = "color";
-const char kFilterFlag[] = "filter";
-const char kListTestsFlag[] = "list_tests";
-const char kOutputFlag[] = "output";
-const char kPrintTimeFlag[] = "print_time";
-const char kRandomSeedFlag[] = "random_seed";
-const char kRepeatFlag[] = "repeat";
-const char kShuffleFlag[] = "shuffle";
-const char kStackTraceDepthFlag[] = "stack_trace_depth";
-const char kStreamResultToFlag[] = "stream_result_to";
-const char kThrowOnFailureFlag[] = "throw_on_failure";
-
-// A valid random seed must be in [1, kMaxRandomSeed].
-const int kMaxRandomSeed = 99999;
-
-// g_help_flag is true iff the --help flag or an equivalent form is
-// specified on the command line.
-GTEST_API_ extern bool g_help_flag;
-
-// Returns the current time in milliseconds.
-GTEST_API_ TimeInMillis GetTimeInMillis();
-
-// Returns true iff Google Test should use colors in the output.
-GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
-
-// Formats the given time in milliseconds as seconds.
-GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
-
-// Converts the given time in milliseconds to a date string in the ISO 8601
-// format, without the timezone information.  N.B.: due to the use the
-// non-reentrant localtime() function, this function is not thread safe.  Do
-// not use it in any code that can be called from multiple threads.
-GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
-
-// Parses a string for an Int32 flag, in the form of "--flag=value".
-//
-// On success, stores the value of the flag in *value, and returns
-// true.  On failure, returns false without changing *value.
-GTEST_API_ bool ParseInt32Flag(
-    const char* str, const char* flag, Int32* value);
-
-// Returns a random seed in range [1, kMaxRandomSeed] based on the
-// given --gtest_random_seed flag value.
-inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
-  const unsigned int raw_seed = (random_seed_flag == 0) ?
-      static_cast<unsigned int>(GetTimeInMillis()) :
-      static_cast<unsigned int>(random_seed_flag);
-
-  // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
-  // it's easy to type.
-  const int normalized_seed =
-      static_cast<int>((raw_seed - 1U) %
-                       static_cast<unsigned int>(kMaxRandomSeed)) + 1;
-  return normalized_seed;
-}
-
-// Returns the first valid random seed after 'seed'.  The behavior is
-// undefined if 'seed' is invalid.  The seed after kMaxRandomSeed is
-// considered to be 1.
-inline int GetNextRandomSeed(int seed) {
-  GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
-      << "Invalid random seed " << seed << " - must be in [1, "
-      << kMaxRandomSeed << "].";
-  const int next_seed = seed + 1;
-  return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
-}
-
-// This class saves the values of all Google Test flags in its c'tor, and
-// restores them in its d'tor.
-class GTestFlagSaver {
- public:
-  // The c'tor.
-  GTestFlagSaver() {
-    also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
-    break_on_failure_ = GTEST_FLAG(break_on_failure);
-    catch_exceptions_ = GTEST_FLAG(catch_exceptions);
-    color_ = GTEST_FLAG(color);
-    death_test_style_ = GTEST_FLAG(death_test_style);
-    death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
-    filter_ = GTEST_FLAG(filter);
-    internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
-    list_tests_ = GTEST_FLAG(list_tests);
-    output_ = GTEST_FLAG(output);
-    print_time_ = GTEST_FLAG(print_time);
-    random_seed_ = GTEST_FLAG(random_seed);
-    repeat_ = GTEST_FLAG(repeat);
-    shuffle_ = GTEST_FLAG(shuffle);
-    stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
-    stream_result_to_ = GTEST_FLAG(stream_result_to);
-    throw_on_failure_ = GTEST_FLAG(throw_on_failure);
-  }
-
-  // The d'tor is not virtual.  DO NOT INHERIT FROM THIS CLASS.
-  ~GTestFlagSaver() {
-    GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
-    GTEST_FLAG(break_on_failure) = break_on_failure_;
-    GTEST_FLAG(catch_exceptions) = catch_exceptions_;
-    GTEST_FLAG(color) = color_;
-    GTEST_FLAG(death_test_style) = death_test_style_;
-    GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
-    GTEST_FLAG(filter) = filter_;
-    GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
-    GTEST_FLAG(list_tests) = list_tests_;
-    GTEST_FLAG(output) = output_;
-    GTEST_FLAG(print_time) = print_time_;
-    GTEST_FLAG(random_seed) = random_seed_;
-    GTEST_FLAG(repeat) = repeat_;
-    GTEST_FLAG(shuffle) = shuffle_;
-    GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
-    GTEST_FLAG(stream_result_to) = stream_result_to_;
-    GTEST_FLAG(throw_on_failure) = throw_on_failure_;
-  }
-
- private:
-  // Fields for saving the original values of flags.
-  bool also_run_disabled_tests_;
-  bool break_on_failure_;
-  bool catch_exceptions_;
-  std::string color_;
-  std::string death_test_style_;
-  bool death_test_use_fork_;
-  std::string filter_;
-  std::string internal_run_death_test_;
-  bool list_tests_;
-  std::string output_;
-  bool print_time_;
-  internal::Int32 random_seed_;
-  internal::Int32 repeat_;
-  bool shuffle_;
-  internal::Int32 stack_trace_depth_;
-  std::string stream_result_to_;
-  bool throw_on_failure_;
-} GTEST_ATTRIBUTE_UNUSED_;
-
-// Converts a Unicode code point to a narrow string in UTF-8 encoding.
-// code_point parameter is of type UInt32 because wchar_t may not be
-// wide enough to contain a code point.
-// If the code_point is not a valid Unicode code point
-// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
-// to "(Invalid Unicode 0xXXXXXXXX)".
-GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
-
-// Converts a wide string to a narrow string in UTF-8 encoding.
-// The wide string is assumed to have the following encoding:
-//   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
-//   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
-// Parameter str points to a null-terminated wide string.
-// Parameter num_chars may additionally limit the number
-// of wchar_t characters processed. -1 is used when the entire string
-// should be processed.
-// If the string contains code points that are not valid Unicode code points
-// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
-// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
-// and contains invalid UTF-16 surrogate pairs, values in those pairs
-// will be encoded as individual Unicode characters from Basic Normal Plane.
-GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
-
-// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
-// if the variable is present. If a file already exists at this location, this
-// function will write over it. If the variable is present, but the file cannot
-// be created, prints an error and exits.
-void WriteToShardStatusFileIfNeeded();
-
-// Checks whether sharding is enabled by examining the relevant
-// environment variable values. If the variables are present,
-// but inconsistent (e.g., shard_index >= total_shards), prints
-// an error and exits. If in_subprocess_for_death_test, sharding is
-// disabled because it must only be applied to the original test
-// process. Otherwise, we could filter out death tests we intended to execute.
-GTEST_API_ bool ShouldShard(const char* total_shards_str,
-                            const char* shard_index_str,
-                            bool in_subprocess_for_death_test);
-
-// Parses the environment variable var as an Int32. If it is unset,
-// returns default_val. If it is not an Int32, prints an error and
-// and aborts.
-GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
-
-// Given the total number of shards, the shard index, and the test id,
-// returns true iff the test should be run on this shard. The test id is
-// some arbitrary but unique non-negative integer assigned to each test
-// method. Assumes that 0 <= shard_index < total_shards.
-GTEST_API_ bool ShouldRunTestOnShard(
-    int total_shards, int shard_index, int test_id);
-
-// STL container utilities.
-
-// Returns the number of elements in the given container that satisfy
-// the given predicate.
-template <class Container, typename Predicate>
-inline int CountIf(const Container& c, Predicate predicate) {
-  // Implemented as an explicit loop since std::count_if() in libCstd on
-  // Solaris has a non-standard signature.
-  int count = 0;
-  for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
-    if (predicate(*it))
-      ++count;
-  }
-  return count;
-}
-
-// Applies a function/functor to each element in the container.
-template <class Container, typename Functor>
-void ForEach(const Container& c, Functor functor) {
-  std::for_each(c.begin(), c.end(), functor);
-}
-
-// Returns the i-th element of the vector, or default_value if i is not
-// in range [0, v.size()).
-template <typename E>
-inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
-  return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
-}
-
-// Performs an in-place shuffle of a range of the vector's elements.
-// 'begin' and 'end' are element indices as an STL-style range;
-// i.e. [begin, end) are shuffled, where 'end' == size() means to
-// shuffle to the end of the vector.
-template <typename E>
-void ShuffleRange(internal::Random* random, int begin, int end,
-                  std::vector<E>* v) {
-  const int size = static_cast<int>(v->size());
-  GTEST_CHECK_(0 <= begin && begin <= size)
-      << "Invalid shuffle range start " << begin << ": must be in range [0, "
-      << size << "].";
-  GTEST_CHECK_(begin <= end && end <= size)
-      << "Invalid shuffle range finish " << end << ": must be in range ["
-      << begin << ", " << size << "].";
-
-  // Fisher-Yates shuffle, from
-  // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
-  for (int range_width = end - begin; range_width >= 2; range_width--) {
-    const int last_in_range = begin + range_width - 1;
-    const int selected = begin + random->Generate(range_width);
-    std::swap((*v)[selected], (*v)[last_in_range]);
-  }
-}
-
-// Performs an in-place shuffle of the vector's elements.
-template <typename E>
-inline void Shuffle(internal::Random* random, std::vector<E>* v) {
-  ShuffleRange(random, 0, static_cast<int>(v->size()), v);
-}
-
-// A function for deleting an object.  Handy for being used as a
-// functor.
-template <typename T>
-static void Delete(T* x) {
-  delete x;
-}
-
-// A predicate that checks the key of a TestProperty against a known key.
-//
-// TestPropertyKeyIs is copyable.
-class TestPropertyKeyIs {
- public:
-  // Constructor.
-  //
-  // TestPropertyKeyIs has NO default constructor.
-  explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
-
-  // Returns true iff the test name of test property matches on key_.
-  bool operator()(const TestProperty& test_property) const {
-    return test_property.key() == key_;
-  }
-
- private:
-  std::string key_;
-};
-
-// Class UnitTestOptions.
-//
-// This class contains functions for processing options the user
-// specifies when running the tests.  It has only static members.
-//
-// In most cases, the user can specify an option using either an
-// environment variable or a command line flag.  E.g. you can set the
-// test filter using either GTEST_FILTER or --gtest_filter.  If both
-// the variable and the flag are present, the latter overrides the
-// former.
-class GTEST_API_ UnitTestOptions {
- public:
-  // Functions for processing the gtest_output flag.
-
-  // Returns the output format, or "" for normal printed output.
-  static std::string GetOutputFormat();
-
-  // Returns the absolute path of the requested output file, or the
-  // default (test_detail.xml in the original working directory) if
-  // none was explicitly specified.
-  static std::string GetAbsolutePathToOutputFile();
-
-  // Functions for processing the gtest_filter flag.
-
-  // Returns true iff the wildcard pattern matches the string.  The
-  // first ':' or '\0' character in pattern marks the end of it.
-  //
-  // This recursive algorithm isn't very efficient, but is clear and
-  // works well enough for matching test names, which are short.
-  static bool PatternMatchesString(const char *pattern, const char *str);
-
-  // Returns true iff the user-specified filter matches the test case
-  // name and the test name.
-  static bool FilterMatchesTest(const std::string &test_case_name,
-                                const std::string &test_name);
-
-#if GTEST_OS_WINDOWS
-  // Function for supporting the gtest_catch_exception flag.
-
-  // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
-  // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
-  // This function is useful as an __except condition.
-  static int GTestShouldProcessSEH(DWORD exception_code);
-#endif  // GTEST_OS_WINDOWS
-
-  // Returns true if "name" matches the ':' separated list of glob-style
-  // filters in "filter".
-  static bool MatchesFilter(const std::string& name, const char* filter);
-};
-
-// Returns the current application's name, removing directory path if that
-// is present.  Used by UnitTestOptions::GetOutputFile.
-GTEST_API_ FilePath GetCurrentExecutableName();
-
-// The role interface for getting the OS stack trace as a string.
-class OsStackTraceGetterInterface {
- public:
-  OsStackTraceGetterInterface() {}
-  virtual ~OsStackTraceGetterInterface() {}
-
-  // Returns the current OS stack trace as an std::string.  Parameters:
-  //
-  //   max_depth  - the maximum number of stack frames to be included
-  //                in the trace.
-  //   skip_count - the number of top frames to be skipped; doesn't count
-  //                against max_depth.
-  virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;
-
-  // UponLeavingGTest() should be called immediately before Google Test calls
-  // user code. It saves some information about the current stack that
-  // CurrentStackTrace() will use to find and hide Google Test stack frames.
-  virtual void UponLeavingGTest() = 0;
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
-};
-
-// A working implementation of the OsStackTraceGetterInterface interface.
-class OsStackTraceGetter : public OsStackTraceGetterInterface {
- public:
-  OsStackTraceGetter() : caller_frame_(NULL) {}
-
-  virtual string CurrentStackTrace(int max_depth, int skip_count)
-      GTEST_LOCK_EXCLUDED_(mutex_);
-
-  virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_);
-
-  // This string is inserted in place of stack frames that are part of
-  // Google Test's implementation.
-  static const char* const kElidedFramesMarker;
-
- private:
-  Mutex mutex_;  // protects all internal state
-
-  // We save the stack frame below the frame that calls user code.
-  // We do this because the address of the frame immediately below
-  // the user code changes between the call to UponLeavingGTest()
-  // and any calls to CurrentStackTrace() from within the user code.
-  void* caller_frame_;
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
-};
-
-// Information about a Google Test trace point.
-struct TraceInfo {
-  const char* file;
-  int line;
-  std::string message;
-};
-
-// This is the default global test part result reporter used in UnitTestImpl.
-// This class should only be used by UnitTestImpl.
-class DefaultGlobalTestPartResultReporter
-  : public TestPartResultReporterInterface {
- public:
-  explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
-  // Implements the TestPartResultReporterInterface. Reports the test part
-  // result in the current test.
-  virtual void ReportTestPartResult(const TestPartResult& result);
-
- private:
-  UnitTestImpl* const unit_test_;
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
-};
-
-// This is the default per thread test part result reporter used in
-// UnitTestImpl. This class should only be used by UnitTestImpl.
-class DefaultPerThreadTestPartResultReporter
-    : public TestPartResultReporterInterface {
- public:
-  explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
-  // Implements the TestPartResultReporterInterface. The implementation just
-  // delegates to the current global test part result reporter of *unit_test_.
-  virtual void ReportTestPartResult(const TestPartResult& result);
-
- private:
-  UnitTestImpl* const unit_test_;
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
-};
-
-// The private implementation of the UnitTest class.  We don't protect
-// the methods under a mutex, as this class is not accessible by a
-// user and the UnitTest class that delegates work to this class does
-// proper locking.
-class GTEST_API_ UnitTestImpl {
- public:
-  explicit UnitTestImpl(UnitTest* parent);
-  virtual ~UnitTestImpl();
-
-  // There are two different ways to register your own TestPartResultReporter.
-  // You can register your own repoter to listen either only for test results
-  // from the current thread or for results from all threads.
-  // By default, each per-thread test result repoter just passes a new
-  // TestPartResult to the global test result reporter, which registers the
-  // test part result for the currently running test.
-
-  // Returns the global test part result reporter.
-  TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
-
-  // Sets the global test part result reporter.
-  void SetGlobalTestPartResultReporter(
-      TestPartResultReporterInterface* reporter);
-
-  // Returns the test part result reporter for the current thread.
-  TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
-
-  // Sets the test part result reporter for the current thread.
-  void SetTestPartResultReporterForCurrentThread(
-      TestPartResultReporterInterface* reporter);
-
-  // Gets the number of successful test cases.
-  int successful_test_case_count() const;
-
-  // Gets the number of failed test cases.
-  int failed_test_case_count() const;
-
-  // Gets the number of all test cases.
-  int total_test_case_count() const;
-
-  // Gets the number of all test cases that contain at least one test
-  // that should run.
-  int test_case_to_run_count() const;
-
-  // Gets the number of successful tests.
-  int successful_test_count() const;
-
-  // Gets the number of failed tests.
-  int failed_test_count() const;
-
-  // Gets the number of disabled tests that will be reported in the XML report.
-  int reportable_disabled_test_count() const;
-
-  // Gets the number of disabled tests.
-  int disabled_test_count() const;
-
-  // Gets the number of tests to be printed in the XML report.
-  int reportable_test_count() const;
-
-  // Gets the number of all tests.
-  int total_test_count() const;
-
-  // Gets the number of tests that should run.
-  int test_to_run_count() const;
-
-  // Gets the time of the test program start, in ms from the start of the
-  // UNIX epoch.
-  TimeInMillis start_timestamp() const { return start_timestamp_; }
-
-  // Gets the elapsed time, in milliseconds.
-  TimeInMillis elapsed_time() const { return elapsed_time_; }
-
-  // Returns true iff the unit test passed (i.e. all test cases passed).
-  bool Passed() const { return !Failed(); }
-
-  // Returns true iff the unit test failed (i.e. some test case failed
-  // or something outside of all tests failed).
-  bool Failed() const {
-    return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
-  }
-
-  // Gets the i-th test case among all the test cases. i can range from 0 to
-  // total_test_case_count() - 1. If i is not in that range, returns NULL.
-  const TestCase* GetTestCase(int i) const {
-    const int index = GetElementOr(test_case_indices_, i, -1);
-    return index < 0 ? NULL : test_cases_[i];
-  }
-
-  // Gets the i-th test case among all the test cases. i can range from 0 to
-  // total_test_case_count() - 1. If i is not in that range, returns NULL.
-  TestCase* GetMutableTestCase(int i) {
-    const int index = GetElementOr(test_case_indices_, i, -1);
-    return index < 0 ? NULL : test_cases_[index];
-  }
-
-  // Provides access to the event listener list.
-  TestEventListeners* listeners() { return &listeners_; }
-
-  // Returns the TestResult for the test that's currently running, or
-  // the TestResult for the ad hoc test if no test is running.
-  TestResult* current_test_result();
-
-  // Returns the TestResult for the ad hoc test.
-  const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
-
-  // Sets the OS stack trace getter.
-  //
-  // Does nothing if the input and the current OS stack trace getter
-  // are the same; otherwise, deletes the old getter and makes the
-  // input the current getter.
-  void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
-
-  // Returns the current OS stack trace getter if it is not NULL;
-  // otherwise, creates an OsStackTraceGetter, makes it the current
-  // getter, and returns it.
-  OsStackTraceGetterInterface* os_stack_trace_getter();
-
-  // Returns the current OS stack trace as an std::string.
-  //
-  // The maximum number of stack frames to be included is specified by
-  // the gtest_stack_trace_depth flag.  The skip_count parameter
-  // specifies the number of top frames to be skipped, which doesn't
-  // count against the number of frames to be included.
-  //
-  // For example, if Foo() calls Bar(), which in turn calls
-  // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
-  // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
-  std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
-
-  // Finds and returns a TestCase with the given name.  If one doesn't
-  // exist, creates one and returns it.
-  //
-  // Arguments:
-  //
-  //   test_case_name: name of the test case
-  //   type_param:     the name of the test's type parameter, or NULL if
-  //                   this is not a typed or a type-parameterized test.
-  //   set_up_tc:      pointer to the function that sets up the test case
-  //   tear_down_tc:   pointer to the function that tears down the test case
-  TestCase* GetTestCase(const char* test_case_name,
-                        const char* type_param,
-                        Test::SetUpTestCaseFunc set_up_tc,
-                        Test::TearDownTestCaseFunc tear_down_tc);
-
-  // Adds a TestInfo to the unit test.
-  //
-  // Arguments:
-  //
-  //   set_up_tc:    pointer to the function that sets up the test case
-  //   tear_down_tc: pointer to the function that tears down the test case
-  //   test_info:    the TestInfo object
-  void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
-                   Test::TearDownTestCaseFunc tear_down_tc,
-                   TestInfo* test_info) {
-    // In order to support thread-safe death tests, we need to
-    // remember the original working directory when the test program
-    // was first invoked.  We cannot do this in RUN_ALL_TESTS(), as
-    // the user may have changed the current directory before calling
-    // RUN_ALL_TESTS().  Therefore we capture the current directory in
-    // AddTestInfo(), which is called to register a TEST or TEST_F
-    // before main() is reached.
-    if (original_working_dir_.IsEmpty()) {
-      original_working_dir_.Set(FilePath::GetCurrentDir());
-      GTEST_CHECK_(!original_working_dir_.IsEmpty())
-          << "Failed to get the current working directory.";
-    }
-
-    GetTestCase(test_info->test_case_name(),
-                test_info->type_param(),
-                set_up_tc,
-                tear_down_tc)->AddTestInfo(test_info);
-  }
-
-#if GTEST_HAS_PARAM_TEST
-  // Returns ParameterizedTestCaseRegistry object used to keep track of
-  // value-parameterized tests and instantiate and register them.
-  internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
-    return parameterized_test_registry_;
-  }
-#endif  // GTEST_HAS_PARAM_TEST
-
-  // Sets the TestCase object for the test that's currently running.
-  void set_current_test_case(TestCase* a_current_test_case) {
-    current_test_case_ = a_current_test_case;
-  }
-
-  // Sets the TestInfo object for the test that's currently running.  If
-  // current_test_info is NULL, the assertion results will be stored in
-  // ad_hoc_test_result_.
-  void set_current_test_info(TestInfo* a_current_test_info) {
-    current_test_info_ = a_current_test_info;
-  }
-
-  // Registers all parameterized tests defined using TEST_P and
-  // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
-  // combination. This method can be called more then once; it has guards
-  // protecting from registering the tests more then once.  If
-  // value-parameterized tests are disabled, RegisterParameterizedTests is
-  // present but does nothing.
-  void RegisterParameterizedTests();
-
-  // Runs all tests in this UnitTest object, prints the result, and
-  // returns true if all tests are successful.  If any exception is
-  // thrown during a test, this test is considered to be failed, but
-  // the rest of the tests will still be run.
-  bool RunAllTests();
-
-  // Clears the results of all tests, except the ad hoc tests.
-  void ClearNonAdHocTestResult() {
-    ForEach(test_cases_, TestCase::ClearTestCaseResult);
-  }
-
-  // Clears the results of ad-hoc test assertions.
-  void ClearAdHocTestResult() {
-    ad_hoc_test_result_.Clear();
-  }
-
-  // Adds a TestProperty to the current TestResult object when invoked in a
-  // context of a test or a test case, or to the global property set. If the
-  // result already contains a property with the same key, the value will be
-  // updated.
-  void RecordProperty(const TestProperty& test_property);
-
-  enum ReactionToSharding {
-    HONOR_SHARDING_PROTOCOL,
-    IGNORE_SHARDING_PROTOCOL
-  };
-
-  // Matches the full name of each test against the user-specified
-  // filter to decide whether the test should run, then records the
-  // result in each TestCase and TestInfo object.
-  // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
-  // based on sharding variables in the environment.
-  // Returns the number of tests that should run.
-  int FilterTests(ReactionToSharding shard_tests);
-
-  // Prints the names of the tests matching the user-specified filter flag.
-  void ListTestsMatchingFilter();
-
-  const TestCase* current_test_case() const { return current_test_case_; }
-  TestInfo* current_test_info() { return current_test_info_; }
-  const TestInfo* current_test_info() const { return current_test_info_; }
-
-  // Returns the vector of environments that need to be set-up/torn-down
-  // before/after the tests are run.
-  std::vector<Environment*>& environments() { return environments_; }
-
-  // Getters for the per-thread Google Test trace stack.
-  std::vector<TraceInfo>& gtest_trace_stack() {
-    return *(gtest_trace_stack_.pointer());
-  }
-  const std::vector<TraceInfo>& gtest_trace_stack() const {
-    return gtest_trace_stack_.get();
-  }
-
-#if GTEST_HAS_DEATH_TEST
-  void InitDeathTestSubprocessControlInfo() {
-    internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
-  }
-  // Returns a pointer to the parsed --gtest_internal_run_death_test
-  // flag, or NULL if that flag was not specified.
-  // This information is useful only in a death test child process.
-  // Must not be called before a call to InitGoogleTest.
-  const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
-    return internal_run_death_test_flag_.get();
-  }
-
-  // Returns a pointer to the current death test factory.
-  internal::DeathTestFactory* death_test_factory() {
-    return death_test_factory_.get();
-  }
-
-  void SuppressTestEventsIfInSubprocess();
-
-  friend class ReplaceDeathTestFactory;
-#endif  // GTEST_HAS_DEATH_TEST
-
-  // Initializes the event listener performing XML output as specified by
-  // UnitTestOptions. Must not be called before InitGoogleTest.
-  void ConfigureXmlOutput();
-
-#if GTEST_CAN_STREAM_RESULTS_
-  // Initializes the event listener for streaming test results to a socket.
-  // Must not be called before InitGoogleTest.
-  void ConfigureStreamingOutput();
-#endif
-
-  // Performs initialization dependent upon flag values obtained in
-  // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
-  // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
-  // this function is also called from RunAllTests.  Since this function can be
-  // called more than once, it has to be idempotent.
-  void PostFlagParsingInit();
-
-  // Gets the random seed used at the start of the current test iteration.
-  int random_seed() const { return random_seed_; }
-
-  // Gets the random number generator.
-  internal::Random* random() { return &random_; }
-
-  // Shuffles all test cases, and the tests within each test case,
-  // making sure that death tests are still run first.
-  void ShuffleTests();
-
-  // Restores the test cases and tests to their order before the first shuffle.
-  void UnshuffleTests();
-
-  // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
-  // UnitTest::Run() starts.
-  bool catch_exceptions() const { return catch_exceptions_; }
-
- private:
-  friend class ::testing::UnitTest;
-
-  // Used by UnitTest::Run() to capture the state of
-  // GTEST_FLAG(catch_exceptions) at the moment it starts.
-  void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
-
-  // The UnitTest object that owns this implementation object.
-  UnitTest* const parent_;
-
-  // The working directory when the first TEST() or TEST_F() was
-  // executed.
-  internal::FilePath original_working_dir_;
-
-  // The default test part result reporters.
-  DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
-  DefaultPerThreadTestPartResultReporter
-      default_per_thread_test_part_result_reporter_;
-
-  // Points to (but doesn't own) the global test part result reporter.
-  TestPartResultReporterInterface* global_test_part_result_repoter_;
-
-  // Protects read and write access to global_test_part_result_reporter_.
-  internal::Mutex global_test_part_result_reporter_mutex_;
-
-  // Points to (but doesn't own) the per-thread test part result reporter.
-  internal::ThreadLocal<TestPartResultReporterInterface*>
-      per_thread_test_part_result_reporter_;
-
-  // The vector of environments that need to be set-up/torn-down
-  // before/after the tests are run.
-  std::vector<Environment*> environments_;
-
-  // The vector of TestCases in their original order.  It owns the
-  // elements in the vector.
-  std::vector<TestCase*> test_cases_;
-
-  // Provides a level of indirection for the test case list to allow
-  // easy shuffling and restoring the test case order.  The i-th
-  // element of this vector is the index of the i-th test case in the
-  // shuffled order.
-  std::vector<int> test_case_indices_;
-
-#if GTEST_HAS_PARAM_TEST
-  // ParameterizedTestRegistry object used to register value-parameterized
-  // tests.
-  internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
-
-  // Indicates whether RegisterParameterizedTests() has been called already.
-  bool parameterized_tests_registered_;
-#endif  // GTEST_HAS_PARAM_TEST
-
-  // Index of the last death test case registered.  Initially -1.
-  int last_death_test_case_;
-
-  // This points to the TestCase for the currently running test.  It
-  // changes as Google Test goes through one test case after another.
-  // When no test is running, this is set to NULL and Google Test
-  // stores assertion results in ad_hoc_test_result_.  Initially NULL.
-  TestCase* current_test_case_;
-
-  // This points to the TestInfo for the currently running test.  It
-  // changes as Google Test goes through one test after another.  When
-  // no test is running, this is set to NULL and Google Test stores
-  // assertion results in ad_hoc_test_result_.  Initially NULL.
-  TestInfo* current_test_info_;
-
-  // Normally, a user only writes assertions inside a TEST or TEST_F,
-  // or inside a function called by a TEST or TEST_F.  Since Google
-  // Test keeps track of which test is current running, it can
-  // associate such an assertion with the test it belongs to.
-  //
-  // If an assertion is encountered when no TEST or TEST_F is running,
-  // Google Test attributes the assertion result to an imaginary "ad hoc"
-  // test, and records the result in ad_hoc_test_result_.
-  TestResult ad_hoc_test_result_;
-
-  // The list of event listeners that can be used to track events inside
-  // Google Test.
-  TestEventListeners listeners_;
-
-  // The OS stack trace getter.  Will be deleted when the UnitTest
-  // object is destructed.  By default, an OsStackTraceGetter is used,
-  // but the user can set this field to use a custom getter if that is
-  // desired.
-  OsStackTraceGetterInterface* os_stack_trace_getter_;
-
-  // True iff PostFlagParsingInit() has been called.
-  bool post_flag_parse_init_performed_;
-
-  // The random number seed used at the beginning of the test run.
-  int random_seed_;
-
-  // Our random number generator.
-  internal::Random random_;
-
-  // The time of the test program start, in ms from the start of the
-  // UNIX epoch.
-  TimeInMillis start_timestamp_;
-
-  // How long the test took to run, in milliseconds.
-  TimeInMillis elapsed_time_;
-
-#if GTEST_HAS_DEATH_TEST
-  // The decomposed components of the gtest_internal_run_death_test flag,
-  // parsed when RUN_ALL_TESTS is called.
-  internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
-  internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
-#endif  // GTEST_HAS_DEATH_TEST
-
-  // A per-thread stack of traces created by the SCOPED_TRACE() macro.
-  internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
-
-  // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
-  // starts.
-  bool catch_exceptions_;
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
-};  // class UnitTestImpl
-
-// Convenience function for accessing the global UnitTest
-// implementation object.
-inline UnitTestImpl* GetUnitTestImpl() {
-  return UnitTest::GetInstance()->impl();
-}
-
-#if GTEST_USES_SIMPLE_RE
-
-// Internal helper functions for implementing the simple regular
-// expression matcher.
-GTEST_API_ bool IsInSet(char ch, const char* str);
-GTEST_API_ bool IsAsciiDigit(char ch);
-GTEST_API_ bool IsAsciiPunct(char ch);
-GTEST_API_ bool IsRepeat(char ch);
-GTEST_API_ bool IsAsciiWhiteSpace(char ch);
-GTEST_API_ bool IsAsciiWordChar(char ch);
-GTEST_API_ bool IsValidEscape(char ch);
-GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
-GTEST_API_ bool ValidateRegex(const char* regex);
-GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
-GTEST_API_ bool MatchRepetitionAndRegexAtHead(
-    bool escaped, char ch, char repeat, const char* regex, const char* str);
-GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
-
-#endif  // GTEST_USES_SIMPLE_RE
-
-// Parses the command line for Google Test flags, without initializing
-// other parts of Google Test.
-GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
-GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
-
-#if GTEST_HAS_DEATH_TEST
-
-// Returns the message describing the last system error, regardless of the
-// platform.
-GTEST_API_ std::string GetLastErrnoDescription();
-
-# if GTEST_OS_WINDOWS
-// Provides leak-safe Windows kernel handle ownership.
-class AutoHandle {
- public:
-  AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
-  explicit AutoHandle(HANDLE handle) : handle_(handle) {}
-
-  ~AutoHandle() { Reset(); }
-
-  HANDLE Get() const { return handle_; }
-  void Reset() { Reset(INVALID_HANDLE_VALUE); }
-  void Reset(HANDLE handle) {
-    if (handle != handle_) {
-      if (handle_ != INVALID_HANDLE_VALUE)
-        ::CloseHandle(handle_);
-      handle_ = handle;
-    }
-  }
-
- private:
-  HANDLE handle_;
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
-};
-# endif  // GTEST_OS_WINDOWS
-
-// Attempts to parse a string into a positive integer pointed to by the
-// number parameter.  Returns true if that is possible.
-// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
-// it here.
-template <typename Integer>
-bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
-  // Fail fast if the given string does not begin with a digit;
-  // this bypasses strtoXXX's "optional leading whitespace and plus
-  // or minus sign" semantics, which are undesirable here.
-  if (str.empty() || !IsDigit(str[0])) {
-    return false;
-  }
-  errno = 0;
-
-  char* end;
-  // BiggestConvertible is the largest integer type that system-provided
-  // string-to-number conversion routines can return.
-
-# if GTEST_OS_WINDOWS && !defined(__GNUC__)
-
-  // MSVC and C++ Builder define __int64 instead of the standard long long.
-  typedef unsigned __int64 BiggestConvertible;
-  const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
-
-# else
-
-  typedef unsigned long long BiggestConvertible;  // NOLINT
-  const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
-
-# endif  // GTEST_OS_WINDOWS && !defined(__GNUC__)
-
-  const bool parse_success = *end == '\0' && errno == 0;
-
-  // TODO(vladl@google.com): Convert this to compile time assertion when it is
-  // available.
-  GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
-
-  const Integer result = static_cast<Integer>(parsed);
-  if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
-    *number = result;
-    return true;
-  }
-  return false;
-}
-#endif  // GTEST_HAS_DEATH_TEST
-
-// TestResult contains some private methods that should be hidden from
-// Google Test user but are required for testing. This class allow our tests
-// to access them.
-//
-// This class is supplied only for the purpose of testing Google Test's own
-// constructs. Do not use it in user tests, either directly or indirectly.
-class TestResultAccessor {
- public:
-  static void RecordProperty(TestResult* test_result,
-                             const std::string& xml_element,
-                             const TestProperty& property) {
-    test_result->RecordProperty(xml_element, property);
-  }
-
-  static void ClearTestPartResults(TestResult* test_result) {
-    test_result->ClearTestPartResults();
-  }
-
-  static const std::vector<testing::TestPartResult>& test_part_results(
-      const TestResult& test_result) {
-    return test_result.test_part_results();
-  }
-};
-
-#if GTEST_CAN_STREAM_RESULTS_
-
-// Streams test results to the given port on the given host machine.
-class StreamingListener : public EmptyTestEventListener {
- public:
-  // Abstract base class for writing strings to a socket.
-  class AbstractSocketWriter {
-   public:
-    virtual ~AbstractSocketWriter() {}
-
-    // Sends a string to the socket.
-    virtual void Send(const string& message) = 0;
-
-    // Closes the socket.
-    virtual void CloseConnection() {}
-
-    // Sends a string and a newline to the socket.
-    void SendLn(const string& message) {
-      Send(message + "\n");
-    }
-  };
-
-  // Concrete class for actually writing strings to a socket.
-  class SocketWriter : public AbstractSocketWriter {
-   public:
-    SocketWriter(const string& host, const string& port)
-        : sockfd_(-1), host_name_(host), port_num_(port) {
-      MakeConnection();
-    }
-
-    virtual ~SocketWriter() {
-      if (sockfd_ != -1)
-        CloseConnection();
-    }
-
-    // Sends a string to the socket.
-    virtual void Send(const string& message) {
-      GTEST_CHECK_(sockfd_ != -1)
-          << "Send() can be called only when there is a connection.";
-
-      const int len = static_cast<int>(message.length());
-      if (write(sockfd_, message.c_str(), len) != len) {
-        GTEST_LOG_(WARNING)
-            << "stream_result_to: failed to stream to "
-            << host_name_ << ":" << port_num_;
-      }
-    }
-
-   private:
-    // Creates a client socket and connects to the server.
-    void MakeConnection();
-
-    // Closes the socket.
-    void CloseConnection() {
-      GTEST_CHECK_(sockfd_ != -1)
-          << "CloseConnection() can be called only when there is a connection.";
-
-      close(sockfd_);
-      sockfd_ = -1;
-    }
-
-    int sockfd_;  // socket file descriptor
-    const string host_name_;
-    const string port_num_;
-
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
-  };  // class SocketWriter
-
-  // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
-  static string UrlEncode(const char* str);
-
-  StreamingListener(const string& host, const string& port)
-      : socket_writer_(new SocketWriter(host, port)) { Start(); }
-
-  explicit StreamingListener(AbstractSocketWriter* socket_writer)
-      : socket_writer_(socket_writer) { Start(); }
-
-  void OnTestProgramStart(const UnitTest& /* unit_test */) {
-    SendLn("event=TestProgramStart");
-  }
-
-  void OnTestProgramEnd(const UnitTest& unit_test) {
-    // Note that Google Test current only report elapsed time for each
-    // test iteration, not for the entire test program.
-    SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
-
-    // Notify the streaming server to stop.
-    socket_writer_->CloseConnection();
-  }
-
-  void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
-    SendLn("event=TestIterationStart&iteration=" +
-           StreamableToString(iteration));
-  }
-
-  void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
-    SendLn("event=TestIterationEnd&passed=" +
-           FormatBool(unit_test.Passed()) + "&elapsed_time=" +
-           StreamableToString(unit_test.elapsed_time()) + "ms");
-  }
-
-  void OnTestCaseStart(const TestCase& test_case) {
-    SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
-  }
-
-  void OnTestCaseEnd(const TestCase& test_case) {
-    SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
-           + "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
-           + "ms");
-  }
-
-  void OnTestStart(const TestInfo& test_info) {
-    SendLn(std::string("event=TestStart&name=") + test_info.name());
-  }
-
-  void OnTestEnd(const TestInfo& test_info) {
-    SendLn("event=TestEnd&passed=" +
-           FormatBool((test_info.result())->Passed()) +
-           "&elapsed_time=" +
-           StreamableToString((test_info.result())->elapsed_time()) + "ms");
-  }
-
-  void OnTestPartResult(const TestPartResult& test_part_result) {
-    const char* file_name = test_part_result.file_name();
-    if (file_name == NULL)
-      file_name = "";
-    SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
-           "&line=" + StreamableToString(test_part_result.line_number()) +
-           "&message=" + UrlEncode(test_part_result.message()));
-  }
-
- private:
-  // Sends the given message and a newline to the socket.
-  void SendLn(const string& message) { socket_writer_->SendLn(message); }
-
-  // Called at the start of streaming to notify the receiver what
-  // protocol we are using.
-  void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
-
-  string FormatBool(bool value) { return value ? "1" : "0"; }
-
-  const scoped_ptr<AbstractSocketWriter> socket_writer_;
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
-};  // class StreamingListener
-
-#endif  // GTEST_CAN_STREAM_RESULTS_
-
-}  // namespace internal
-}  // namespace testing
-
-#endif  // GTEST_SRC_GTEST_INTERNAL_INL_H_
-#undef GTEST_IMPLEMENTATION_
-
-#if GTEST_OS_WINDOWS
-# define vsnprintf _vsnprintf
-#endif  // GTEST_OS_WINDOWS
-
-namespace testing {
-
-using internal::CountIf;
-using internal::ForEach;
-using internal::GetElementOr;
-using internal::Shuffle;
-
-// Constants.
-
-// A test whose test case name or test name matches this filter is
-// disabled and not run.
-static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
-
-// A test case whose name matches this filter is considered a death
-// test case and will be run before test cases whose name doesn't
-// match this filter.
-static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
-
-// A test filter that matches everything.
-static const char kUniversalFilter[] = "*";
-
-// The default output file for XML output.
-static const char kDefaultOutputFile[] = "test_detail.xml";
-
-// The environment variable name for the test shard index.
-static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
-// The environment variable name for the total number of test shards.
-static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
-// The environment variable name for the test shard status file.
-static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
-
-namespace internal {
-
-// The text used in failure messages to indicate the start of the
-// stack trace.
-const char kStackTraceMarker[] = "\nStack trace:\n";
-
-// g_help_flag is true iff the --help flag or an equivalent form is
-// specified on the command line.
-bool g_help_flag = false;
-
-}  // namespace internal
-
-static const char* GetDefaultFilter() {
-  return kUniversalFilter;
-}
-
-GTEST_DEFINE_bool_(
-    also_run_disabled_tests,
-    internal::BoolFromGTestEnv("also_run_disabled_tests", false),
-    "Run disabled tests too, in addition to the tests normally being run.");
-
-GTEST_DEFINE_bool_(
-    break_on_failure,
-    internal::BoolFromGTestEnv("break_on_failure", false),
-    "True iff a failed assertion should be a debugger break-point.");
-
-GTEST_DEFINE_bool_(
-    catch_exceptions,
-    internal::BoolFromGTestEnv("catch_exceptions", true),
-    "True iff " GTEST_NAME_
-    " should catch exceptions and treat them as test failures.");
-
-GTEST_DEFINE_string_(
-    color,
-    internal::StringFromGTestEnv("color", "auto"),
-    "Whether to use colors in the output.  Valid values: yes, no, "
-    "and auto.  'auto' means to use colors if the output is "
-    "being sent to a terminal and the TERM environment variable "
-    "is set to a terminal type that supports colors.");
-
-GTEST_DEFINE_string_(
-    filter,
-    internal::StringFromGTestEnv("filter", GetDefaultFilter()),
-    "A colon-separated list of glob (not regex) patterns "
-    "for filtering the tests to run, optionally followed by a "
-    "'-' and a : separated list of negative patterns (tests to "
-    "exclude).  A test is run if it matches one of the positive "
-    "patterns and does not match any of the negative patterns.");
-
-GTEST_DEFINE_bool_(list_tests, false,
-                   "List all tests without running them.");
-
-GTEST_DEFINE_string_(
-    output,
-    internal::StringFromGTestEnv("output", ""),
-    "A format (currently must be \"xml\"), optionally followed "
-    "by a colon and an output file name or directory. A directory "
-    "is indicated by a trailing pathname separator. "
-    "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
-    "If a directory is specified, output files will be created "
-    "within that directory, with file-names based on the test "
-    "executable's name and, if necessary, made unique by adding "
-    "digits.");
-
-GTEST_DEFINE_bool_(
-    print_time,
-    internal::BoolFromGTestEnv("print_time", true),
-    "True iff " GTEST_NAME_
-    " should display elapsed time in text output.");
-
-GTEST_DEFINE_int32_(
-    random_seed,
-    internal::Int32FromGTestEnv("random_seed", 0),
-    "Random number seed to use when shuffling test orders.  Must be in range "
-    "[1, 99999], or 0 to use a seed based on the current time.");
-
-GTEST_DEFINE_int32_(
-    repeat,
-    internal::Int32FromGTestEnv("repeat", 1),
-    "How many times to repeat each test.  Specify a negative number "
-    "for repeating forever.  Useful for shaking out flaky tests.");
-
-GTEST_DEFINE_bool_(
-    show_internal_stack_frames, false,
-    "True iff " GTEST_NAME_ " should include internal stack frames when "
-    "printing test failure stack traces.");
-
-GTEST_DEFINE_bool_(
-    shuffle,
-    internal::BoolFromGTestEnv("shuffle", false),
-    "True iff " GTEST_NAME_
-    " should randomize tests' order on every run.");
-
-GTEST_DEFINE_int32_(
-    stack_trace_depth,
-    internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
-    "The maximum number of stack frames to print when an "
-    "assertion fails.  The valid range is 0 through 100, inclusive.");
-
-GTEST_DEFINE_string_(
-    stream_result_to,
-    internal::StringFromGTestEnv("stream_result_to", ""),
-    "This flag specifies the host name and the port number on which to stream "
-    "test results. Example: \"localhost:555\". The flag is effective only on "
-    "Linux.");
-
-GTEST_DEFINE_bool_(
-    throw_on_failure,
-    internal::BoolFromGTestEnv("throw_on_failure", false),
-    "When this flag is specified, a failed assertion will throw an exception "
-    "if exceptions are enabled or exit the program with a non-zero code "
-    "otherwise.");
-
-namespace internal {
-
-// Generates a random number from [0, range), using a Linear
-// Congruential Generator (LCG).  Crashes if 'range' is 0 or greater
-// than kMaxRange.
-UInt32 Random::Generate(UInt32 range) {
-  // These constants are the same as are used in glibc's rand(3).
-  state_ = (1103515245U*state_ + 12345U) % kMaxRange;
-
-  GTEST_CHECK_(range > 0)
-      << "Cannot generate a number in the range [0, 0).";
-  GTEST_CHECK_(range <= kMaxRange)
-      << "Generation of a number in [0, " << range << ") was requested, "
-      << "but this can only generate numbers in [0, " << kMaxRange << ").";
-
-  // Converting via modulus introduces a bit of downward bias, but
-  // it's simple, and a linear congruential generator isn't too good
-  // to begin with.
-  return state_ % range;
-}
-
-// GTestIsInitialized() returns true iff the user has initialized
-// Google Test.  Useful for catching the user mistake of not initializing
-// Google Test before calling RUN_ALL_TESTS().
-//
-// A user must call testing::InitGoogleTest() to initialize Google
-// Test.  g_init_gtest_count is set to the number of times
-// InitGoogleTest() has been called.  We don't protect this variable
-// under a mutex as it is only accessed in the main thread.
-GTEST_API_ int g_init_gtest_count = 0;
-static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
-
-// Iterates over a vector of TestCases, keeping a running sum of the
-// results of calling a given int-returning method on each.
-// Returns the sum.
-static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
-                               int (TestCase::*method)() const) {
-  int sum = 0;
-  for (size_t i = 0; i < case_list.size(); i++) {
-    sum += (case_list[i]->*method)();
-  }
-  return sum;
-}
-
-// Returns true iff the test case passed.
-static bool TestCasePassed(const TestCase* test_case) {
-  return test_case->should_run() && test_case->Passed();
-}
-
-// Returns true iff the test case failed.
-static bool TestCaseFailed(const TestCase* test_case) {
-  return test_case->should_run() && test_case->Failed();
-}
-
-// Returns true iff test_case contains at least one test that should
-// run.
-static bool ShouldRunTestCase(const TestCase* test_case) {
-  return test_case->should_run();
-}
-
-// AssertHelper constructor.
-AssertHelper::AssertHelper(TestPartResult::Type type,
-                           const char* file,
-                           int line,
-                           const char* message)
-    : data_(new AssertHelperData(type, file, line, message)) {
-}
-
-AssertHelper::~AssertHelper() {
-  delete data_;
-}
-
-// Message assignment, for assertion streaming support.
-void AssertHelper::operator=(const Message& message) const {
-  UnitTest::GetInstance()->
-    AddTestPartResult(data_->type, data_->file, data_->line,
-                      AppendUserMessage(data_->message, message),
-                      UnitTest::GetInstance()->impl()
-                      ->CurrentOsStackTraceExceptTop(1)
-                      // Skips the stack frame for this function itself.
-                      );  // NOLINT
-}
-
-// Mutex for linked pointers.
-GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
-
-// Application pathname gotten in InitGoogleTest.
-std::string g_executable_path;
-
-// Returns the current application's name, removing directory path if that
-// is present.
-FilePath GetCurrentExecutableName() {
-  FilePath result;
-
-#if GTEST_OS_WINDOWS
-  result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
-#else
-  result.Set(FilePath(g_executable_path));
-#endif  // GTEST_OS_WINDOWS
-
-  return result.RemoveDirectoryName();
-}
-
-// Functions for processing the gtest_output flag.
-
-// Returns the output format, or "" for normal printed output.
-std::string UnitTestOptions::GetOutputFormat() {
-  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
-  if (gtest_output_flag == NULL) return std::string("");
-
-  const char* const colon = strchr(gtest_output_flag, ':');
-  return (colon == NULL) ?
-      std::string(gtest_output_flag) :
-      std::string(gtest_output_flag, colon - gtest_output_flag);
-}
-
-// Returns the name of the requested output file, or the default if none
-// was explicitly specified.
-std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
-  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
-  if (gtest_output_flag == NULL)
-    return "";
-
-  const char* const colon = strchr(gtest_output_flag, ':');
-  if (colon == NULL)
-    return internal::FilePath::ConcatPaths(
-        internal::FilePath(
-            UnitTest::GetInstance()->original_working_dir()),
-        internal::FilePath(kDefaultOutputFile)).string();
-
-  internal::FilePath output_name(colon + 1);
-  if (!output_name.IsAbsolutePath())
-    // TODO(wan@google.com): on Windows \some\path is not an absolute
-    // path (as its meaning depends on the current drive), yet the
-    // following logic for turning it into an absolute path is wrong.
-    // Fix it.
-    output_name = internal::FilePath::ConcatPaths(
-        internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
-        internal::FilePath(colon + 1));
-
-  if (!output_name.IsDirectory())
-    return output_name.string();
-
-  internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
-      output_name, internal::GetCurrentExecutableName(),
-      GetOutputFormat().c_str()));
-  return result.string();
-}
-
-// Returns true iff the wildcard pattern matches the string.  The
-// first ':' or '\0' character in pattern marks the end of it.
-//
-// This recursive algorithm isn't very efficient, but is clear and
-// works well enough for matching test names, which are short.
-bool UnitTestOptions::PatternMatchesString(const char *pattern,
-                                           const char *str) {
-  switch (*pattern) {
-    case '\0':
-    case ':':  // Either ':' or '\0' marks the end of the pattern.
-      return *str == '\0';
-    case '?':  // Matches any single character.
-      return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
-    case '*':  // Matches any string (possibly empty) of characters.
-      return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
-          PatternMatchesString(pattern + 1, str);
-    default:  // Non-special character.  Matches itself.
-      return *pattern == *str &&
-          PatternMatchesString(pattern + 1, str + 1);
-  }
-}
-
-bool UnitTestOptions::MatchesFilter(
-    const std::string& name, const char* filter) {
-  const char *cur_pattern = filter;
-  for (;;) {
-    if (PatternMatchesString(cur_pattern, name.c_str())) {
-      return true;
-    }
-
-    // Finds the next pattern in the filter.
-    cur_pattern = strchr(cur_pattern, ':');
-
-    // Returns if no more pattern can be found.
-    if (cur_pattern == NULL) {
-      return false;
-    }
-
-    // Skips the pattern separater (the ':' character).
-    cur_pattern++;
-  }
-}
-
-// Returns true iff the user-specified filter matches the test case
-// name and the test name.
-bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
-                                        const std::string &test_name) {
-  const std::string& full_name = test_case_name + "." + test_name.c_str();
-
-  // Split --gtest_filter at '-', if there is one, to separate into
-  // positive filter and negative filter portions
-  const char* const p = GTEST_FLAG(filter).c_str();
-  const char* const dash = strchr(p, '-');
-  std::string positive;
-  std::string negative;
-  if (dash == NULL) {
-    positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter
-    negative = "";
-  } else {
-    positive = std::string(p, dash);   // Everything up to the dash
-    negative = std::string(dash + 1);  // Everything after the dash
-    if (positive.empty()) {
-      // Treat '-test1' as the same as '*-test1'
-      positive = kUniversalFilter;
-    }
-  }
-
-  // A filter is a colon-separated list of patterns.  It matches a
-  // test if any pattern in it matches the test.
-  return (MatchesFilter(full_name, positive.c_str()) &&
-          !MatchesFilter(full_name, negative.c_str()));
-}
-
-#if GTEST_HAS_SEH
-// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
-// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
-// This function is useful as an __except condition.
-int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
-  // Google Test should handle a SEH exception if:
-  //   1. the user wants it to, AND
-  //   2. this is not a breakpoint exception, AND
-  //   3. this is not a C++ exception (VC++ implements them via SEH,
-  //      apparently).
-  //
-  // SEH exception code for C++ exceptions.
-  // (see http://support.microsoft.com/kb/185294 for more information).
-  const DWORD kCxxExceptionCode = 0xe06d7363;
-
-  bool should_handle = true;
-
-  if (!GTEST_FLAG(catch_exceptions))
-    should_handle = false;
-  else if (exception_code == EXCEPTION_BREAKPOINT)
-    should_handle = false;
-  else if (exception_code == kCxxExceptionCode)
-    should_handle = false;
-
-  return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
-}
-#endif  // GTEST_HAS_SEH
-
-}  // namespace internal
-
-// The c'tor sets this object as the test part result reporter used by
-// Google Test.  The 'result' parameter specifies where to report the
-// results. Intercepts only failures from the current thread.
-ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
-    TestPartResultArray* result)
-    : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
-      result_(result) {
-  Init();
-}
-
-// The c'tor sets this object as the test part result reporter used by
-// Google Test.  The 'result' parameter specifies where to report the
-// results.
-ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
-    InterceptMode intercept_mode, TestPartResultArray* result)
-    : intercept_mode_(intercept_mode),
-      result_(result) {
-  Init();
-}
-
-void ScopedFakeTestPartResultReporter::Init() {
-  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
-  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
-    old_reporter_ = impl->GetGlobalTestPartResultReporter();
-    impl->SetGlobalTestPartResultReporter(this);
-  } else {
-    old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
-    impl->SetTestPartResultReporterForCurrentThread(this);
-  }
-}
-
-// The d'tor restores the test part result reporter used by Google Test
-// before.
-ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
-  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
-  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
-    impl->SetGlobalTestPartResultReporter(old_reporter_);
-  } else {
-    impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
-  }
-}
-
-// Increments the test part result count and remembers the result.
-// This method is from the TestPartResultReporterInterface interface.
-void ScopedFakeTestPartResultReporter::ReportTestPartResult(
-    const TestPartResult& result) {
-  result_->Append(result);
-}
-
-namespace internal {
-
-// Returns the type ID of ::testing::Test.  We should always call this
-// instead of GetTypeId< ::testing::Test>() to get the type ID of
-// testing::Test.  This is to work around a suspected linker bug when
-// using Google Test as a framework on Mac OS X.  The bug causes
-// GetTypeId< ::testing::Test>() to return different values depending
-// on whether the call is from the Google Test framework itself or
-// from user test code.  GetTestTypeId() is guaranteed to always
-// return the same value, as it always calls GetTypeId<>() from the
-// gtest.cc, which is within the Google Test framework.
-TypeId GetTestTypeId() {
-  return GetTypeId<Test>();
-}
-
-// The value of GetTestTypeId() as seen from within the Google Test
-// library.  This is solely for testing GetTestTypeId().
-extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
-
-// This predicate-formatter checks that 'results' contains a test part
-// failure of the given type and that the failure message contains the
-// given substring.
-AssertionResult HasOneFailure(const char* /* results_expr */,
-                              const char* /* type_expr */,
-                              const char* /* substr_expr */,
-                              const TestPartResultArray& results,
-                              TestPartResult::Type type,
-                              const string& substr) {
-  const std::string expected(type == TestPartResult::kFatalFailure ?
-                        "1 fatal failure" :
-                        "1 non-fatal failure");
-  Message msg;
-  if (results.size() != 1) {
-    msg << "Expected: " << expected << "\n"
-        << "  Actual: " << results.size() << " failures";
-    for (int i = 0; i < results.size(); i++) {
-      msg << "\n" << results.GetTestPartResult(i);
-    }
-    return AssertionFailure() << msg;
-  }
-
-  const TestPartResult& r = results.GetTestPartResult(0);
-  if (r.type() != type) {
-    return AssertionFailure() << "Expected: " << expected << "\n"
-                              << "  Actual:\n"
-                              << r;
-  }
-
-  if (strstr(r.message(), substr.c_str()) == NULL) {
-    return AssertionFailure() << "Expected: " << expected << " containing \""
-                              << substr << "\"\n"
-                              << "  Actual:\n"
-                              << r;
-  }
-
-  return AssertionSuccess();
-}
-
-// The constructor of SingleFailureChecker remembers where to look up
-// test part results, what type of failure we expect, and what
-// substring the failure message should contain.
-SingleFailureChecker:: SingleFailureChecker(
-    const TestPartResultArray* results,
-    TestPartResult::Type type,
-    const string& substr)
-    : results_(results),
-      type_(type),
-      substr_(substr) {}
-
-// The destructor of SingleFailureChecker verifies that the given
-// TestPartResultArray contains exactly one failure that has the given
-// type and contains the given substring.  If that's not the case, a
-// non-fatal failure will be generated.
-SingleFailureChecker::~SingleFailureChecker() {
-  EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
-}
-
-DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
-    UnitTestImpl* unit_test) : unit_test_(unit_test) {}
-
-void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
-    const TestPartResult& result) {
-  unit_test_->current_test_result()->AddTestPartResult(result);
-  unit_test_->listeners()->repeater()->OnTestPartResult(result);
-}
-
-DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
-    UnitTestImpl* unit_test) : unit_test_(unit_test) {}
-
-void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
-    const TestPartResult& result) {
-  unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
-}
-
-// Returns the global test part result reporter.
-TestPartResultReporterInterface*
-UnitTestImpl::GetGlobalTestPartResultReporter() {
-  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
-  return global_test_part_result_repoter_;
-}
-
-// Sets the global test part result reporter.
-void UnitTestImpl::SetGlobalTestPartResultReporter(
-    TestPartResultReporterInterface* reporter) {
-  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
-  global_test_part_result_repoter_ = reporter;
-}
-
-// Returns the test part result reporter for the current thread.
-TestPartResultReporterInterface*
-UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
-  return per_thread_test_part_result_reporter_.get();
-}
-
-// Sets the test part result reporter for the current thread.
-void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
-    TestPartResultReporterInterface* reporter) {
-  per_thread_test_part_result_reporter_.set(reporter);
-}
-
-// Gets the number of successful test cases.
-int UnitTestImpl::successful_test_case_count() const {
-  return CountIf(test_cases_, TestCasePassed);
-}
-
-// Gets the number of failed test cases.
-int UnitTestImpl::failed_test_case_count() const {
-  return CountIf(test_cases_, TestCaseFailed);
-}
-
-// Gets the number of all test cases.
-int UnitTestImpl::total_test_case_count() const {
-  return static_cast<int>(test_cases_.size());
-}
-
-// Gets the number of all test cases that contain at least one test
-// that should run.
-int UnitTestImpl::test_case_to_run_count() const {
-  return CountIf(test_cases_, ShouldRunTestCase);
-}
-
-// Gets the number of successful tests.
-int UnitTestImpl::successful_test_count() const {
-  return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
-}
-
-// Gets the number of failed tests.
-int UnitTestImpl::failed_test_count() const {
-  return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
-}
-
-// Gets the number of disabled tests that will be reported in the XML report.
-int UnitTestImpl::reportable_disabled_test_count() const {
-  return SumOverTestCaseList(test_cases_,
-                             &TestCase::reportable_disabled_test_count);
-}
-
-// Gets the number of disabled tests.
-int UnitTestImpl::disabled_test_count() const {
-  return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
-}
-
-// Gets the number of tests to be printed in the XML report.
-int UnitTestImpl::reportable_test_count() const {
-  return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);
-}
-
-// Gets the number of all tests.
-int UnitTestImpl::total_test_count() const {
-  return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
-}
-
-// Gets the number of tests that should run.
-int UnitTestImpl::test_to_run_count() const {
-  return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
-}
-
-// Returns the current OS stack trace as an std::string.
-//
-// The maximum number of stack frames to be included is specified by
-// the gtest_stack_trace_depth flag.  The skip_count parameter
-// specifies the number of top frames to be skipped, which doesn't
-// count against the number of frames to be included.
-//
-// For example, if Foo() calls Bar(), which in turn calls
-// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
-// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
-std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
-  (void)skip_count;
-  return "";
-}
-
-// Returns the current time in milliseconds.
-TimeInMillis GetTimeInMillis() {
-#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
-  // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
-  // http://analogous.blogspot.com/2005/04/epoch.html
-  const TimeInMillis kJavaEpochToWinFileTimeDelta =
-    static_cast<TimeInMillis>(116444736UL) * 100000UL;
-  const DWORD kTenthMicrosInMilliSecond = 10000;
-
-  SYSTEMTIME now_systime;
-  FILETIME now_filetime;
-  ULARGE_INTEGER now_int64;
-  // TODO(kenton@google.com): Shouldn't this just use
-  //   GetSystemTimeAsFileTime()?
-  GetSystemTime(&now_systime);
-  if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
-    now_i

<TRUNCATED>

[35/50] [abbrv] marmotta git commit: Merge branch 'develop' of https://git-wip-us.apache.org/repos/asf/marmotta into develop

Posted by wi...@apache.org.
Merge branch 'develop' of https://git-wip-us.apache.org/repos/asf/marmotta into develop


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/28e6dba3
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/28e6dba3
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/28e6dba3

Branch: refs/heads/MARMOTTA-584
Commit: 28e6dba31cc45614ce8b2ac2602b3f986a527de9
Parents: b79a162 503cbc8
Author: Thomas Kurz <th...@salzburgresearch.at>
Authored: Tue Mar 8 15:12:07 2016 +0100
Committer: Thomas Kurz <th...@salzburgresearch.at>
Committed: Tue Mar 8 15:12:07 2016 +0100

----------------------------------------------------------------------
 README.md                                       |   109 +
 README.txt                                      |   119 -
 launchers/marmotta-webapp/README.md             |     1 +
 launchers/marmotta-webapp/pom.xml               |    22 +
 .../kiwi/reasoner/parser/KWRLProgramParser.jj   |    26 +-
 .../test/parser/KWRLRuleParserTest.java         |    41 +-
 .../persistence/KWRLProgramPersistenceTest.java |     2 -
 .../builder/eval/ValueExpressionEvaluator.java  |     6 +-
 .../kiwi/sparql/test/KiWiSparqlTest.java        |    56 +-
 .../marmotta/kiwi/sail/KiWiValueFactory.java    |    28 +-
 libraries/ostrich/Dockerfile                    |    77 +
 libraries/ostrich/README.md                     |   105 +
 libraries/ostrich/backend/.dockerignore         |     1 +
 libraries/ostrich/backend/CMakeLists.txt        |    42 +
 libraries/ostrich/backend/client/CMakeLists.txt |     9 +
 libraries/ostrich/backend/client/client.cc      |   379 +
 .../ostrich/backend/cmake/FindGFlags.cmake      |    48 +
 libraries/ostrich/backend/cmake/FindGLog.cmake  |    18 +
 libraries/ostrich/backend/cmake/FindGRPC.cmake  |    67 +
 .../ostrich/backend/cmake/FindLevelDB.cmake     |    18 +
 .../ostrich/backend/cmake/FindRAPTOR.cmake      |   103 +
 .../ostrich/backend/cmake/FindRasqal.cmake      |    99 +
 .../ostrich/backend/cmake/FindTcmalloc.cmake    |    39 +
 libraries/ostrich/backend/model/CMakeLists.txt  |     6 +
 libraries/ostrich/backend/model/model.proto     |    77 +
 libraries/ostrich/backend/model/rdf_model.cc    |   348 +
 libraries/ostrich/backend/model/rdf_model.h     |   709 +
 .../ostrich/backend/model/rdf_operators.cc      |    65 +
 libraries/ostrich/backend/model/rdf_operators.h |   240 +
 libraries/ostrich/backend/parser/CMakeLists.txt |     6 +
 libraries/ostrich/backend/parser/rdf_parser.cc  |   157 +
 libraries/ostrich/backend/parser/rdf_parser.h   |    94 +
 .../ostrich/backend/persistence/CMakeLists.txt  |    21 +
 .../backend/persistence/leveldb_persistence.cc  |   729 +
 .../backend/persistence/leveldb_persistence.h   |   185 +
 .../backend/persistence/leveldb_server.cc       |    73 +
 .../backend/persistence/leveldb_service.cc      |   307 +
 .../backend/persistence/leveldb_service.h       |   128 +
 .../backend/persistence/leveldb_sparql.cc       |    85 +
 .../backend/persistence/leveldb_sparql.h        |    52 +
 .../backend/persistence/marmotta_updatedb.cc    |   215 +
 .../ostrich/backend/serializer/CMakeLists.txt   |    10 +
 .../ostrich/backend/serializer/serializer.cc    |    49 +
 .../ostrich/backend/serializer/serializer.h     |    54 +
 .../backend/serializer/serializer_base.cc       |    76 +
 .../backend/serializer/serializer_base.h        |   104 +
 .../backend/serializer/serializer_proto.cc      |    56 +
 .../backend/serializer/serializer_proto.h       |    50 +
 .../backend/serializer/serializer_raptor.cc     |   175 +
 .../backend/serializer/serializer_raptor.h      |    55 +
 .../ostrich/backend/service/CMakeLists.txt      |     9 +
 libraries/ostrich/backend/service/sail.proto    |   102 +
 libraries/ostrich/backend/service/sparql.proto  |    53 +
 .../ostrich/backend/sharding/CMakeLists.txt     |    11 +
 libraries/ostrich/backend/sharding/server.cc    |    66 +
 libraries/ostrich/backend/sharding/sharding.cc  |   335 +
 libraries/ostrich/backend/sharding/sharding.h   |   174 +
 libraries/ostrich/backend/sparql/CMakeLists.txt |     8 +
 .../ostrich/backend/sparql/rasqal_adapter.cc    |   382 +
 .../ostrich/backend/sparql/rasqal_adapter.h     |   124 +
 .../ostrich/backend/sparql/rasqal_model.cc      |   205 +
 libraries/ostrich/backend/sparql/rasqal_model.h |    73 +
 libraries/ostrich/backend/test/CMakeLists.txt   |    20 +
 .../ostrich/backend/test/PersistenceTest.cc     |   268 +
 libraries/ostrich/backend/test/SparqlTest.cc    |   291 +
 libraries/ostrich/backend/test/StatementTest.cc |   135 +
 .../ostrich/backend/test/gmock-gtest-all.cc     | 12243 ++++++++++
 libraries/ostrich/backend/test/gmock/gmock.h    | 14978 ++++++++++++
 libraries/ostrich/backend/test/gtest/gtest.h    | 21197 +++++++++++++++++
 libraries/ostrich/backend/test/main.cc          |    11 +
 libraries/ostrich/backend/util/CMakeLists.txt   |     6 +
 libraries/ostrich/backend/util/iterator.h       |   315 +
 libraries/ostrich/backend/util/murmur3.cc       |   313 +
 libraries/ostrich/backend/util/murmur3.h        |    18 +
 libraries/ostrich/backend/util/raptor_util.cc   |   179 +
 libraries/ostrich/backend/util/raptor_util.h    |    74 +
 libraries/ostrich/backend/util/split.cc         |    40 +
 libraries/ostrich/backend/util/split.h          |    38 +
 libraries/ostrich/backend/util/time_logger.cc   |    17 +
 libraries/ostrich/backend/util/time_logger.h    |    32 +
 libraries/ostrich/backend/util/unique.h         |    23 +
 libraries/ostrich/client/pom.xml                |   234 +
 .../ostrich/sail/ClosableResponseStream.java    |   163 +
 .../marmotta/ostrich/sail/OstrichSail.java      |    87 +
 .../ostrich/sail/OstrichSailConnection.java     |   618 +
 .../ostrich/sail/OstrichValueFactory.java       |   260 +
 .../ostrich/sail/test/CMarmottaSailTest.java    |    74 +
 .../ostrich/sail/test/TestSailConnection.java   |    80 +
 libraries/ostrich/model/pom.xml                 |   219 +
 .../marmotta/ostrich/model/ProtoBNode.java      |    79 +
 .../ostrich/model/ProtoDatatypeLiteral.java     |   106 +
 .../ostrich/model/ProtoLiteralBase.java         |   187 +
 .../marmotta/ostrich/model/ProtoNamespace.java  |    86 +
 .../marmotta/ostrich/model/ProtoStatement.java  |   221 +
 .../ostrich/model/ProtoStringLiteral.java       |   101 +
 .../apache/marmotta/ostrich/model/ProtoURI.java |   113 +
 .../ostrich/model/test/StatementTest.java       |    68 +
 .../marmotta/ostrich/model/test/URITest.java    |    57 +
 .../model/src/test/resources/logback.xml        |    28 +
 libraries/ostrich/pom.xml                       |    60 +
 libraries/pom.xml                               |     9 +
 loader/marmotta-loader-ostrich/pom.xml          |    83 +
 .../loader/ostrich/OstrichLoaderBackend.java    |   100 +
 .../loader/ostrich/OstrichLoaderHandler.java    |   156 +
 ...org.apache.marmotta.loader.api.LoaderBackend |    18 +
 .../src/main/resources/logback.xml              |    32 +
 loader/pom.xml                                  |    10 +
 .../backends/marmotta-backend-ostrich/pom.xml   |   176 +
 .../backend/ostrich/OstrichProvider.java        |    97 +
 .../backend/ostrich/OstrichSailRepository.java  |   168 +
 .../src/main/resources/META-INF/beans.xml       |    28 +
 .../main/resources/config-defaults.properties   |    25 +
 .../resources/config-descriptions.properties    |    31 +
 .../src/main/resources/kiwi-module.properties   |    38 +
 .../src/main/resources/web/admin/about.html     |    36 +
 .../main/resources/web/admin/configuration.html |    52 +
 platform/backends/pom.xml                       |     6 +
 .../triplestore/ContextServiceImpl.java         |    82 +-
 .../test/triplestore/ContextServiceTest.java    |    78 +
 119 files changed, 61197 insertions(+), 150 deletions(-)
----------------------------------------------------------------------



[42/50] [abbrv] marmotta git commit: disable failing tests caused by config change

Posted by wi...@apache.org.
disable failing tests caused by config change


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/9779f366
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/9779f366
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/9779f366

Branch: refs/heads/MARMOTTA-584
Commit: 9779f3660d2e77b06078df93ecc29b26d89a8f0e
Parents: c8f067f
Author: Thomas Kurz <th...@salzburgresearch.at>
Authored: Fri Apr 22 10:17:36 2016 +0200
Committer: Thomas Kurz <th...@salzburgresearch.at>
Committed: Fri Apr 22 10:17:36 2016 +0200

----------------------------------------------------------------------
 .../kiwi/sparql/test/ComplexKiWiSparqlQueryTest.java  | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/9779f366/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/ComplexKiWiSparqlQueryTest.java
----------------------------------------------------------------------
diff --git a/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/ComplexKiWiSparqlQueryTest.java b/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/ComplexKiWiSparqlQueryTest.java
index 4126495..6158081 100644
--- a/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/ComplexKiWiSparqlQueryTest.java
+++ b/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/ComplexKiWiSparqlQueryTest.java
@@ -56,4 +56,18 @@ public class ComplexKiWiSparqlQueryTest extends ComplexSPARQLQueryTest {
         super.testSES1898LeftJoinSemantics1();
     }
 
+    @Test
+    @Override
+    @Ignore("Ignored because of http://git-wip-us.apache.org/repos/asf/marmotta/commit/35b98edc")
+    public void testSES1991UUIDEvaluation() throws Exception {
+        super.testSES1991UUIDEvaluation();
+    }
+
+    @Test
+    @Override
+    @Ignore("Ignored because of http://git-wip-us.apache.org/repos/asf/marmotta/commit/35b98edc")
+    public void testSES1991STRUUIDEvaluation() throws Exception {
+        super.testSES1991STRUUIDEvaluation();
+    }
+
 }


[23/50] [abbrv] marmotta git commit: MARMOTTA-627: recovered all dialects

Posted by wi...@apache.org.
MARMOTTA-627: recovered all dialects


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/6eb09733
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/6eb09733
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/6eb09733

Branch: refs/heads/MARMOTTA-584
Commit: 6eb09733b31eeb935d0f8c003b75f4d110cdb063
Parents: 1eb0065
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Thu Feb 11 14:41:04 2016 +0100
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Thu Feb 11 14:41:04 2016 +0100

----------------------------------------------------------------------
 .../org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java    | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/6eb09733/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java
----------------------------------------------------------------------
diff --git a/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java b/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java
index 4a615bc..1246845 100644
--- a/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java
+++ b/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java
@@ -23,7 +23,6 @@ import info.aduna.iteration.Iterations;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.io.IOUtils;
 import org.apache.marmotta.kiwi.config.KiWiConfiguration;
-import org.apache.marmotta.kiwi.persistence.pgsql.PostgreSQLDialect;
 import org.apache.marmotta.kiwi.sail.KiWiStore;
 import org.apache.marmotta.kiwi.sparql.sail.KiWiSparqlSail;
 import org.apache.marmotta.kiwi.test.junit.KiWiDatabaseRunner;
@@ -31,7 +30,8 @@ import org.junit.*;
 import org.junit.rules.TestWatcher;
 import org.junit.runner.Description;
 import org.junit.runner.RunWith;
-import org.openrdf.model.*;
+import org.openrdf.model.BNode;
+import org.openrdf.model.Literal;
 import org.openrdf.query.*;
 import org.openrdf.repository.Repository;
 import org.openrdf.repository.RepositoryConnection;
@@ -55,7 +55,6 @@ import java.util.Set;
  * @author Sergio Fern�mdez
  */
 @RunWith(KiWiDatabaseRunner.class)
-@KiWiDatabaseRunner.ForDialects(PostgreSQLDialect.class)
 public class KiWiSparqlTest {
 
     final Logger log = LoggerFactory.getLogger(this.getClass());


[49/50] [abbrv] marmotta git commit: merged develop into MARMOTTA-584

Posted by wi...@apache.org.
merged develop into MARMOTTA-584


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/653706d0
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/653706d0
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/653706d0

Branch: refs/heads/MARMOTTA-584
Commit: 653706d003644490b0d4a526ddb676cd3d0236a0
Parents: fc5bb28 1d20483
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Mon May 2 09:35:07 2016 +0200
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Mon May 2 09:35:07 2016 +0200

----------------------------------------------------------------------
 .dockerignore                                   |     2 +
 Dockerfile                                      |    81 +
 README.md                                       |   127 +
 README.txt                                      |   119 -
 launchers/marmotta-webapp/README.md             |    50 +
 launchers/marmotta-webapp/pom.xml               |    22 +
 .../marmotta-webapp/src/deb/control/control     |     2 +-
 .../marmotta-webapp/src/docker/entrypoint.sh    |    23 +
 .../kiwi/reasoner/parser/KWRLProgramParser.jj   |    26 +-
 .../test/parser/KWRLRuleParserTest.java         |    41 +-
 .../persistence/KWRLProgramPersistenceTest.java |     2 -
 .../builder/eval/ValueExpressionEvaluator.java  |     6 +-
 .../sparql/optimizer/NativeFilterOptimizer.java |   198 +
 .../sparql/sail/KiWiSparqlSailConnection.java   |     5 +-
 .../sparql/test/ComplexKiWiSparqlQueryTest.java |    14 +
 .../kiwi/sparql/test/KiWiSparqlTest.java        |    56 +-
 .../marmotta/kiwi/sail/KiWiValueFactory.java    |    43 +-
 .../services/test/ng/BaseLDCacheTest.java       |     7 +-
 .../test/rdf/TestLinkedDataProvider.java        |     1 +
 libraries/ostrich/Dockerfile                    |    77 +
 libraries/ostrich/README.md                     |   105 +
 libraries/ostrich/backend/.dockerignore         |     1 +
 libraries/ostrich/backend/CMakeLists.txt        |    42 +
 libraries/ostrich/backend/client/CMakeLists.txt |     9 +
 libraries/ostrich/backend/client/client.cc      |   379 +
 .../ostrich/backend/cmake/FindGFlags.cmake      |    48 +
 libraries/ostrich/backend/cmake/FindGLog.cmake  |    18 +
 libraries/ostrich/backend/cmake/FindGRPC.cmake  |    67 +
 .../ostrich/backend/cmake/FindLevelDB.cmake     |    18 +
 .../ostrich/backend/cmake/FindRAPTOR.cmake      |   103 +
 .../ostrich/backend/cmake/FindRasqal.cmake      |    99 +
 .../ostrich/backend/cmake/FindTcmalloc.cmake    |    39 +
 libraries/ostrich/backend/model/CMakeLists.txt  |     6 +
 libraries/ostrich/backend/model/model.proto     |    77 +
 libraries/ostrich/backend/model/rdf_model.cc    |   348 +
 libraries/ostrich/backend/model/rdf_model.h     |   709 +
 .../ostrich/backend/model/rdf_operators.cc      |    65 +
 libraries/ostrich/backend/model/rdf_operators.h |   240 +
 libraries/ostrich/backend/parser/CMakeLists.txt |     6 +
 libraries/ostrich/backend/parser/rdf_parser.cc  |   157 +
 libraries/ostrich/backend/parser/rdf_parser.h   |    94 +
 .../ostrich/backend/persistence/CMakeLists.txt  |    21 +
 .../backend/persistence/leveldb_persistence.cc  |   729 +
 .../backend/persistence/leveldb_persistence.h   |   185 +
 .../backend/persistence/leveldb_server.cc       |    73 +
 .../backend/persistence/leveldb_service.cc      |   307 +
 .../backend/persistence/leveldb_service.h       |   128 +
 .../backend/persistence/leveldb_sparql.cc       |    85 +
 .../backend/persistence/leveldb_sparql.h        |    52 +
 .../backend/persistence/marmotta_updatedb.cc    |   215 +
 .../ostrich/backend/serializer/CMakeLists.txt   |    10 +
 .../ostrich/backend/serializer/serializer.cc    |    49 +
 .../ostrich/backend/serializer/serializer.h     |    54 +
 .../backend/serializer/serializer_base.cc       |    76 +
 .../backend/serializer/serializer_base.h        |   104 +
 .../backend/serializer/serializer_proto.cc      |    56 +
 .../backend/serializer/serializer_proto.h       |    50 +
 .../backend/serializer/serializer_raptor.cc     |   175 +
 .../backend/serializer/serializer_raptor.h      |    55 +
 .../ostrich/backend/service/CMakeLists.txt      |     9 +
 libraries/ostrich/backend/service/sail.proto    |   102 +
 libraries/ostrich/backend/service/sparql.proto  |    53 +
 .../ostrich/backend/sharding/CMakeLists.txt     |    11 +
 libraries/ostrich/backend/sharding/server.cc    |    66 +
 libraries/ostrich/backend/sharding/sharding.cc  |   335 +
 libraries/ostrich/backend/sharding/sharding.h   |   174 +
 libraries/ostrich/backend/sparql/CMakeLists.txt |     8 +
 .../ostrich/backend/sparql/rasqal_adapter.cc    |   382 +
 .../ostrich/backend/sparql/rasqal_adapter.h     |   124 +
 .../ostrich/backend/sparql/rasqal_model.cc      |   205 +
 libraries/ostrich/backend/sparql/rasqal_model.h |    73 +
 libraries/ostrich/backend/test/CMakeLists.txt   |    20 +
 .../ostrich/backend/test/PersistenceTest.cc     |   268 +
 libraries/ostrich/backend/test/SparqlTest.cc    |   291 +
 libraries/ostrich/backend/test/StatementTest.cc |   135 +
 .../ostrich/backend/test/gmock-gtest-all.cc     | 12243 ++++++++++
 libraries/ostrich/backend/test/gmock/gmock.h    | 14978 ++++++++++++
 libraries/ostrich/backend/test/gtest/gtest.h    | 21197 +++++++++++++++++
 libraries/ostrich/backend/test/main.cc          |    11 +
 libraries/ostrich/backend/util/CMakeLists.txt   |     6 +
 libraries/ostrich/backend/util/iterator.h       |   315 +
 libraries/ostrich/backend/util/murmur3.cc       |   313 +
 libraries/ostrich/backend/util/murmur3.h        |    18 +
 libraries/ostrich/backend/util/raptor_util.cc   |   179 +
 libraries/ostrich/backend/util/raptor_util.h    |    74 +
 libraries/ostrich/backend/util/split.cc         |    40 +
 libraries/ostrich/backend/util/split.h          |    38 +
 libraries/ostrich/backend/util/time_logger.cc   |    17 +
 libraries/ostrich/backend/util/time_logger.h    |    32 +
 libraries/ostrich/backend/util/unique.h         |    23 +
 libraries/ostrich/client/pom.xml                |   234 +
 .../ostrich/sail/ClosableResponseStream.java    |   163 +
 .../marmotta/ostrich/sail/OstrichSail.java      |    87 +
 .../ostrich/sail/OstrichSailConnection.java     |   618 +
 .../ostrich/sail/OstrichValueFactory.java       |   260 +
 .../ostrich/sail/test/CMarmottaSailTest.java    |    74 +
 .../ostrich/sail/test/TestSailConnection.java   |    80 +
 libraries/ostrich/model/pom.xml                 |   219 +
 .../marmotta/ostrich/model/ProtoBNode.java      |    79 +
 .../ostrich/model/ProtoDatatypeLiteral.java     |   106 +
 .../ostrich/model/ProtoLiteralBase.java         |   187 +
 .../marmotta/ostrich/model/ProtoNamespace.java  |    86 +
 .../marmotta/ostrich/model/ProtoStatement.java  |   221 +
 .../ostrich/model/ProtoStringLiteral.java       |   101 +
 .../apache/marmotta/ostrich/model/ProtoURI.java |   113 +
 .../ostrich/model/test/StatementTest.java       |    68 +
 .../marmotta/ostrich/model/test/URITest.java    |    57 +
 .../model/src/test/resources/logback.xml        |    28 +
 libraries/ostrich/pom.xml                       |    60 +
 libraries/pom.xml                               |     9 +
 loader/marmotta-loader-ostrich/pom.xml          |    83 +
 .../loader/ostrich/OstrichLoaderBackend.java    |   100 +
 .../loader/ostrich/OstrichLoaderHandler.java    |   156 +
 ...org.apache.marmotta.loader.api.LoaderBackend |    18 +
 .../src/main/resources/logback.xml              |    32 +
 loader/pom.xml                                  |    10 +
 parent/pom.xml                                  |     6 +-
 .../src/main/resources/web/admin/about.html     |    41 +-
 .../main/resources/web/admin/configuration.html |     7 +-
 .../src/main/resources/web/admin/console.html   |     2 +-
 .../src/main/resources/web/admin/database.html  |     2 +-
 .../backends/marmotta-backend-ostrich/pom.xml   |   176 +
 .../backend/ostrich/OstrichProvider.java        |    97 +
 .../backend/ostrich/OstrichSailRepository.java  |   168 +
 .../src/main/resources/META-INF/beans.xml       |    28 +
 .../main/resources/config-defaults.properties   |    25 +
 .../resources/config-descriptions.properties    |    31 +
 .../src/main/resources/kiwi-module.properties   |    38 +
 .../src/main/resources/web/admin/about.html     |    36 +
 .../main/resources/web/admin/configuration.html |    52 +
 platform/backends/pom.xml                       |     6 +
 .../triplestore/ContextServiceImpl.java         |    82 +-
 .../test/triplestore/ContextServiceTest.java    |    78 +
 133 files changed, 61616 insertions(+), 204 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/653706d0/libraries/kiwi/kiwi-sparql/src/main/java/org/apache/marmotta/kiwi/sparql/builder/eval/ValueExpressionEvaluator.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/marmotta/blob/653706d0/libraries/kiwi/kiwi-triplestore/src/main/java/org/apache/marmotta/kiwi/sail/KiWiValueFactory.java
----------------------------------------------------------------------
diff --cc libraries/kiwi/kiwi-triplestore/src/main/java/org/apache/marmotta/kiwi/sail/KiWiValueFactory.java
index e02d82b,3a717a2..a5cb8d3
--- a/libraries/kiwi/kiwi-triplestore/src/main/java/org/apache/marmotta/kiwi/sail/KiWiValueFactory.java
+++ b/libraries/kiwi/kiwi-triplestore/src/main/java/org/apache/marmotta/kiwi/sail/KiWiValueFactory.java
@@@ -566,14 -556,16 +566,16 @@@ public class KiWiValueFactory implement
      public Statement createStatement(Resource subject, URI predicate, Value object, Resource context, KiWiConnection connection) {
          try {
  
--            IntArray cacheKey = IntArray.createSPOCKey(subject, predicate, object, context);
++            final IntArray cacheKey = IntArray.createSPOCKey(subject, predicate, object, context);
  
-             KiWiResource ksubject = convert(subject);
 -            KiWiResource ksubject   = convert(subject);
--            KiWiUriResource kpredicate = convert(predicate);
-             KiWiNode kobject = convert(object);
-             KiWiResource kcontext = convert(context);
 -            KiWiNode kobject    = convert(object);
 -            KiWiResource    kcontext   = convert(context);
++            final KiWiResource ksubject = convert(subject);
++            final KiWiUriResource kpredicate = convert(predicate);
++            final KiWiNode kobject = convert(object);
++            final KiWiResource kcontext = convert(context);
  
-             KiWiTriple result = new KiWiTriple(ksubject, kpredicate, kobject, kcontext);
 -            KiWiTriple result = new KiWiTriple(ksubject,kpredicate,kobject,kcontext);
++            final KiWiTriple result = new KiWiTriple(ksubject, kpredicate, kobject, kcontext);
+ 
+             boolean needsDBLookup = false;
  
              synchronized (registry) {
                  long tripleId = registry.lookupKey(cacheKey);
@@@ -585,13 -577,29 +587,29 @@@
                      registry.registerKey(cacheKey, connection.getTransactionId(), result.getId());
                  } else {
                      // not found in registry, try loading from database
-                     result.setId(connection.getTripleId(ksubject, kpredicate, kobject, kcontext));
+                     needsDBLookup = true;
                  }
+             }
+ 
 -            if(needsDBLookup) {
 -                result.setId(connection.getTripleId(ksubject,kpredicate,kobject,kcontext));
++            if (needsDBLookup) {
++                result.setId(connection.getTripleId(ksubject, kpredicate, kobject, kcontext));
+             }
  
-                 // triple has no id from registry or database, so we create one and flag it for reasoning
-                 if (result.getId() < 0) {
-                     result.setId(connection.getNextSequence());
-                     result.setNewTriple(true);
+             // triple has no id from registry or database, so we create one and flag it for reasoning
 -            if(result.getId() < 0) {
++            if (result.getId() < 0) {
+                 synchronized (registry) {
+                     // It's possible a concurrent thread might have created this
+                     // triple while we were blocked.  Check the registry again.
+                     long tripleId = registry.lookupKey(cacheKey);
+ 
+                     if(tripleId >= 0) {
+                         // A concurrent thread got in first.  Take the one it created.
+                         result.setId(tripleId);
+                     } else {
+                         // Create the new triple
+                         result.setId(connection.getNextSequence());
+                         result.setNewTriple(true);
+                     }
  
                      registry.registerKey(cacheKey, connection.getTransactionId(), result.getId());
                  }
@@@ -652,19 -659,10 +670,20 @@@
  
      }
  
 -
      public void close() {
+ 
      }
  
 +    /**
 +     *
 +     * @param value
 +     * @return
 +     */
 +    public boolean isGeometry(String value) {
 +        if (value.contains("POINT") || value.contains("MULTIPOINT") || value.contains("LINESTRING") || value.contains("MULTILINESTRING") || value.contains("POLYGON") || value.contains("MULTIPOLYGON")) {
 +            return true;
 +        }
 +        return false;
 +    }
  
- }
+ }

http://git-wip-us.apache.org/repos/asf/marmotta/blob/653706d0/parent/pom.xml
----------------------------------------------------------------------


[02/50] [abbrv] marmotta git commit: refactor iterator implementations, they were broken

Posted by wi...@apache.org.
http://git-wip-us.apache.org/repos/asf/marmotta/blob/2e32da5d/libraries/ostrich/backend/test/main.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/test/main.cc b/libraries/ostrich/backend/test/main.cc
index 40755a6..5e6a52b 100644
--- a/libraries/ostrich/backend/test/main.cc
+++ b/libraries/ostrich/backend/test/main.cc
@@ -1,7 +1,7 @@
 // Copyright 2015 Google Inc. All Rights Reserved.
 // Author: Sebastian Schaffert <sc...@google.com>
 #include <glog/logging.h>
-#include "gtest.h"
+#include "gtest/gtest.h"
 
 // run all tests in the current binary
 int main(int argc, char **argv) {

http://git-wip-us.apache.org/repos/asf/marmotta/blob/2e32da5d/libraries/ostrich/backend/util/iterator.h
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/util/iterator.h b/libraries/ostrich/backend/util/iterator.h
index 002c24f..0d34a4b 100644
--- a/libraries/ostrich/backend/util/iterator.h
+++ b/libraries/ostrich/backend/util/iterator.h
@@ -23,6 +23,10 @@
 #ifndef MARMOTTA_ITERATOR_H
 #define MARMOTTA_ITERATOR_H
 
+#include <queue>
+#include <mutex>
+#include <condition_variable>
+
 namespace marmotta {
 namespace util {
 
@@ -39,19 +43,14 @@ class CloseableIterator {
     virtual ~CloseableIterator() {}
 
     /**
-     * Increment iterator to next element.
+     * Increment iterator to next element and return a reference to this element.
     */
-    virtual CloseableIterator<T>& operator++() = 0;
-
-    /**
-     * Dereference iterator, returning a reference to the current element.
-     */
-    virtual T& operator*() = 0;
+    virtual const T& next() = 0;
 
     /**
-     * Dereference iterator, returning a pointer to the current element.
+     * Return a reference to the current element.
      */
-    virtual T* operator->() = 0;
+    virtual const T& current() const = 0;
 
     /**
      * Return true in case the iterator has more elements.
@@ -68,15 +67,11 @@ class EmptyIterator : public CloseableIterator<T> {
  public:
     EmptyIterator() { }
 
-    CloseableIterator<T> &operator++() override {
-        return *this;
-    }
-
-    T &operator*() override {
+    const T &next() override {
         throw std::out_of_range("No more elements");
     };
 
-    T *operator->() override {
+    const T &current() const override {
         throw std::out_of_range("No more elements");
     };
 
@@ -95,23 +90,21 @@ class SingletonIterator : public CloseableIterator<T> {
  public:
     SingletonIterator(T& value) : value(value), incremented(false) { }
 
-    CloseableIterator<T> &operator++() override {
-        incremented = true;
-        return *this;
-    };
-
-    T &operator*() override {
-        if (!incremented)
+    const T &next() override {
+        if (!incremented) {
+            incremented = true;
             return value;
-        else
+        } else {
             throw std::out_of_range("No more elements");
+        }
     };
 
-    T *operator->() override {
-        if (!incremented)
-            return &value;
-        else
+    const T &current() const override {
+        if (!incremented) {
+            return value;
+        } else {
             throw std::out_of_range("No more elements");
+        }
     };
 
     bool hasNext() override {
@@ -124,7 +117,37 @@ class SingletonIterator : public CloseableIterator<T> {
 
 };
 
+/**
+ * An iterator wrapping a standard STL collection iterator.
+ */
+template<typename T>
+class CollectionIterator : public CloseableIterator<T> {
+ public:
+    CollectionIterator(std::vector<T> values)
+            : values(values), index(0) {
+    }
 
+    const T& next() override {
+        index++;
+        return values[index-1];
+    };
+
+    const T& current() const override {
+        return values[index-1];
+    };
+
+    bool hasNext() override {
+        return index < values.size();
+    };
+
+ private:
+    std::vector<T> values;
+    int index;
+};
+
+/**
+ * An iterator implementation supporting to pass a predicate for filtering values.
+ */
 template<typename T>
 class FilteringIterator : public CloseableIterator<T> {
  public:
@@ -137,31 +160,20 @@ class FilteringIterator : public CloseableIterator<T> {
      */
     FilteringIterator(CloseableIterator<T>* it,  PredicateFn pred)
             : it(it), pred(pred), nextExists(false) {
-        // run findNext twice so both current and next are set
-        findNext();
+        // run findNext once so next is set
         findNext();
     }
 
     /**
      * Increment iterator to next element.
-    */
-    CloseableIterator<T>& operator++() override {
-        findNext();
-        return *this;
-    };
-
-    /**
-     * Dereference iterator, returning a reference to the current element.
      */
-    T& operator*() override {
-        return current;
+    const T& next() override {
+        findNext();
+        return current_;
     };
 
-    /**
-     * Dereference iterator, returning a pointer to the current element.
-     */
-    T* operator->() override {
-        return &current;
+    const T& current() const override {
+        return current_;
     };
 
     /**
@@ -176,18 +188,18 @@ class FilteringIterator : public CloseableIterator<T> {
     std::unique_ptr<CloseableIterator<T>> it;
     PredicateFn pred;
 
-    T current;
-    T next;
+    T current_;
+    T next_;
 
     bool nextExists;
 
     void findNext() {
-        current = next;
+        current_ = next_;
         nextExists = false;
 
         while (it->hasNext()) {
-            if (pred(**it)) {
-                next = **it;
+            next_ = it->next();
+            if (pred(next_)) {
                 nextExists = true;
                 break;
             }
@@ -195,6 +207,69 @@ class FilteringIterator : public CloseableIterator<T> {
     }
 };
 
+/**
+ * A multi-threaded iterator supporting iteration over the results
+ * successively added by a producer. Blocks while the internal queue
+ * is empty and the producer is not yet finished reporting. The
+ * producer has to explicitly call finish() when there are no more
+ * elements to report.
+ */
+template<typename T>
+class ProducerConsumerIterator : public CloseableIterator<T> {
+ public:
+    ProducerConsumerIterator() {}
+
+    void add(const T& value) {
+        std::unique_lock<std::mutex> lock(mutex);
+        queue.push(value);
+        condition.notify_one();
+    }
+
+    void finish() {
+        std::unique_lock<std::mutex> lock(mutex);
+        finished = true;
+        condition.notify_all();
+    }
+
+    /**
+     * Increment iterator to next element.
+     */
+    const T& next() override {
+        if (hasNext()) {
+            std::unique_lock<std::mutex> lock(mutex);
+            current_ = queue.front();
+            queue.pop();
+        }
+        return current_;
+    };
+
+    const T& current() const override {
+        return current_;
+    };
+
+    /**
+     * Return true in case the iterator has more elements.
+     */
+    bool hasNext() override {
+        std::unique_lock<std::mutex> lock(mutex);
+        if (queue.size() > 0) {
+            return true;
+        }
+        if (finished) {
+            return false;
+        }
+        condition.wait(lock);
+        return hasNext();
+    };
+
+ private:
+    std::queue<T> queue;
+    std::mutex mutex;
+    std::condition_variable condition;
+
+    bool finished;
+    T current_;
+};
 
 }
 }


[18/50] [abbrv] marmotta git commit: some fine tuning

Posted by wi...@apache.org.
some fine tuning


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/ea28ddb1
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/ea28ddb1
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/ea28ddb1

Branch: refs/heads/MARMOTTA-584
Commit: ea28ddb1af6b6cdd2aa58ac792337d378925295a
Parents: 8f60cf6
Author: Sebastian Schaffert <ss...@apache.org>
Authored: Sun Dec 20 13:12:04 2015 +0100
Committer: Sebastian Schaffert <ss...@apache.org>
Committed: Sun Dec 20 13:12:04 2015 +0100

----------------------------------------------------------------------
 libraries/ostrich/backend/persistence/leveldb_persistence.cc  | 7 +++++--
 .../apache/marmotta/loader/ostrich/OstrichLoaderBackend.java  | 4 ++--
 2 files changed, 7 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/ea28ddb1/libraries/ostrich/backend/persistence/leveldb_persistence.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/persistence/leveldb_persistence.cc b/libraries/ostrich/backend/persistence/leveldb_persistence.cc
index 365397e..759acc6 100644
--- a/libraries/ostrich/backend/persistence/leveldb_persistence.cc
+++ b/libraries/ostrich/backend/persistence/leveldb_persistence.cc
@@ -302,6 +302,9 @@ leveldb::Options* buildOptions(KeyComparator* cmp, leveldb::Cache* cache) {
     // Cache reads in memory.
     options->block_cache = cache;
 
+    // Write buffer size 16MB (fast bulk imports)
+    options->write_buffer_size = 16384 * 1024;
+
     // Set a bloom filter of 10 bits.
     options->filter_policy = leveldb::NewBloomFilterPolicy(10);
     return options;
@@ -549,7 +552,7 @@ int64_t LevelDBPersistence::RemoveStatements(const rdf::proto::Statement& patter
 
 UpdateStatistics LevelDBPersistence::Update(LevelDBPersistence::UpdateIterator &it) {
     auto start = std::chrono::steady_clock::now();
-    DLOG(INFO) << "Starting batch update operation.";
+    LOG(INFO) << "Starting batch update operation.";
     UpdateStatistics stats;
 
     WriteBatch b_spoc, b_cspo, b_opsc, b_pcos, b_prefix, b_url;
@@ -592,7 +595,7 @@ UpdateStatistics LevelDBPersistence::Update(LevelDBPersistence::UpdateIterator &
         t.join();
     }
 
-    DLOG(INFO) << "Batch update complete. (statements added: " << stats.added_stmts
+    LOG(INFO) << "Batch update complete. (statements added: " << stats.added_stmts
             << ", statements removed: " << stats.removed_stmts
             << ", namespaces added: " << stats.added_ns
             << ", namespaces removed: " << stats.removed_ns

http://git-wip-us.apache.org/repos/asf/marmotta/blob/ea28ddb1/loader/marmotta-loader-ostrich/src/main/java/org/apache/marmotta/loader/ostrich/OstrichLoaderBackend.java
----------------------------------------------------------------------
diff --git a/loader/marmotta-loader-ostrich/src/main/java/org/apache/marmotta/loader/ostrich/OstrichLoaderBackend.java b/loader/marmotta-loader-ostrich/src/main/java/org/apache/marmotta/loader/ostrich/OstrichLoaderBackend.java
index bd6e49e..ddb4bce 100644
--- a/loader/marmotta-loader-ostrich/src/main/java/org/apache/marmotta/loader/ostrich/OstrichLoaderBackend.java
+++ b/loader/marmotta-loader-ostrich/src/main/java/org/apache/marmotta/loader/ostrich/OstrichLoaderBackend.java
@@ -45,7 +45,7 @@ public class OstrichLoaderBackend implements LoaderBackend {
         return new OstrichLoaderHandler(
                 configuration.getString("backend.ostrich.host", "localhost"),
                 configuration.getInt("backend.ostrich.port", 10000),
-                configuration.getLong("backend.ostrich.batchsize", 500000));
+                configuration.getLong("backend.ostrich.batchsize", 1000000));
     }
 
     /**
@@ -90,7 +90,7 @@ public class OstrichLoaderBackend implements LoaderBackend {
         Option batchSize =
                 OptionBuilder.withArgName("batchsize")
                         .hasArgs(1)
-                        .withDescription("maximum number of statements to commit in one batch")
+                        .withDescription("maximum number of statements to commit in one batch (default 1M)")
                         .withLongOpt("batchsize")
                         .create('B');
         options.add(batchSize);


[09/50] [abbrv] marmotta git commit: fix filtering in persistence

Posted by wi...@apache.org.
fix filtering in persistence


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/ba1168d2
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/ba1168d2
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/ba1168d2

Branch: refs/heads/MARMOTTA-584
Commit: ba1168d25c12facc5f9ecf11b70ec561851bb7e3
Parents: 2e32da5
Author: Sebastian Schaffert <ss...@apache.org>
Authored: Sat Dec 19 16:36:31 2015 +0100
Committer: Sebastian Schaffert <ss...@apache.org>
Committed: Sat Dec 19 16:36:31 2015 +0100

----------------------------------------------------------------------
 .../backend/persistence/leveldb_persistence.cc  | 66 ++++++++++++++------
 1 file changed, 48 insertions(+), 18 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/ba1168d2/libraries/ostrich/backend/persistence/leveldb_persistence.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/persistence/leveldb_persistence.cc b/libraries/ostrich/backend/persistence/leveldb_persistence.cc
index dd9eef9..1157869 100644
--- a/libraries/ostrich/backend/persistence/leveldb_persistence.cc
+++ b/libraries/ostrich/backend/persistence/leveldb_persistence.cc
@@ -84,7 +84,7 @@ class PatternQuery {
         SPOC, CSPO, OPSC, PCOS
     };
 
-    PatternQuery(const Statement& pattern) : pattern(pattern) {
+    PatternQuery(const Statement& pattern) : pattern(pattern), needsFilter(true) {
         if (pattern.has_subject()) {
             s.reset(new std::string());
             pattern.subject().SerializeToString(s.get());
@@ -110,17 +110,32 @@ class PatternQuery {
             } else {
                 type_ = SPOC;
             }
+
+            // Filter needed if there is no predicate but an object.
+            needsFilter = !(pattern.has_predicate()) && pattern.has_object();
         } else if (pattern.has_object()) {
             // Second-best option is object.
             type_ = OPSC;
+
+            // Filter needed if there is a context (subject already checked, predicate irrelevant).
+            needsFilter = pattern.has_context();
         } else if (pattern.has_predicate()) {
             // Predicate is usually least selective.
             type_ = PCOS;
+
+            // No filter needed, object and subject are not set.
+            needsFilter = false;
         } else if (pattern.has_context()) {
             type_ = CSPO;
+
+            // No filter needed, subject, predicate object are not set.
+            needsFilter = false;
         } else {
             // Fall back to SPOC.
             type_ = SPOC;
+
+            // No filter needed, we just scan from the beginning.
+            needsFilter = false;
         }
     }
 
@@ -155,6 +170,10 @@ class PatternQuery {
         return *this;
     }
 
+    bool NeedsFilter() const {
+        return needsFilter;
+    }
+
  private:
     const Statement& pattern;
     std::unique_ptr<std::string> s, p, o, c;
@@ -178,6 +197,7 @@ class PatternQuery {
     }
 
     IndexType type_;
+    bool needsFilter = true;
 };
 
 
@@ -240,6 +260,22 @@ class StatementRangeIterator : public LevelDBIterator<Statement> {
     char *hiKey;
 };
 
+
+bool Matches(const Statement& pattern, const Statement& stmt) {
+    // equality operators defined in rdf_model.h
+    if (pattern.has_context() && stmt.context() != pattern.context()) {
+        return false;
+    }
+    if (pattern.has_subject() && stmt.subject() != pattern.subject()) {
+        return false;
+    }
+    if (pattern.has_predicate() && stmt.predicate() != pattern.predicate()) {
+        return false;
+    }
+    return !(pattern.has_object() && stmt.object() != pattern.object());
+}
+
+
 }  // namespace
 
 
@@ -441,23 +477,17 @@ std::unique_ptr<LevelDBPersistence::StatementIterator> LevelDBPersistence::GetSt
             break;
     };
 
-    return std::unique_ptr<StatementIterator>(
-            new util::FilteringIterator<Statement>(
-                    new StatementRangeIterator(
-                            db->NewIterator(leveldb::ReadOptions()), query.MinKey(), query.MaxKey()),
-                    [&pattern](const Statement& stmt) -> bool {
-                        // equality operators defined in rdf_model.h
-                        if (pattern.has_context() && stmt.context() != pattern.context()) {
-                            return false;
-                        }
-                        if (pattern.has_subject() && stmt.subject() != pattern.subject()) {
-                            return false;
-                        }
-                        if (pattern.has_predicate() && stmt.predicate() != pattern.predicate()) {
-                            return false;
-                        }
-                        return !(pattern.has_object() && stmt.object() != pattern.object());
-                    }));
+    if (query.NeedsFilter()) {
+        return std::unique_ptr<StatementIterator>(
+                new util::FilteringIterator<Statement>(
+                        new StatementRangeIterator(
+                                db->NewIterator(leveldb::ReadOptions()), query.MinKey(), query.MaxKey()),
+                        [&pattern](const Statement& stmt) -> bool { return Matches(pattern, stmt); }));
+    } else {
+        return std::unique_ptr<StatementIterator>(
+                new StatementRangeIterator(
+                        db->NewIterator(leveldb::ReadOptions()), query.MinKey(), query.MaxKey()));
+    }
 }
 
 


[50/50] [abbrv] marmotta git commit: MARMOTTA-584: cosmetics

Posted by wi...@apache.org.
MARMOTTA-584: cosmetics


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/cde06ca1
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/cde06ca1
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/cde06ca1

Branch: refs/heads/MARMOTTA-584
Commit: cde06ca13b1f3a42955b84706e0575d662551a8b
Parents: 653706d
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Mon May 2 11:48:22 2016 +0200
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Mon May 2 11:49:10 2016 +0200

----------------------------------------------------------------------
 .../persistence/pgsql/upgrade_base_004_005.sql  | 15 ++--
 .../marmotta/kiwi/test/PersistenceTest.java     | 73 ++++----------------
 2 files changed, 21 insertions(+), 67 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/cde06ca1/libraries/kiwi/kiwi-triplestore/src/main/resources/org/apache/marmotta/kiwi/persistence/pgsql/upgrade_base_004_005.sql
----------------------------------------------------------------------
diff --git a/libraries/kiwi/kiwi-triplestore/src/main/resources/org/apache/marmotta/kiwi/persistence/pgsql/upgrade_base_004_005.sql b/libraries/kiwi/kiwi-triplestore/src/main/resources/org/apache/marmotta/kiwi/persistence/pgsql/upgrade_base_004_005.sql
index 75cc875..b1de974 100644
--- a/libraries/kiwi/kiwi-triplestore/src/main/resources/org/apache/marmotta/kiwi/persistence/pgsql/upgrade_base_004_005.sql
+++ b/libraries/kiwi/kiwi-triplestore/src/main/resources/org/apache/marmotta/kiwi/persistence/pgsql/upgrade_base_004_005.sql
@@ -16,26 +16,25 @@
 
 --creating new type 'geom'
 -- 1. rename the enum type 
-alter type nodetype rename to nodetype_old;
+ALTER TYPE nodetype RENAME TO nodetype_old;
 -- 2. create new type
 CREATE TYPE nodetype AS ENUM ('uri','bnode','string','int','double','date','boolean','geom');
 -- 3. rename column(s) which uses our enum type
-alter table nodes rename column ntype to ntype_old;
+ALTER TABLE nodes RENAME COLUMN ntype TO ntype_old;
 -- 4. add new column of new type
-alter table nodes add ntype nodetype;
+ALTER TABLE nodes ADD ntype nodetype;
 -- 5. copy values to the new column
-update nodes set ntype = ntype_old::text::nodetype;
+UPDATE nodes SET ntype = ntype_old::text::nodetype;
 -- 6. remove old column and type
-alter table nodes drop column ntype_old;
-
+ALTER TABLE nodes DROP COLUMN ntype_old;
 -- 7. delete old enum type
-drop type nodetype_old;
+DROP TYPE nodetype_old;
 
 --necessary for use spatial queries
 CREATE EXTENSION IF NOT EXISTS POSTGIS;
 
 --adding geometry colum
-ALTER TABLE nodes ADD COLUMN gvalue geometry;
+ALTER TABLE nodes ADD COLUMN gvalue GEOMETRY;
 
 UPDATE METADATA SET mvalue = '5' WHERE mkey = 'version';
 INSERT INTO metadata(mkey,mvalue) VALUES ('updated',to_char(now(),'yyyy-MM-DD HH:mm:ss TZ') );

http://git-wip-us.apache.org/repos/asf/marmotta/blob/cde06ca1/libraries/kiwi/kiwi-triplestore/src/test/java/org/apache/marmotta/kiwi/test/PersistenceTest.java
----------------------------------------------------------------------
diff --git a/libraries/kiwi/kiwi-triplestore/src/test/java/org/apache/marmotta/kiwi/test/PersistenceTest.java b/libraries/kiwi/kiwi-triplestore/src/test/java/org/apache/marmotta/kiwi/test/PersistenceTest.java
index 3aa3842..22b9736 100644
--- a/libraries/kiwi/kiwi-triplestore/src/test/java/org/apache/marmotta/kiwi/test/PersistenceTest.java
+++ b/libraries/kiwi/kiwi-triplestore/src/test/java/org/apache/marmotta/kiwi/test/PersistenceTest.java
@@ -52,7 +52,6 @@ import static org.hamcrest.Matchers.hasItems;
 @RunWith(KiWiDatabaseRunner.class)
 public class PersistenceTest {
 
-
     private KiWiPersistence persistence;
 
     private final KiWiConfiguration kiwiConfig;
@@ -61,7 +60,6 @@ public class PersistenceTest {
         this.kiwiConfig = kiwiConfig;
     }
 
-
     @Before
     public void initDatabase() throws SQLException {
         persistence = new KiWiPersistence(kiwiConfig);
@@ -75,20 +73,18 @@ public class PersistenceTest {
         persistence.shutdown();
     }
 
-
     @Test
     public void testCreateDropDatabase() throws SQLException {
         // test if database exists and has a version
-        KiWiConnection connection = persistence.getConnection();
+        final KiWiConnection connection = persistence.getConnection();
         try {
-            Assert.assertThat(connection.getDatabaseTables(),hasItems("nodes","triples","namespaces"));
+            Assert.assertThat(connection.getDatabaseTables(), hasItems("nodes", "triples", "namespaces"));
             Assert.assertEquals(KiWiDialect.VERSION, connection.getDatabaseVersion());
 
             connection.commit();
         } finally {
             connection.close();
         }
-
     }
 
     /**
@@ -121,19 +117,16 @@ public class PersistenceTest {
             Assert.assertEquals(uri,testUri2);
             Assert.assertEquals(uri.getId(), testUri2.getId());
 
-
             KiWiNode testUri3 = connection.loadUriResource(uri.stringValue());
 
             // needs to be equal, and should also be the identical object!
             Assert.assertEquals(uri,testUri3);
             Assert.assertEquals(uri.getId(), testUri3.getId());
 
-
             connection.commit();
 
             Assert.assertEquals(1,Iterations.asList(connection.listResources()).size());
 
-
             // clear cache and test again
             persistence.clearCache();
             KiWiNode testUri4 = connection.loadNodeById(uri.getId());
@@ -167,7 +160,6 @@ public class PersistenceTest {
 
     }
 
-
     /**
      * Test storing and loading blank nodes.
      *
@@ -198,14 +190,12 @@ public class PersistenceTest {
             Assert.assertEquals(bnode,testBNode2);
             Assert.assertEquals(bnode.getId(), testBNode2.getId());
 
-
             KiWiNode testBNode3 = connection.loadAnonResource(bnode.stringValue());
 
             // needs to be equal, and should also be the identical object!
             Assert.assertEquals(bnode,testBNode3);
             Assert.assertEquals(bnode.getId(), testBNode3.getId());
 
-
             connection.commit();
 
             Assert.assertEquals(1,Iterations.asList(connection.listResources()).size());
@@ -240,7 +230,6 @@ public class PersistenceTest {
         } finally {
             connection.close();
         }
-
     }
 
 
@@ -285,7 +274,6 @@ public class PersistenceTest {
 
             connection.commit();
 
-
             // clear cache and test again
             persistence.clearCache();
             KiWiNode testLiteral4 = connection.loadNodeById(literal.getId());
@@ -319,7 +307,6 @@ public class PersistenceTest {
         } finally {
             connection.close();
         }
-
     }
 
 
@@ -364,7 +351,6 @@ public class PersistenceTest {
 
             connection.commit();
 
-
             // clear cache and test again
             persistence.clearCache();
             KiWiNode testLiteral4 = connection.loadNodeById(literal.getId());
@@ -398,7 +384,6 @@ public class PersistenceTest {
         } finally {
             connection.close();
         }
-
     }
 
 
@@ -445,7 +430,6 @@ public class PersistenceTest {
 
             connection.commit();
 
-
             // clear cache and test again
             persistence.clearCache();
             KiWiNode testLiteral4 = connection.loadNodeById(literal.getId());
@@ -480,7 +464,6 @@ public class PersistenceTest {
         } finally {
             connection.close();
         }
-
     }
 
 
@@ -527,7 +510,6 @@ public class PersistenceTest {
 
             connection.commit();
 
-
             // clear cache and test again
             persistence.clearCache();
             KiWiNode testLiteral4 = connection.loadNodeById(literal.getId());
@@ -562,7 +544,6 @@ public class PersistenceTest {
         } finally {
             connection.close();
         }
-
     }
 
 
@@ -578,11 +559,10 @@ public class PersistenceTest {
         try {
             KiWiUriResource uri = new KiWiUriResource(Namespaces.NS_XSD + "integer");
 
-
             Random rnd = new Random();
             long value = rnd.nextLong();
 
-                    // add a new URI to the triple store and check if it exists afterwards, before and after commit
+            // add a new URI to the triple store and check if it exists afterwards, before and after commit
             KiWiIntLiteral literal = new KiWiIntLiteral(value, uri);
             connection.storeNode(literal);
 
@@ -612,7 +592,6 @@ public class PersistenceTest {
             Assert.assertEquals(uri,((KiWiLiteral)testLiteral3).getType());
             //Assert.assertTrue(literal == testLiteral3);
 
-
             // load by integer value
             KiWiNode testLiteral6 = connection.loadLiteral(value);
 
@@ -621,10 +600,8 @@ public class PersistenceTest {
             Assert.assertEquals(uri,((KiWiLiteral)testLiteral6).getType());
             //Assert.assertTrue(literal == testLiteral6);
 
-
             connection.commit();
 
-
             // clear cache and test again
             persistence.clearCache();
             KiWiNode testLiteral4 = connection.loadNodeById(literal.getId());
@@ -641,7 +618,6 @@ public class PersistenceTest {
             Assert.assertEquals(uri,((KiWiLiteral)testLiteral5).getType());
             //Assert.assertTrue(literal != testLiteral5);
 
-
             // load by integer value
             KiWiNode testLiteral7 = connection.loadLiteral(value);
 
@@ -669,7 +645,6 @@ public class PersistenceTest {
         } finally {
             connection.close();
         }
-
     }
 
     /**
@@ -683,7 +658,6 @@ public class PersistenceTest {
         try {
             KiWiUriResource uri = new KiWiUriResource(Namespaces.NS_XSD + "double");
 
-
             Random rnd = new Random();
             double value = rnd.nextDouble();
 
@@ -717,7 +691,6 @@ public class PersistenceTest {
             Assert.assertEquals(uri,((KiWiLiteral)testLiteral3).getType());
             //Assert.assertTrue(literal == testLiteral3);
 
-
             // load by integer value
             KiWiNode testLiteral6 = connection.loadLiteral(value);
 
@@ -726,10 +699,8 @@ public class PersistenceTest {
             Assert.assertEquals(uri,((KiWiLiteral)testLiteral6).getType());
             //Assert.assertTrue(literal == testLiteral6);
 
-
             connection.commit();
 
-
             // clear cache and test again
             persistence.clearCache();
             KiWiNode testLiteral4 = connection.loadNodeById(literal.getId());
@@ -746,7 +717,6 @@ public class PersistenceTest {
             Assert.assertEquals(uri,((KiWiLiteral)testLiteral5).getType());
             //Assert.assertTrue(literal != testLiteral5);
 
-
             // load by integer value
             KiWiNode testLiteral7 = connection.loadLiteral(value);
 
@@ -774,7 +744,6 @@ public class PersistenceTest {
         } finally {
             connection.close();
         }
-
     }
 
     /**
@@ -821,7 +790,6 @@ public class PersistenceTest {
             Assert.assertEquals(uri,((KiWiLiteral)testLiteral3).getType());
             //Assert.assertTrue(literal == testLiteral3);
 
-
             // load by integer value
             KiWiNode testLiteral6 = connection.loadLiteral(value);
 
@@ -830,10 +798,8 @@ public class PersistenceTest {
             Assert.assertEquals(uri,((KiWiLiteral)testLiteral6).getType());
             //Assert.assertTrue(literal == testLiteral6);
 
-
             connection.commit();
 
-
             // clear cache and test again
             persistence.clearCache();
             KiWiNode testLiteral4 = connection.loadNodeById(literal.getId());
@@ -850,7 +816,6 @@ public class PersistenceTest {
             Assert.assertEquals(uri,((KiWiLiteral)testLiteral5).getType());
             //Assert.assertTrue(literal != testLiteral5);
 
-
             // load by integer value
             KiWiNode testLiteral7 = connection.loadLiteral(value);
 
@@ -878,7 +843,6 @@ public class PersistenceTest {
         } finally {
             connection.close();
         }
-
     }
 
     /**
@@ -892,7 +856,6 @@ public class PersistenceTest {
         try {
             KiWiUriResource uri = new KiWiUriResource(Namespaces.NS_XSD + "dateTime");
 
-
             DateTime value = DateTime.now().withMillisOfSecond(0);
             // add a new URI to the triple store and check if it exists afterwards, before and after commit
             KiWiDateLiteral literal = new KiWiDateLiteral(value, uri);
@@ -924,7 +887,6 @@ public class PersistenceTest {
             Assert.assertEquals(uri,((KiWiLiteral)testLiteral3).getType());
             //Assert.assertTrue(literal == testLiteral3);
 
-
             // load by integer value
             KiWiNode testLiteral6 = connection.loadLiteral(value);
 
@@ -933,10 +895,8 @@ public class PersistenceTest {
             Assert.assertEquals(uri,((KiWiLiteral)testLiteral6).getType());
             //Assert.assertTrue(literal == testLiteral6);
 
-
             connection.commit();
 
-
             // clear cache and test again
             persistence.clearCache();
             KiWiNode testLiteral4 = connection.loadNodeById(literal.getId());
@@ -953,7 +913,6 @@ public class PersistenceTest {
             Assert.assertEquals(uri,((KiWiLiteral)testLiteral5).getType());
             //Assert.assertTrue(literal != testLiteral5);
 
-
             // load by integer value
             KiWiNode testLiteral7 = connection.loadLiteral(value);
 
@@ -981,11 +940,8 @@ public class PersistenceTest {
         } finally {
             connection.close();
         }
-
     }
 
-
-
     /**
      * Test storing, querying and deleting triples
      */
@@ -1037,9 +993,8 @@ public class PersistenceTest {
                 // clear cache and test again
                 persistence.clearCache();
 
-                List<Statement> result3 = Iterations.asList(connection.listTriples(subject,null,null,null,false, true));
-                Assert.assertThat(result3,hasItems((Statement)triple1,(Statement)triple2));
-
+                List<Statement> result3 = Iterations.asList(connection.listTriples(subject, null, null, null, false, true));
+                Assert.assertThat(result3,hasItems((Statement)triple1, triple2));
 
                 Assert.assertEquals(2, connection.getSize());
                 Assert.assertEquals(2, connection.getSize(context));
@@ -1050,16 +1005,16 @@ public class PersistenceTest {
                 ResultSet dbResult1 = stmt.executeQuery();
 
                 Assert.assertTrue(dbResult1.next());
-                Assert.assertEquals((long) triple1.getId(), dbResult1.getLong("id"));
-                Assert.assertEquals((long) triple1.getSubject().getId(), dbResult1.getLong("subject"));
-                Assert.assertEquals((long) triple1.getPredicate().getId(), dbResult1.getLong("predicate"));
-                Assert.assertEquals((long)triple1.getObject().getId(),dbResult1.getLong("object"));
+                Assert.assertEquals(triple1.getId(), dbResult1.getLong("id"));
+                Assert.assertEquals( triple1.getSubject().getId(), dbResult1.getLong("subject"));
+                Assert.assertEquals(triple1.getPredicate().getId(), dbResult1.getLong("predicate"));
+                Assert.assertEquals(triple1.getObject().getId(),dbResult1.getLong("object"));
 
                 Assert.assertTrue(dbResult1.next());
-                Assert.assertEquals((long)triple2.getId(),dbResult1.getLong("id"));
-                Assert.assertEquals((long)triple2.getSubject().getId(),dbResult1.getLong("subject"));
-                Assert.assertEquals((long)triple2.getPredicate().getId(),dbResult1.getLong("predicate"));
-                Assert.assertEquals((long)triple2.getObject().getId(),dbResult1.getLong("object"));
+                Assert.assertEquals(triple2.getId(),dbResult1.getLong("id"));
+                Assert.assertEquals(triple2.getSubject().getId(),dbResult1.getLong("subject"));
+                Assert.assertEquals(triple2.getPredicate().getId(),dbResult1.getLong("predicate"));
+                Assert.assertEquals(triple2.getObject().getId(),dbResult1.getLong("object"));
 
                 dbResult1.close();
 
@@ -1067,7 +1022,6 @@ public class PersistenceTest {
             } finally {
                 connection.close();
             }
-
     }
 
     // TODO: test namespaces
@@ -1122,4 +1076,5 @@ public class PersistenceTest {
             connection.close();
         }
     }
+
 }


[11/50] [abbrv] marmotta git commit: more testing

Posted by wi...@apache.org.
more testing


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/622a3009
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/622a3009
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/622a3009

Branch: refs/heads/MARMOTTA-584
Commit: 622a30099d3ed004de3d1869fe42f867d5bf81b7
Parents: 299272a
Author: Sebastian Schaffert <ss...@apache.org>
Authored: Sat Dec 19 16:53:28 2015 +0100
Committer: Sebastian Schaffert <ss...@apache.org>
Committed: Sat Dec 19 16:53:28 2015 +0100

----------------------------------------------------------------------
 .../ostrich/backend/test/PersistenceTest.cc     | 53 +++++++++++++++++++-
 1 file changed, 52 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/622a3009/libraries/ostrich/backend/test/PersistenceTest.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/test/PersistenceTest.cc b/libraries/ostrich/backend/test/PersistenceTest.cc
index 9878cd6..fdfc604 100644
--- a/libraries/ostrich/backend/test/PersistenceTest.cc
+++ b/libraries/ostrich/backend/test/PersistenceTest.cc
@@ -16,6 +16,8 @@
 
 using namespace boost::filesystem;
 
+using testing::Contains;
+
 namespace marmotta {
 namespace rdf {
 namespace proto {
@@ -42,7 +44,7 @@ class PersistenceTest : public ::testing::Test {
     }
 
     ~PersistenceTest() {
-        LOG(INFO) << "Destroying Test DB";
+        LOG(INFO) << "Destroying Test DB: " << testdir.string();
         delete db;
         remove_all(testdir);
     }
@@ -71,6 +73,55 @@ TEST_F(PersistenceTest, TestAddStatements) {
     }
 }
 
+
+TEST_F(PersistenceTest, TestGetStatements) {
+    std::vector<rdf::proto::Statement> stmts = {
+            rdf::Statement(rdf::URI("http://example.com/s1"), rdf::URI("http://example.com/p1"),
+                           rdf::URI("http://example.com/o1")).getMessage(),
+            rdf::Statement(rdf::URI("http://example.com/s2"), rdf::URI("http://example.com/p1"),
+                           rdf::URI("http://example.com/o1")).getMessage(),
+            rdf::Statement(rdf::URI("http://example.com/s1"), rdf::URI("http://example.com/p2"),
+                           rdf::URI("http://example.com/o2")).getMessage(),
+            rdf::Statement(rdf::URI("http://example.com/s2"), rdf::URI("http://example.com/p2"),
+                           rdf::URI("http://example.com/o2")).getMessage(),
+            rdf::Statement(rdf::URI("http://example.com/s1"), rdf::URI("http://example.com/p3"),
+                           rdf::URI("http://example.com/o3")).getMessage(),
+    };
+
+    util::CollectionIterator<rdf::proto::Statement> it(stmts);
+    db->AddStatements(it);
+
+    EXPECT_EQ(5, db->Size());
+
+    rdf::Statement pattern1;
+    pattern1.setSubject(rdf::URI("http://example.com/s1"));
+    auto it1 = db->GetStatements(pattern1.getMessage());
+    for (int i=0; i<3; i++) {
+        ASSERT_TRUE(it1->hasNext());
+        EXPECT_THAT(stmts, Contains(it1->next()));
+    }
+    EXPECT_FALSE(it1->hasNext());
+
+    rdf::Statement pattern2;
+    pattern2.setObject(rdf::URI("http://example.com/o1"));
+    auto it2 = db->GetStatements(pattern2.getMessage());
+    for (int i=0; i<2; i++) {
+        ASSERT_TRUE(it2->hasNext());
+        EXPECT_THAT(stmts, Contains(it2->next()));
+    }
+    EXPECT_FALSE(it2->hasNext());
+
+    rdf::Statement pattern3;
+    pattern2.setPredicate(rdf::URI("http://example.com/p1"));
+    auto it3 = db->GetStatements(pattern2.getMessage());
+    for (int i=0; i<2; i++) {
+        ASSERT_TRUE(it3->hasNext());
+        EXPECT_THAT(stmts, Contains(it3->next()));
+    }
+    EXPECT_FALSE(it3->hasNext());
+}
+
+
 }
 }
 }


[30/50] [abbrv] marmotta git commit: [MARMOTTA-621] implement Java client side support for direct ASK and CONSTRUCT queries

Posted by wi...@apache.org.
[MARMOTTA-621] implement Java client side support for direct ASK and CONSTRUCT queries


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/4ab20b3d
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/4ab20b3d
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/4ab20b3d

Branch: refs/heads/MARMOTTA-584
Commit: 4ab20b3d874ff1062d4ddb5fb52790d7fe7348a8
Parents: 4a5e588
Author: Sebastian Schaffert <ss...@apache.org>
Authored: Sat Feb 13 16:14:03 2016 +0100
Committer: Sebastian Schaffert <ss...@apache.org>
Committed: Sat Feb 13 16:14:03 2016 +0100

----------------------------------------------------------------------
 .../ostrich/sail/OstrichSailConnection.java     | 97 ++++++++++++++++++--
 .../backend/ostrich/OstrichSailRepository.java  | 72 +++++++++++++--
 2 files changed, 153 insertions(+), 16 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/4ab20b3d/libraries/ostrich/client/src/main/java/org/apache/marmotta/ostrich/sail/OstrichSailConnection.java
----------------------------------------------------------------------
diff --git a/libraries/ostrich/client/src/main/java/org/apache/marmotta/ostrich/sail/OstrichSailConnection.java b/libraries/ostrich/client/src/main/java/org/apache/marmotta/ostrich/sail/OstrichSailConnection.java
index e85fdd2..b8f6b27 100644
--- a/libraries/ostrich/client/src/main/java/org/apache/marmotta/ostrich/sail/OstrichSailConnection.java
+++ b/libraries/ostrich/client/src/main/java/org/apache/marmotta/ostrich/sail/OstrichSailConnection.java
@@ -24,6 +24,7 @@ import info.aduna.iteration.*;
 import io.grpc.ManagedChannel;
 import io.grpc.ManagedChannelBuilder;
 import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
 import io.grpc.stub.StreamObserver;
 import org.apache.marmotta.ostrich.client.proto.Sail;
 import org.apache.marmotta.ostrich.client.proto.SailServiceGrpc;
@@ -67,7 +68,8 @@ public class OstrichSailConnection extends NotifyingSailConnectionBase {
     private static Logger log = LoggerFactory.getLogger(OstrichSailConnection.class);
 
     private final ManagedChannel channel;
-    private final SailServiceGrpc.SailServiceBlockingStub stub;
+    private final SailServiceGrpc.SailServiceBlockingStub blockingSailStub;
+    private final SparqlServiceGrpc.SparqlServiceBlockingStub blockingSparqlStub;
     private final SailServiceGrpc.SailServiceStub sailServiceStub;
     private final SparqlServiceGrpc.SparqlServiceStub sparqlServiceStub;
 
@@ -80,9 +82,10 @@ public class OstrichSailConnection extends NotifyingSailConnectionBase {
         channel = ManagedChannelBuilder.forAddress(host, port)
                 .usePlaintext(true)
                 .build();
-        stub = SailServiceGrpc.newBlockingStub(channel);
+        blockingSailStub = SailServiceGrpc.newBlockingStub(channel);
         sailServiceStub = SailServiceGrpc.newStub(channel);
         sparqlServiceStub = SparqlServiceGrpc.newStub(channel);
+        blockingSparqlStub = SparqlServiceGrpc.newBlockingStub(channel);
 
         updateResponseObserver = new StreamObserver<Sail.UpdateResponse>() {
             @Override
@@ -177,11 +180,21 @@ public class OstrichSailConnection extends NotifyingSailConnectionBase {
      * @return
      * @throws SailException
      */
-    public CloseableIteration<? extends BindingSet, QueryEvaluationException> directTupleQuery(String query) throws SailException {
+    public CloseableIteration<? extends BindingSet, QueryEvaluationException> directTupleQuery(String query, String baseUri) throws SailException {
         log.info("Committing transaction before querying ...");
         commitForQuery();
 
-        Sparql.SparqlRequest request = Sparql.SparqlRequest.newBuilder().setQuery(query).build();
+        Sparql.SparqlRequest request;
+        if (baseUri != null) {
+            request = Sparql.SparqlRequest.newBuilder()
+                    .setQuery(query)
+                    .setBaseUri(new ProtoURI(baseUri).getMessage())
+                    .build();
+        } else {
+            request = Sparql.SparqlRequest.newBuilder()
+                    .setQuery(query)
+                    .build();
+        }
 
         return new ExceptionConvertingIteration<BindingSet, QueryEvaluationException>(
                 new ConvertingIteration<Sparql.SparqlResponse, BindingSet, SailException>(
@@ -226,12 +239,80 @@ public class OstrichSailConnection extends NotifyingSailConnectionBase {
         };
     }
 
+    /**
+     * Send a SPARQL query to a backend supporting direct SPARQL evaluation.
+     *
+     * @param query
+     * @return
+     * @throws SailException
+     */
+    public CloseableIteration<? extends Statement, QueryEvaluationException> directGraphQuery(String query, String baseUri) throws SailException {
+        log.info("Committing transaction before querying ...");
+        commitForQuery();
+
+        Sparql.SparqlRequest request;
+        if (baseUri != null) {
+            request = Sparql.SparqlRequest.newBuilder()
+                    .setQuery(query)
+                    .setBaseUri(new ProtoURI(baseUri).getMessage())
+                    .build();
+        } else {
+            request = Sparql.SparqlRequest.newBuilder()
+                    .setQuery(query)
+                    .build();
+        }
+
+        return new ExceptionConvertingIteration<Statement, QueryEvaluationException>(
+                new ConvertingIteration<Model.Statement, Statement, SailException>(
+                        new ClosableResponseStream<>(sparqlServiceStub, SparqlServiceGrpc.METHOD_GRAPH_QUERY, request)) {
+                    @Override
+                    protected Statement convert(Model.Statement sourceObject) throws SailException {
+                        return new ProtoStatement(sourceObject);
+                    }
+                }) {
+            @Override
+            protected QueryEvaluationException convert(Exception e) {
+                return new QueryEvaluationException(e);
+            }
+        };
+    }
+
+    /**
+     * Send a SPARQL query to a backend supporting direct SPARQL evaluation.
+     *
+     * @param query
+     * @return
+     * @throws SailException
+     */
+    public boolean directBooleanQuery(String query, String baseUri) throws SailException {
+        log.info("Committing transaction before querying ...");
+        commitForQuery();
+
+        Sparql.SparqlRequest request;
+        if (baseUri != null) {
+            request = Sparql.SparqlRequest.newBuilder()
+                    .setQuery(query)
+                    .setBaseUri(new ProtoURI(baseUri).getMessage())
+                    .build();
+        } else {
+            request = Sparql.SparqlRequest.newBuilder()
+                    .setQuery(query)
+                    .build();
+        }
+
+        try {
+            return blockingSparqlStub.askQuery(request).getValue();
+        } catch (StatusRuntimeException ex) {
+            throw new SailException(ex.getMessage());
+        }
+    }
+
     @Override
     protected CloseableIteration<? extends Resource, SailException> getContextIDsInternal() throws SailException {
         log.info("Committing transaction before querying ...");
         commitForQuery();
 
-        return wrapResourceIterator(stub.getContexts(Empty.getDefaultInstance()));
+        return wrapResourceIterator(blockingSailStub.getContexts(Empty.getDefaultInstance()));
     }
 
     @Override
@@ -272,7 +353,7 @@ public class OstrichSailConnection extends NotifyingSailConnectionBase {
             }
         }
 
-        Int64Value v = stub.size(builder.build());
+        Int64Value v = blockingSailStub.size(builder.build());
         return v.getValue();
     }
 
@@ -361,7 +442,7 @@ public class OstrichSailConnection extends NotifyingSailConnectionBase {
         commitForQuery();
 
         Empty pattern = Empty.getDefaultInstance();
-        return wrapNamespaceIterator(stub.getNamespaces(pattern));
+        return wrapNamespaceIterator(blockingSailStub.getNamespaces(pattern));
     }
 
     @Override
@@ -371,7 +452,7 @@ public class OstrichSailConnection extends NotifyingSailConnectionBase {
 
         Model.Namespace pattern = Model.Namespace.newBuilder().setPrefix(prefix).build();
         try {
-            return stub.getNamespace(pattern).getUri();
+            return blockingSailStub.getNamespace(pattern).getUri();
         } catch (io.grpc.StatusRuntimeException ex) {
             if (ex.getStatus().getCode() == Status.Code.NOT_FOUND) {
                 return null;

http://git-wip-us.apache.org/repos/asf/marmotta/blob/4ab20b3d/platform/backends/marmotta-backend-ostrich/src/main/java/org/apache/marmotta/platform/backend/ostrich/OstrichSailRepository.java
----------------------------------------------------------------------
diff --git a/platform/backends/marmotta-backend-ostrich/src/main/java/org/apache/marmotta/platform/backend/ostrich/OstrichSailRepository.java b/platform/backends/marmotta-backend-ostrich/src/main/java/org/apache/marmotta/platform/backend/ostrich/OstrichSailRepository.java
index 0dbf1e8..684ae5b 100644
--- a/platform/backends/marmotta-backend-ostrich/src/main/java/org/apache/marmotta/platform/backend/ostrich/OstrichSailRepository.java
+++ b/platform/backends/marmotta-backend-ostrich/src/main/java/org/apache/marmotta/platform/backend/ostrich/OstrichSailRepository.java
@@ -19,16 +19,13 @@ package org.apache.marmotta.platform.backend.ostrich;
 
 import info.aduna.iteration.CloseableIteration;
 import org.apache.marmotta.ostrich.sail.OstrichSailConnection;
+import org.openrdf.model.Statement;
 import org.openrdf.query.*;
+import org.openrdf.query.impl.GraphQueryResultImpl;
 import org.openrdf.query.impl.TupleQueryResultImpl;
-import org.openrdf.query.parser.ParsedQuery;
-import org.openrdf.query.parser.ParsedTupleQuery;
-import org.openrdf.query.parser.QueryParserUtil;
+import org.openrdf.query.parser.*;
 import org.openrdf.repository.RepositoryException;
-import org.openrdf.repository.sail.SailQuery;
-import org.openrdf.repository.sail.SailRepository;
-import org.openrdf.repository.sail.SailRepositoryConnection;
-import org.openrdf.repository.sail.SailTupleQuery;
+import org.openrdf.repository.sail.*;
 import org.openrdf.sail.Sail;
 import org.openrdf.sail.SailConnection;
 import org.openrdf.sail.SailException;
@@ -37,6 +34,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import java.util.ArrayList;
+import java.util.HashMap;
 
 /**
  * A wrapper SailRepository for Ostrich allowing access to direct SPARQL support.
@@ -69,7 +67,7 @@ public class OstrichSailRepository extends SailRepository {
                                     // Let Sesame still parse the query for better error messages and for the binding names.
                                     ParsedTupleQuery parsedQuery = QueryParserUtil.parseTupleQuery(ql, queryString, baseURI);
                                     OstrichSailConnection sailCon = findConnection(getConnection().getSailConnection());
-                                    bindingsIter = sailCon.directTupleQuery(queryString);
+                                    bindingsIter = sailCon.directTupleQuery(queryString, baseURI);
                                     bindingsIter = enforceMaxQueryTime(bindingsIter);
 
                                     return new TupleQueryResultImpl(new ArrayList<String>(parsedQuery.getTupleExpr().getBindingNames()), bindingsIter);
@@ -86,11 +84,69 @@ public class OstrichSailRepository extends SailRepository {
                 }
 
                 @Override
+                public SailBooleanQuery prepareBooleanQuery(final QueryLanguage ql, final String queryString, final String baseURI) throws MalformedQueryException {
+                    if (ql == QueryLanguage.SPARQL) {
+                        return new SailBooleanQuery(null, this) {
+                            @Override
+                            public boolean evaluate() throws QueryEvaluationException {
+                                try {
+                                    log.info("Running native SPARQL query: {}", queryString);
+                                    CloseableIteration<? extends BindingSet, QueryEvaluationException> bindingsIter;
+
+                                    // Let Sesame still parse the query for better error messages and for the binding names.
+                                    ParsedBooleanQuery parsedQuery = QueryParserUtil.parseBooleanQuery(ql, queryString, baseURI);
+                                    OstrichSailConnection sailCon = findConnection(getConnection().getSailConnection());
+                                    return sailCon.directBooleanQuery(queryString, baseURI);
+                                } catch (SailException e) {
+                                    throw new QueryEvaluationException(e.getMessage(), e);
+                                } catch (MalformedQueryException e) {
+                                    throw new QueryEvaluationException(e.getMessage(), e);
+                                }
+                            }
+                        };
+                    } else {
+                        return super.prepareBooleanQuery(ql, queryString, baseURI);
+                    }
+                }
+
+                @Override
+                public SailGraphQuery prepareGraphQuery(final QueryLanguage ql, final String queryString, final String baseURI) throws MalformedQueryException {
+                    if (ql == QueryLanguage.SPARQL) {
+                        return new SailGraphQuery(null, this) {
+                            @Override
+                            public GraphQueryResult evaluate() throws QueryEvaluationException {
+                                try {
+                                    log.info("Running native SPARQL query: {}", queryString);
+                                    CloseableIteration<? extends Statement, ? extends QueryEvaluationException> bindingsIter;
+
+                                    // Let Sesame still parse the query for better error messages and for the binding names.
+                                    ParsedGraphQuery parsedQuery = QueryParserUtil.parseGraphQuery(ql, queryString, baseURI);
+                                    OstrichSailConnection sailCon = findConnection(getConnection().getSailConnection());
+                                    bindingsIter = sailCon.directGraphQuery(queryString, baseURI);
+
+                                    return new GraphQueryResultImpl(new HashMap<String, String>(), bindingsIter);
+                                } catch (SailException e) {
+                                    throw new QueryEvaluationException(e.getMessage(), e);
+                                } catch (MalformedQueryException e) {
+                                    throw new QueryEvaluationException(e.getMessage(), e);
+                                }
+                            }
+                        };
+                    } else {
+                        return super.prepareGraphQuery(ql, queryString, baseURI);
+                    }
+                }
+
+                @Override
                 public SailQuery prepareQuery(QueryLanguage ql, String queryString, String baseURI) throws MalformedQueryException {
                     ParsedQuery parsedQuery = QueryParserUtil.parseQuery(ql, queryString, baseURI);
 
                     if (parsedQuery instanceof ParsedTupleQuery) {
                         return prepareTupleQuery(ql, queryString, baseURI);
+                    } else if (parsedQuery instanceof ParsedBooleanQuery) {
+                        return prepareBooleanQuery(ql, queryString, baseURI);
+                    } else if (parsedQuery instanceof ParsedGraphQuery) {
+                        return prepareGraphQuery(ql, queryString, baseURI);
                     } else {
                         return super.prepareQuery(ql, queryString, baseURI);
                     }


[16/50] [abbrv] marmotta git commit: backport implementation of std::make_unique from C++14 and use it

Posted by wi...@apache.org.
backport implementation of std::make_unique from C++14 and use it


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/4eb074dc
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/4eb074dc
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/4eb074dc

Branch: refs/heads/MARMOTTA-584
Commit: 4eb074dcb9936259ce111f991760ada8fd741d75
Parents: 767ef4a
Author: Sebastian Schaffert <ss...@apache.org>
Authored: Sun Dec 20 11:33:32 2015 +0100
Committer: Sebastian Schaffert <ss...@apache.org>
Committed: Sun Dec 20 11:33:32 2015 +0100

----------------------------------------------------------------------
 .../backend/persistence/leveldb_persistence.cc  | 25 +++++++++-----------
 .../backend/persistence/leveldb_service.cc      |  5 ++--
 libraries/ostrich/backend/util/CMakeLists.txt   |  2 +-
 libraries/ostrich/backend/util/iterator.h       |  2 +-
 libraries/ostrich/backend/util/unique.h         | 23 ++++++++++++++++++
 5 files changed, 38 insertions(+), 19 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/4eb074dc/libraries/ostrich/backend/persistence/leveldb_persistence.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/persistence/leveldb_persistence.cc b/libraries/ostrich/backend/persistence/leveldb_persistence.cc
index 852f152..365397e 100644
--- a/libraries/ostrich/backend/persistence/leveldb_persistence.cc
+++ b/libraries/ostrich/backend/persistence/leveldb_persistence.cc
@@ -28,6 +28,7 @@
 #include "leveldb_persistence.h"
 #include "model/rdf_operators.h"
 #include "util/murmur3.h"
+#include "util/unique.h"
 
 #define CHECK_STATUS(s) CHECK(s.ok()) << "Writing to database failed: " << s.ToString()
 
@@ -387,16 +388,14 @@ std::unique_ptr<LevelDBPersistence::NamespaceIterator> LevelDBPersistence::GetNa
         leveldb::Status s = db->Get(leveldb::ReadOptions(), key, &value);
         if (s.ok()) {
             ns.ParseFromString(value);
-            return std::unique_ptr<NamespaceIterator>(
-                    new util::SingletonIterator<Namespace>(ns));
+            return util::make_unique<util::SingletonIterator<Namespace>>(std::move(ns));
         } else {
-            return std::unique_ptr<NamespaceIterator>(
-                    new util::EmptyIterator<Namespace>());
+            return util::make_unique<util::EmptyIterator<Namespace>>();
         }
     } else {
         // Pattern was empty, iterate over all namespaces and report them.
-        return std::unique_ptr<NamespaceIterator>(
-            new LevelDBIterator<Namespace>(db_ns_prefix->NewIterator(leveldb::ReadOptions())));
+        return util::make_unique<LevelDBIterator<Namespace>>(
+                db_ns_prefix->NewIterator(leveldb::ReadOptions()));
     }
 }
 
@@ -481,16 +480,14 @@ std::unique_ptr<LevelDBPersistence::StatementIterator> LevelDBPersistence::GetSt
 
     if (query.NeedsFilter()) {
         DLOG(INFO) << "Retrieving statements with filter.";
-        return std::unique_ptr<StatementIterator>(
-                new util::FilteringIterator<Statement>(
-                        new StatementRangeIterator(
-                                db->NewIterator(leveldb::ReadOptions()), query.MinKey(), query.MaxKey()),
-                        [&pattern](const Statement& stmt) -> bool { return Matches(pattern, stmt); }));
+        return util::make_unique<util::FilteringIterator<Statement>>(
+                new StatementRangeIterator(
+                        db->NewIterator(leveldb::ReadOptions()), query.MinKey(), query.MaxKey()),
+                [&pattern](const Statement& stmt) -> bool { return Matches(pattern, stmt); });
     } else {
         DLOG(INFO) << "Retrieving statements without filter.";
-        return std::unique_ptr<StatementIterator>(
-                new StatementRangeIterator(
-                        db->NewIterator(leveldb::ReadOptions()), query.MinKey(), query.MaxKey()));
+        return util::make_unique<StatementRangeIterator>(
+                db->NewIterator(leveldb::ReadOptions()), query.MinKey(), query.MaxKey());
     }
 }
 

http://git-wip-us.apache.org/repos/asf/marmotta/blob/4eb074dc/libraries/ostrich/backend/persistence/leveldb_service.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/persistence/leveldb_service.cc b/libraries/ostrich/backend/persistence/leveldb_service.cc
index 9ab9fd8..c11b002 100644
--- a/libraries/ostrich/backend/persistence/leveldb_service.cc
+++ b/libraries/ostrich/backend/persistence/leveldb_service.cc
@@ -21,6 +21,7 @@
 #include <unordered_set>
 #include <model/rdf_operators.h>
 #include <util/iterator.h>
+#include <util/unique.h>
 
 using grpc::Status;
 using grpc::StatusCode;
@@ -230,9 +231,7 @@ grpc::Status LevelDBSparqlService::TupleQuery(
         grpc::ServerContext* context, const spq::SparqlRequest* query,
         grpc::ServerWriter<spq::SparqlResponse>* result) {
 
-    SparqlService svc(
-        std::unique_ptr<TripleSource>(
-                new LevelDBTripleSource(persistence)));
+    SparqlService svc(util::make_unique<LevelDBTripleSource>(persistence));
 
     svc.TupleQuery(query->query(), [&result](const SparqlService::RowType& row) {
         spq::SparqlResponse response;

http://git-wip-us.apache.org/repos/asf/marmotta/blob/4eb074dc/libraries/ostrich/backend/util/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/util/CMakeLists.txt b/libraries/ostrich/backend/util/CMakeLists.txt
index f573c3c..ac87cd8 100644
--- a/libraries/ostrich/backend/util/CMakeLists.txt
+++ b/libraries/ostrich/backend/util/CMakeLists.txt
@@ -1,3 +1,3 @@
 include_directories(.. ${CMAKE_CURRENT_BINARY_DIR}/..)
 
-add_library(marmotta_util murmur3.cc murmur3.h split.cc split.h iterator.h)
\ No newline at end of file
+add_library(marmotta_util murmur3.cc murmur3.h split.cc split.h iterator.h unique.h)
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/marmotta/blob/4eb074dc/libraries/ostrich/backend/util/iterator.h
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/util/iterator.h b/libraries/ostrich/backend/util/iterator.h
index fd29cc4..0f08531 100644
--- a/libraries/ostrich/backend/util/iterator.h
+++ b/libraries/ostrich/backend/util/iterator.h
@@ -88,7 +88,7 @@ class EmptyIterator : public CloseableIterator<T> {
 template<typename T>
 class SingletonIterator : public CloseableIterator<T> {
  public:
-    SingletonIterator(T& value) : value(value), incremented(false) { }
+    SingletonIterator(T&& value) : value(value), incremented(false) { }
 
     const T &next() override {
         if (!incremented) {

http://git-wip-us.apache.org/repos/asf/marmotta/blob/4eb074dc/libraries/ostrich/backend/util/unique.h
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/util/unique.h b/libraries/ostrich/backend/util/unique.h
new file mode 100644
index 0000000..d212af2
--- /dev/null
+++ b/libraries/ostrich/backend/util/unique.h
@@ -0,0 +1,23 @@
+//
+// Created by wastl on 20.12.15.
+//
+
+#include <memory>
+
+#ifndef MARMOTTA_UNIQUE_H
+#define MARMOTTA_UNIQUE_H
+namespace marmotta {
+namespace util {
+
+/**
+ * Backport of C++14 make_unique implementation.
+ */
+template<typename T, typename ...Args>
+std::unique_ptr<T> make_unique( Args&& ...args )
+{
+    return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
+}
+
+}  // namespace util
+}  // namespace marmotta
+#endif //MARMOTTA_UNIQUE_H


[06/50] [abbrv] marmotta git commit: refactor iterator implementations, they were broken

Posted by wi...@apache.org.
http://git-wip-us.apache.org/repos/asf/marmotta/blob/2e32da5d/libraries/ostrich/backend/test/gmock/gmock.h
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/test/gmock/gmock.h b/libraries/ostrich/backend/test/gmock/gmock.h
new file mode 100644
index 0000000..cd54177
--- /dev/null
+++ b/libraries/ostrich/backend/test/gmock/gmock.h
@@ -0,0 +1,14978 @@
+// Copyright 2007, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+// Author: wan@google.com (Zhanyong Wan)
+
+// Google Mock - a framework for writing C++ mock classes.
+//
+// This is the main header file a user should include.
+
+#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_H_
+#define GMOCK_INCLUDE_GMOCK_GMOCK_H_
+
+// This file implements the following syntax:
+//
+//   ON_CALL(mock_object.Method(...))
+//     .With(...) ?
+//     .WillByDefault(...);
+//
+// where With() is optional and WillByDefault() must appear exactly
+// once.
+//
+//   EXPECT_CALL(mock_object.Method(...))
+//     .With(...) ?
+//     .Times(...) ?
+//     .InSequence(...) *
+//     .WillOnce(...) *
+//     .WillRepeatedly(...) ?
+//     .RetiresOnSaturation() ? ;
+//
+// where all clauses are optional and WillOnce() can be repeated.
+
+// Copyright 2007, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+// Author: wan@google.com (Zhanyong Wan)
+
+// Google Mock - a framework for writing C++ mock classes.
+//
+// This file implements some commonly used actions.
+
+#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
+#define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
+
+#ifndef _WIN32_WCE
+# include <errno.h>
+#endif
+
+#include <algorithm>
+#include <string>
+
+// Copyright 2007, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+// Author: wan@google.com (Zhanyong Wan)
+
+// Google Mock - a framework for writing C++ mock classes.
+//
+// This file defines some utilities useful for implementing Google
+// Mock.  They are subject to change without notice, so please DO NOT
+// USE THEM IN USER CODE.
+
+#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
+#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
+
+#include <stdio.h>
+#include <ostream>  // NOLINT
+#include <string>
+
+// This file was GENERATED by command:
+//     pump.py gmock-generated-internal-utils.h.pump
+// DO NOT EDIT BY HAND!!!
+
+// Copyright 2007, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+// Author: wan@google.com (Zhanyong Wan)
+
+// Google Mock - a framework for writing C++ mock classes.
+//
+// This file contains template meta-programming utility classes needed
+// for implementing Google Mock.
+
+#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
+#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
+
+// Copyright 2008, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+// Author: vadimb@google.com (Vadim Berman)
+//
+// Low-level types and utilities for porting Google Mock to various
+// platforms.  All macros ending with _ and symbols defined in an
+// internal namespace are subject to change without notice.  Code
+// outside Google Mock MUST NOT USE THEM DIRECTLY.  Macros that don't
+// end with _ are part of Google Mock's public API and can be used by
+// code outside Google Mock.
+
+#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
+#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
+
+#include <assert.h>
+#include <stdlib.h>
+#include <iostream>
+
+// Most of the utilities needed for porting Google Mock are also
+// required for Google Test and are defined in gtest-port.h.
+//
+// Note to maintainers: to reduce code duplication, prefer adding
+// portability utilities to Google Test's gtest-port.h instead of
+// here, as Google Mock depends on Google Test.  Only add a utility
+// here if it's truly specific to Google Mock.
+#include "gtest/gtest.h"
+// Copyright 2015, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+// Injection point for custom user configurations.
+// The following macros can be defined:
+//
+//   Flag related macros:
+//     GMOCK_DECLARE_bool_(name)
+//     GMOCK_DECLARE_int32_(name)
+//     GMOCK_DECLARE_string_(name)
+//     GMOCK_DEFINE_bool_(name, default_val, doc)
+//     GMOCK_DEFINE_int32_(name, default_val, doc)
+//     GMOCK_DEFINE_string_(name, default_val, doc)
+//
+// ** Custom implementation starts here **
+
+#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
+#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
+
+#endif  // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
+
+// To avoid conditional compilation everywhere, we make it
+// gmock-port.h's responsibility to #include the header implementing
+// tr1/tuple.  gmock-port.h does this via gtest-port.h, which is
+// guaranteed to pull in the tuple header.
+
+// For MS Visual C++, check the compiler version. At least VS 2003 is
+// required to compile Google Mock.
+#if defined(_MSC_VER) && _MSC_VER < 1310
+# error "At least Visual C++ 2003 (7.1) is required to compile Google Mock."
+#endif
+
+// Macro for referencing flags.  This is public as we want the user to
+// use this syntax to reference Google Mock flags.
+#define GMOCK_FLAG(name) FLAGS_gmock_##name
+
+#if !defined(GMOCK_DECLARE_bool_)
+
+// Macros for declaring flags.
+#define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name)
+#define GMOCK_DECLARE_int32_(name) \
+    extern GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name)
+#define GMOCK_DECLARE_string_(name) \
+    extern GTEST_API_ ::std::string GMOCK_FLAG(name)
+
+// Macros for defining flags.
+#define GMOCK_DEFINE_bool_(name, default_val, doc) \
+    GTEST_API_ bool GMOCK_FLAG(name) = (default_val)
+#define GMOCK_DEFINE_int32_(name, default_val, doc) \
+    GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name) = (default_val)
+#define GMOCK_DEFINE_string_(name, default_val, doc) \
+    GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val)
+
+#endif  // !defined(GMOCK_DECLARE_bool_)
+
+#endif  // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
+
+namespace testing {
+
+template <typename T>
+class Matcher;
+
+namespace internal {
+
+// An IgnoredValue object can be implicitly constructed from ANY value.
+// This is used in implementing the IgnoreResult(a) action.
+class IgnoredValue {
+ public:
+  // This constructor template allows any value to be implicitly
+  // converted to IgnoredValue.  The object has no data member and
+  // doesn't try to remember anything about the argument.  We
+  // deliberately omit the 'explicit' keyword in order to allow the
+  // conversion to be implicit.
+  template <typename T>
+  IgnoredValue(const T& /* ignored */) {}  // NOLINT(runtime/explicit)
+};
+
+// MatcherTuple<T>::type is a tuple type where each field is a Matcher
+// for the corresponding field in tuple type T.
+template <typename Tuple>
+struct MatcherTuple;
+
+template <>
+struct MatcherTuple< ::testing::tuple<> > {
+  typedef ::testing::tuple< > type;
+};
+
+template <typename A1>
+struct MatcherTuple< ::testing::tuple<A1> > {
+  typedef ::testing::tuple<Matcher<A1> > type;
+};
+
+template <typename A1, typename A2>
+struct MatcherTuple< ::testing::tuple<A1, A2> > {
+  typedef ::testing::tuple<Matcher<A1>, Matcher<A2> > type;
+};
+
+template <typename A1, typename A2, typename A3>
+struct MatcherTuple< ::testing::tuple<A1, A2, A3> > {
+  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3> > type;
+};
+
+template <typename A1, typename A2, typename A3, typename A4>
+struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4> > {
+  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>,
+      Matcher<A4> > type;
+};
+
+template <typename A1, typename A2, typename A3, typename A4, typename A5>
+struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5> > {
+  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
+      Matcher<A5> > type;
+};
+
+template <typename A1, typename A2, typename A3, typename A4, typename A5,
+    typename A6>
+struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6> > {
+  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
+      Matcher<A5>, Matcher<A6> > type;
+};
+
+template <typename A1, typename A2, typename A3, typename A4, typename A5,
+    typename A6, typename A7>
+struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7> > {
+  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
+      Matcher<A5>, Matcher<A6>, Matcher<A7> > type;
+};
+
+template <typename A1, typename A2, typename A3, typename A4, typename A5,
+    typename A6, typename A7, typename A8>
+struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8> > {
+  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
+      Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8> > type;
+};
+
+template <typename A1, typename A2, typename A3, typename A4, typename A5,
+    typename A6, typename A7, typename A8, typename A9>
+struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> > {
+  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
+      Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8>, Matcher<A9> > type;
+};
+
+template <typename A1, typename A2, typename A3, typename A4, typename A5,
+    typename A6, typename A7, typename A8, typename A9, typename A10>
+struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9,
+    A10> > {
+  typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
+      Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8>, Matcher<A9>,
+      Matcher<A10> > type;
+};
+
+// Template struct Function<F>, where F must be a function type, contains
+// the following typedefs:
+//
+//   Result:               the function's return type.
+//   ArgumentN:            the type of the N-th argument, where N starts with 1.
+//   ArgumentTuple:        the tuple type consisting of all parameters of F.
+//   ArgumentMatcherTuple: the tuple type consisting of Matchers for all
+//                         parameters of F.
+//   MakeResultVoid:       the function type obtained by substituting void
+//                         for the return type of F.
+//   MakeResultIgnoredValue:
+//                         the function type obtained by substituting Something
+//                         for the return type of F.
+template <typename F>
+struct Function;
+
+template <typename R>
+struct Function<R()> {
+  typedef R Result;
+  typedef ::testing::tuple<> ArgumentTuple;
+  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
+  typedef void MakeResultVoid();
+  typedef IgnoredValue MakeResultIgnoredValue();
+};
+
+template <typename R, typename A1>
+struct Function<R(A1)>
+    : Function<R()> {
+  typedef A1 Argument1;
+  typedef ::testing::tuple<A1> ArgumentTuple;
+  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
+  typedef void MakeResultVoid(A1);
+  typedef IgnoredValue MakeResultIgnoredValue(A1);
+};
+
+template <typename R, typename A1, typename A2>
+struct Function<R(A1, A2)>
+    : Function<R(A1)> {
+  typedef A2 Argument2;
+  typedef ::testing::tuple<A1, A2> ArgumentTuple;
+  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
+  typedef void MakeResultVoid(A1, A2);
+  typedef IgnoredValue MakeResultIgnoredValue(A1, A2);
+};
+
+template <typename R, typename A1, typename A2, typename A3>
+struct Function<R(A1, A2, A3)>
+    : Function<R(A1, A2)> {
+  typedef A3 Argument3;
+  typedef ::testing::tuple<A1, A2, A3> ArgumentTuple;
+  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
+  typedef void MakeResultVoid(A1, A2, A3);
+  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3);
+};
+
+template <typename R, typename A1, typename A2, typename A3, typename A4>
+struct Function<R(A1, A2, A3, A4)>
+    : Function<R(A1, A2, A3)> {
+  typedef A4 Argument4;
+  typedef ::testing::tuple<A1, A2, A3, A4> ArgumentTuple;
+  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
+  typedef void MakeResultVoid(A1, A2, A3, A4);
+  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4);
+};
+
+template <typename R, typename A1, typename A2, typename A3, typename A4,
+    typename A5>
+struct Function<R(A1, A2, A3, A4, A5)>
+    : Function<R(A1, A2, A3, A4)> {
+  typedef A5 Argument5;
+  typedef ::testing::tuple<A1, A2, A3, A4, A5> ArgumentTuple;
+  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
+  typedef void MakeResultVoid(A1, A2, A3, A4, A5);
+  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5);
+};
+
+template <typename R, typename A1, typename A2, typename A3, typename A4,
+    typename A5, typename A6>
+struct Function<R(A1, A2, A3, A4, A5, A6)>
+    : Function<R(A1, A2, A3, A4, A5)> {
+  typedef A6 Argument6;
+  typedef ::testing::tuple<A1, A2, A3, A4, A5, A6> ArgumentTuple;
+  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
+  typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6);
+  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6);
+};
+
+template <typename R, typename A1, typename A2, typename A3, typename A4,
+    typename A5, typename A6, typename A7>
+struct Function<R(A1, A2, A3, A4, A5, A6, A7)>
+    : Function<R(A1, A2, A3, A4, A5, A6)> {
+  typedef A7 Argument7;
+  typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7> ArgumentTuple;
+  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
+  typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7);
+  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7);
+};
+
+template <typename R, typename A1, typename A2, typename A3, typename A4,
+    typename A5, typename A6, typename A7, typename A8>
+struct Function<R(A1, A2, A3, A4, A5, A6, A7, A8)>
+    : Function<R(A1, A2, A3, A4, A5, A6, A7)> {
+  typedef A8 Argument8;
+  typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8> ArgumentTuple;
+  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
+  typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8);
+  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8);
+};
+
+template <typename R, typename A1, typename A2, typename A3, typename A4,
+    typename A5, typename A6, typename A7, typename A8, typename A9>
+struct Function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)>
+    : Function<R(A1, A2, A3, A4, A5, A6, A7, A8)> {
+  typedef A9 Argument9;
+  typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> ArgumentTuple;
+  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
+  typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8, A9);
+  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8,
+      A9);
+};
+
+template <typename R, typename A1, typename A2, typename A3, typename A4,
+    typename A5, typename A6, typename A7, typename A8, typename A9,
+    typename A10>
+struct Function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)>
+    : Function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> {
+  typedef A10 Argument10;
+  typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9,
+      A10> ArgumentTuple;
+  typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
+  typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10);
+  typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8,
+      A9, A10);
+};
+
+}  // namespace internal
+
+}  // namespace testing
+
+#endif  // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
+
+namespace testing {
+namespace internal {
+
+// Converts an identifier name to a space-separated list of lower-case
+// words.  Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
+// treated as one word.  For example, both "FooBar123" and
+// "foo_bar_123" are converted to "foo bar 123".
+GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name);
+
+// PointeeOf<Pointer>::type is the type of a value pointed to by a
+// Pointer, which can be either a smart pointer or a raw pointer.  The
+// following default implementation is for the case where Pointer is a
+// smart pointer.
+template <typename Pointer>
+struct PointeeOf {
+  // Smart pointer classes define type element_type as the type of
+  // their pointees.
+  typedef typename Pointer::element_type type;
+};
+// This specialization is for the raw pointer case.
+template <typename T>
+struct PointeeOf<T*> { typedef T type; };  // NOLINT
+
+// GetRawPointer(p) returns the raw pointer underlying p when p is a
+// smart pointer, or returns p itself when p is already a raw pointer.
+// The following default implementation is for the smart pointer case.
+template <typename Pointer>
+inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {
+  return p.get();
+}
+// This overloaded version is for the raw pointer case.
+template <typename Element>
+inline Element* GetRawPointer(Element* p) { return p; }
+
+// This comparator allows linked_ptr to be stored in sets.
+template <typename T>
+struct LinkedPtrLessThan {
+  bool operator()(const ::testing::internal::linked_ptr<T>& lhs,
+                  const ::testing::internal::linked_ptr<T>& rhs) const {
+    return lhs.get() < rhs.get();
+  }
+};
+
+// Symbian compilation can be done with wchar_t being either a native
+// type or a typedef.  Using Google Mock with OpenC without wchar_t
+// should require the definition of _STLP_NO_WCHAR_T.
+//
+// MSVC treats wchar_t as a native type usually, but treats it as the
+// same as unsigned short when the compiler option /Zc:wchar_t- is
+// specified.  It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
+// is a native type.
+#if (GTEST_OS_SYMBIAN && defined(_STLP_NO_WCHAR_T)) || \
+    (defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED))
+// wchar_t is a typedef.
+#else
+# define GMOCK_WCHAR_T_IS_NATIVE_ 1
+#endif
+
+// signed wchar_t and unsigned wchar_t are NOT in the C++ standard.
+// Using them is a bad practice and not portable.  So DON'T use them.
+//
+// Still, Google Mock is designed to work even if the user uses signed
+// wchar_t or unsigned wchar_t (obviously, assuming the compiler
+// supports them).
+//
+// To gcc,
+//   wchar_t == signed wchar_t != unsigned wchar_t == unsigned int
+#ifdef __GNUC__
+// signed/unsigned wchar_t are valid types.
+# define GMOCK_HAS_SIGNED_WCHAR_T_ 1
+#endif
+
+// In what follows, we use the term "kind" to indicate whether a type
+// is bool, an integer type (excluding bool), a floating-point type,
+// or none of them.  This categorization is useful for determining
+// when a matcher argument type can be safely converted to another
+// type in the implementation of SafeMatcherCast.
+enum TypeKind {
+  kBool, kInteger, kFloatingPoint, kOther
+};
+
+// KindOf<T>::value is the kind of type T.
+template <typename T> struct KindOf {
+  enum { value = kOther };  // The default kind.
+};
+
+// This macro declares that the kind of 'type' is 'kind'.
+#define GMOCK_DECLARE_KIND_(type, kind) \
+  template <> struct KindOf<type> { enum { value = kind }; }
+
+GMOCK_DECLARE_KIND_(bool, kBool);
+
+// All standard integer types.
+GMOCK_DECLARE_KIND_(char, kInteger);
+GMOCK_DECLARE_KIND_(signed char, kInteger);
+GMOCK_DECLARE_KIND_(unsigned char, kInteger);
+GMOCK_DECLARE_KIND_(short, kInteger);  // NOLINT
+GMOCK_DECLARE_KIND_(unsigned short, kInteger);  // NOLINT
+GMOCK_DECLARE_KIND_(int, kInteger);
+GMOCK_DECLARE_KIND_(unsigned int, kInteger);
+GMOCK_DECLARE_KIND_(long, kInteger);  // NOLINT
+GMOCK_DECLARE_KIND_(unsigned long, kInteger);  // NOLINT
+
+#if GMOCK_WCHAR_T_IS_NATIVE_
+GMOCK_DECLARE_KIND_(wchar_t, kInteger);
+#endif
+
+// Non-standard integer types.
+GMOCK_DECLARE_KIND_(Int64, kInteger);
+GMOCK_DECLARE_KIND_(UInt64, kInteger);
+
+// All standard floating-point types.
+GMOCK_DECLARE_KIND_(float, kFloatingPoint);
+GMOCK_DECLARE_KIND_(double, kFloatingPoint);
+GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
+
+#undef GMOCK_DECLARE_KIND_
+
+// Evaluates to the kind of 'type'.
+#define GMOCK_KIND_OF_(type) \
+  static_cast< ::testing::internal::TypeKind>( \
+      ::testing::internal::KindOf<type>::value)
+
+// Evaluates to true iff integer type T is signed.
+#define GMOCK_IS_SIGNED_(T) (static_cast<T>(-1) < 0)
+
+// LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
+// is true iff arithmetic type From can be losslessly converted to
+// arithmetic type To.
+//
+// It's the user's responsibility to ensure that both From and To are
+// raw (i.e. has no CV modifier, is not a pointer, and is not a
+// reference) built-in arithmetic types, kFromKind is the kind of
+// From, and kToKind is the kind of To; the value is
+// implementation-defined when the above pre-condition is violated.
+template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>
+struct LosslessArithmeticConvertibleImpl : public false_type {};
+
+// Converting bool to bool is lossless.
+template <>
+struct LosslessArithmeticConvertibleImpl<kBool, bool, kBool, bool>
+    : public true_type {};  // NOLINT
+
+// Converting bool to any integer type is lossless.
+template <typename To>
+struct LosslessArithmeticConvertibleImpl<kBool, bool, kInteger, To>
+    : public true_type {};  // NOLINT
+
+// Converting bool to any floating-point type is lossless.
+template <typename To>
+struct LosslessArithmeticConvertibleImpl<kBool, bool, kFloatingPoint, To>
+    : public true_type {};  // NOLINT
+
+// Converting an integer to bool is lossy.
+template <typename From>
+struct LosslessArithmeticConvertibleImpl<kInteger, From, kBool, bool>
+    : public false_type {};  // NOLINT
+
+// Converting an integer to another non-bool integer is lossless iff
+// the target type's range encloses the source type's range.
+template <typename From, typename To>
+struct LosslessArithmeticConvertibleImpl<kInteger, From, kInteger, To>
+    : public bool_constant<
+      // When converting from a smaller size to a larger size, we are
+      // fine as long as we are not converting from signed to unsigned.
+      ((sizeof(From) < sizeof(To)) &&
+       (!GMOCK_IS_SIGNED_(From) || GMOCK_IS_SIGNED_(To))) ||
+      // When converting between the same size, the signedness must match.
+      ((sizeof(From) == sizeof(To)) &&
+       (GMOCK_IS_SIGNED_(From) == GMOCK_IS_SIGNED_(To)))> {};  // NOLINT
+
+#undef GMOCK_IS_SIGNED_
+
+// Converting an integer to a floating-point type may be lossy, since
+// the format of a floating-point number is implementation-defined.
+template <typename From, typename To>
+struct LosslessArithmeticConvertibleImpl<kInteger, From, kFloatingPoint, To>
+    : public false_type {};  // NOLINT
+
+// Converting a floating-point to bool is lossy.
+template <typename From>
+struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kBool, bool>
+    : public false_type {};  // NOLINT
+
+// Converting a floating-point to an integer is lossy.
+template <typename From, typename To>
+struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kInteger, To>
+    : public false_type {};  // NOLINT
+
+// Converting a floating-point to another floating-point is lossless
+// iff the target type is at least as big as the source type.
+template <typename From, typename To>
+struct LosslessArithmeticConvertibleImpl<
+  kFloatingPoint, From, kFloatingPoint, To>
+    : public bool_constant<sizeof(From) <= sizeof(To)> {};  // NOLINT
+
+// LosslessArithmeticConvertible<From, To>::value is true iff arithmetic
+// type From can be losslessly converted to arithmetic type To.
+//
+// It's the user's responsibility to ensure that both From and To are
+// raw (i.e. has no CV modifier, is not a pointer, and is not a
+// reference) built-in arithmetic types; the value is
+// implementation-defined when the above pre-condition is violated.
+template <typename From, typename To>
+struct LosslessArithmeticConvertible
+    : public LosslessArithmeticConvertibleImpl<
+  GMOCK_KIND_OF_(From), From, GMOCK_KIND_OF_(To), To> {};  // NOLINT
+
+// This interface knows how to report a Google Mock failure (either
+// non-fatal or fatal).
+class FailureReporterInterface {
+ public:
+  // The type of a failure (either non-fatal or fatal).
+  enum FailureType {
+    kNonfatal, kFatal
+  };
+
+  virtual ~FailureReporterInterface() {}
+
+  // Reports a failure that occurred at the given source file location.
+  virtual void ReportFailure(FailureType type, const char* file, int line,
+                             const string& message) = 0;
+};
+
+// Returns the failure reporter used by Google Mock.
+GTEST_API_ FailureReporterInterface* GetFailureReporter();
+
+// Asserts that condition is true; aborts the process with the given
+// message if condition is false.  We cannot use LOG(FATAL) or CHECK()
+// as Google Mock might be used to mock the log sink itself.  We
+// inline this function to prevent it from showing up in the stack
+// trace.
+inline void Assert(bool condition, const char* file, int line,
+                   const string& msg) {
+  if (!condition) {
+    GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal,
+                                        file, line, msg);
+  }
+}
+inline void Assert(bool condition, const char* file, int line) {
+  Assert(condition, file, line, "Assertion failed.");
+}
+
+// Verifies that condition is true; generates a non-fatal failure if
+// condition is false.
+inline void Expect(bool condition, const char* file, int line,
+                   const string& msg) {
+  if (!condition) {
+    GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal,
+                                        file, line, msg);
+  }
+}
+inline void Expect(bool condition, const char* file, int line) {
+  Expect(condition, file, line, "Expectation failed.");
+}
+
+// Severity level of a log.
+enum LogSeverity {
+  kInfo = 0,
+  kWarning = 1
+};
+
+// Valid values for the --gmock_verbose flag.
+
+// All logs (informational and warnings) are printed.
+const char kInfoVerbosity[] = "info";
+// Only warnings are printed.
+const char kWarningVerbosity[] = "warning";
+// No logs are printed.
+const char kErrorVerbosity[] = "error";
+
+// Returns true iff a log with the given severity is visible according
+// to the --gmock_verbose flag.
+GTEST_API_ bool LogIsVisible(LogSeverity severity);
+
+// Prints the given message to stdout iff 'severity' >= the level
+// specified by the --gmock_verbose flag.  If stack_frames_to_skip >=
+// 0, also prints the stack trace excluding the top
+// stack_frames_to_skip frames.  In opt mode, any positive
+// stack_frames_to_skip is treated as 0, since we don't know which
+// function calls will be inlined by the compiler and need to be
+// conservative.
+GTEST_API_ void Log(LogSeverity severity,
+                    const string& message,
+                    int stack_frames_to_skip);
+
+// TODO(wan@google.com): group all type utilities together.
+
+// Type traits.
+
+// is_reference<T>::value is non-zero iff T is a reference type.
+template <typename T> struct is_reference : public false_type {};
+template <typename T> struct is_reference<T&> : public true_type {};
+
+// type_equals<T1, T2>::value is non-zero iff T1 and T2 are the same type.
+template <typename T1, typename T2> struct type_equals : public false_type {};
+template <typename T> struct type_equals<T, T> : public true_type {};
+
+// remove_reference<T>::type removes the reference from type T, if any.
+template <typename T> struct remove_reference { typedef T type; };  // NOLINT
+template <typename T> struct remove_reference<T&> { typedef T type; }; // NOLINT
+
+// DecayArray<T>::type turns an array type U[N] to const U* and preserves
+// other types.  Useful for saving a copy of a function argument.
+template <typename T> struct DecayArray { typedef T type; };  // NOLINT
+template <typename T, size_t N> struct DecayArray<T[N]> {
+  typedef const T* type;
+};
+// Sometimes people use arrays whose size is not available at the use site
+// (e.g. extern const char kNamePrefix[]).  This specialization covers that
+// case.
+template <typename T> struct DecayArray<T[]> {
+  typedef const T* type;
+};
+
+// Disable MSVC warnings for infinite recursion, since in this case the
+// the recursion is unreachable.
+#ifdef _MSC_VER
+# pragma warning(push)
+# pragma warning(disable:4717)
+#endif
+
+// Invalid<T>() is usable as an expression of type T, but will terminate
+// the program with an assertion failure if actually run.  This is useful
+// when a value of type T is needed for compilation, but the statement
+// will not really be executed (or we don't care if the statement
+// crashes).
+template <typename T>
+inline T Invalid() {
+  Assert(false, "", -1, "Internal error: attempt to return invalid value");
+  // This statement is unreachable, and would never terminate even if it
+  // could be reached. It is provided only to placate compiler warnings
+  // about missing return statements.
+  return Invalid<T>();
+}
+
+#ifdef _MSC_VER
+# pragma warning(pop)
+#endif
+
+// Given a raw type (i.e. having no top-level reference or const
+// modifier) RawContainer that's either an STL-style container or a
+// native array, class StlContainerView<RawContainer> has the
+// following members:
+//
+//   - type is a type that provides an STL-style container view to
+//     (i.e. implements the STL container concept for) RawContainer;
+//   - const_reference is a type that provides a reference to a const
+//     RawContainer;
+//   - ConstReference(raw_container) returns a const reference to an STL-style
+//     container view to raw_container, which is a RawContainer.
+//   - Copy(raw_container) returns an STL-style container view of a
+//     copy of raw_container, which is a RawContainer.
+//
+// This generic version is used when RawContainer itself is already an
+// STL-style container.
+template <class RawContainer>
+class StlContainerView {
+ public:
+  typedef RawContainer type;
+  typedef const type& const_reference;
+
+  static const_reference ConstReference(const RawContainer& container) {
+    // Ensures that RawContainer is not a const type.
+    testing::StaticAssertTypeEq<RawContainer,
+        GTEST_REMOVE_CONST_(RawContainer)>();
+    return container;
+  }
+  static type Copy(const RawContainer& container) { return container; }
+};
+
+// This specialization is used when RawContainer is a native array type.
+template <typename Element, size_t N>
+class StlContainerView<Element[N]> {
+ public:
+  typedef GTEST_REMOVE_CONST_(Element) RawElement;
+  typedef internal::NativeArray<RawElement> type;
+  // NativeArray<T> can represent a native array either by value or by
+  // reference (selected by a constructor argument), so 'const type'
+  // can be used to reference a const native array.  We cannot
+  // 'typedef const type& const_reference' here, as that would mean
+  // ConstReference() has to return a reference to a local variable.
+  typedef const type const_reference;
+
+  static const_reference ConstReference(const Element (&array)[N]) {
+    // Ensures that Element is not a const type.
+    testing::StaticAssertTypeEq<Element, RawElement>();
+#if GTEST_OS_SYMBIAN
+    // The Nokia Symbian compiler confuses itself in template instantiation
+    // for this call without the cast to Element*:
+    // function call '[testing::internal::NativeArray<char *>].NativeArray(
+    //     {lval} const char *[4], long, testing::internal::RelationToSource)'
+    //     does not match
+    // 'testing::internal::NativeArray<char *>::NativeArray(
+    //     char *const *, unsigned int, testing::internal::RelationToSource)'
+    // (instantiating: 'testing::internal::ContainsMatcherImpl
+    //     <const char * (&)[4]>::Matches(const char * (&)[4]) const')
+    // (instantiating: 'testing::internal::StlContainerView<char *[4]>::
+    //     ConstReference(const char * (&)[4])')
+    // (and though the N parameter type is mismatched in the above explicit
+    // conversion of it doesn't help - only the conversion of the array).
+    return type(const_cast<Element*>(&array[0]), N,
+                RelationToSourceReference());
+#else
+    return type(array, N, RelationToSourceReference());
+#endif  // GTEST_OS_SYMBIAN
+  }
+  static type Copy(const Element (&array)[N]) {
+#if GTEST_OS_SYMBIAN
+    return type(const_cast<Element*>(&array[0]), N, RelationToSourceCopy());
+#else
+    return type(array, N, RelationToSourceCopy());
+#endif  // GTEST_OS_SYMBIAN
+  }
+};
+
+// This specialization is used when RawContainer is a native array
+// represented as a (pointer, size) tuple.
+template <typename ElementPointer, typename Size>
+class StlContainerView< ::testing::tuple<ElementPointer, Size> > {
+ public:
+  typedef GTEST_REMOVE_CONST_(
+      typename internal::PointeeOf<ElementPointer>::type) RawElement;
+  typedef internal::NativeArray<RawElement> type;
+  typedef const type const_reference;
+
+  static const_reference ConstReference(
+      const ::testing::tuple<ElementPointer, Size>& array) {
+    return type(get<0>(array), get<1>(array), RelationToSourceReference());
+  }
+  static type Copy(const ::testing::tuple<ElementPointer, Size>& array) {
+    return type(get<0>(array), get<1>(array), RelationToSourceCopy());
+  }
+};
+
+// The following specialization prevents the user from instantiating
+// StlContainer with a reference type.
+template <typename T> class StlContainerView<T&>;
+
+// A type transform to remove constness from the first part of a pair.
+// Pairs like that are used as the value_type of associative containers,
+// and this transform produces a similar but assignable pair.
+template <typename T>
+struct RemoveConstFromKey {
+  typedef T type;
+};
+
+// Partially specialized to remove constness from std::pair<const K, V>.
+template <typename K, typename V>
+struct RemoveConstFromKey<std::pair<const K, V> > {
+  typedef std::pair<K, V> type;
+};
+
+// Mapping from booleans to types. Similar to boost::bool_<kValue> and
+// std::integral_constant<bool, kValue>.
+template <bool kValue>
+struct BooleanConstant {};
+
+}  // namespace internal
+}  // namespace testing
+
+#endif  // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
+
+
+#if GTEST_HAS_STD_TYPE_TRAITS_  // Defined by gtest-port.h via gmock-port.h.
+#include <type_traits>
+#endif
+
+namespace testing {
+
+// To implement an action Foo, define:
+//   1. a class FooAction that implements the ActionInterface interface, and
+//   2. a factory function that creates an Action object from a
+//      const FooAction*.
+//
+// The two-level delegation design follows that of Matcher, providing
+// consistency for extension developers.  It also eases ownership
+// management as Action objects can now be copied like plain values.
+
+namespace internal {
+
+template <typename F1, typename F2>
+class ActionAdaptor;
+
+// BuiltInDefaultValueGetter<T, true>::Get() returns a
+// default-constructed T value.  BuiltInDefaultValueGetter<T,
+// false>::Get() crashes with an error.
+//
+// This primary template is used when kDefaultConstructible is true.
+template <typename T, bool kDefaultConstructible>
+struct BuiltInDefaultValueGetter {
+  static T Get() { return T(); }
+};
+template <typename T>
+struct BuiltInDefaultValueGetter<T, false> {
+  static T Get() {
+    Assert(false, __FILE__, __LINE__,
+           "Default action undefined for the function return type.");
+    return internal::Invalid<T>();
+    // The above statement will never be reached, but is required in
+    // order for this function to compile.
+  }
+};
+
+// BuiltInDefaultValue<T>::Get() returns the "built-in" default value
+// for type T, which is NULL when T is a raw pointer type, 0 when T is
+// a numeric type, false when T is bool, or "" when T is string or
+// std::string.  In addition, in C++11 and above, it turns a
+// default-constructed T value if T is default constructible.  For any
+// other type T, the built-in default T value is undefined, and the
+// function will abort the process.
+template <typename T>
+class BuiltInDefaultValue {
+ public:
+#if GTEST_HAS_STD_TYPE_TRAITS_
+  // This function returns true iff type T has a built-in default value.
+  static bool Exists() {
+    return ::std::is_default_constructible<T>::value;
+  }
+
+  static T Get() {
+    return BuiltInDefaultValueGetter<
+        T, ::std::is_default_constructible<T>::value>::Get();
+  }
+
+#else  // GTEST_HAS_STD_TYPE_TRAITS_
+  // This function returns true iff type T has a built-in default value.
+  static bool Exists() {
+    return false;
+  }
+
+  static T Get() {
+    return BuiltInDefaultValueGetter<T, false>::Get();
+  }
+
+#endif  // GTEST_HAS_STD_TYPE_TRAITS_
+};
+
+// This partial specialization says that we use the same built-in
+// default value for T and const T.
+template <typename T>
+class BuiltInDefaultValue<const T> {
+ public:
+  static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
+  static T Get() { return BuiltInDefaultValue<T>::Get(); }
+};
+
+// This partial specialization defines the default values for pointer
+// types.
+template <typename T>
+class BuiltInDefaultValue<T*> {
+ public:
+  static bool Exists() { return true; }
+  static T* Get() { return NULL; }
+};
+
+// The following specializations define the default values for
+// specific types we care about.
+#define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
+  template <> \
+  class BuiltInDefaultValue<type> { \
+   public: \
+    static bool Exists() { return true; } \
+    static type Get() { return value; } \
+  }
+
+GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, );  // NOLINT
+#if GTEST_HAS_GLOBAL_STRING
+GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::string, "");
+#endif  // GTEST_HAS_GLOBAL_STRING
+GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
+GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
+GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
+GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
+GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
+
+// There's no need for a default action for signed wchar_t, as that
+// type is the same as wchar_t for gcc, and invalid for MSVC.
+//
+// There's also no need for a default action for unsigned wchar_t, as
+// that type is the same as unsigned int for gcc, and invalid for
+// MSVC.
+#if GMOCK_WCHAR_T_IS_NATIVE_
+GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U);  // NOLINT
+#endif
+
+GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U);  // NOLINT
+GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0);     // NOLINT
+GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
+GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
+GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL);  // NOLINT
+GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L);     // NOLINT
+GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0);
+GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0);
+GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
+GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
+
+#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
+
+}  // namespace internal
+
+// When an unexpected function call is encountered, Google Mock will
+// let it return a default value if the user has specified one for its
+// return type, or if the return type has a built-in default value;
+// otherwise Google Mock won't know what value to return and will have
+// to abort the process.
+//
+// The DefaultValue<T> class allows a user to specify the
+// default value for a type T that is both copyable and publicly
+// destructible (i.e. anything that can be used as a function return
+// type).  The usage is:
+//
+//   // Sets the default value for type T to be foo.
+//   DefaultValue<T>::Set(foo);
+template <typename T>
+class DefaultValue {
+ public:
+  // Sets the default value for type T; requires T to be
+  // copy-constructable and have a public destructor.
+  static void Set(T x) {
+    delete producer_;
+    producer_ = new FixedValueProducer(x);
+  }
+
+  // Provides a factory function to be called to generate the default value.
+  // This method can be used even if T is only move-constructible, but it is not
+  // limited to that case.
+  typedef T (*FactoryFunction)();
+  static void SetFactory(FactoryFunction factory) {
+    delete producer_;
+    producer_ = new FactoryValueProducer(factory);
+  }
+
+  // Unsets the default value for type T.
+  static void Clear() {
+    delete producer_;
+    producer_ = NULL;
+  }
+
+  // Returns true iff the user has set the default value for type T.
+  static bool IsSet() { return producer_ != NULL; }
+
+  // Returns true if T has a default return value set by the user or there
+  // exists a built-in default value.
+  static bool Exists() {
+    return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
+  }
+
+  // Returns the default value for type T if the user has set one;
+  // otherwise returns the built-in default value. Requires that Exists()
+  // is true, which ensures that the return value is well-defined.
+  static T Get() {
+    return producer_ == NULL ?
+        internal::BuiltInDefaultValue<T>::Get() : producer_->Produce();
+  }
+
+ private:
+  class ValueProducer {
+   public:
+    virtual ~ValueProducer() {}
+    virtual T Produce() = 0;
+  };
+
+  class FixedValueProducer : public ValueProducer {
+   public:
+    explicit FixedValueProducer(T value) : value_(value) {}
+    virtual T Produce() { return value_; }
+
+   private:
+    const T value_;
+    GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer);
+  };
+
+  class FactoryValueProducer : public ValueProducer {
+   public:
+    explicit FactoryValueProducer(FactoryFunction factory)
+        : factory_(factory) {}
+    virtual T Produce() { return factory_(); }
+
+   private:
+    const FactoryFunction factory_;
+    GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer);
+  };
+
+  static ValueProducer* producer_;
+};
+
+// This partial specialization allows a user to set default values for
+// reference types.
+template <typename T>
+class DefaultValue<T&> {
+ public:
+  // Sets the default value for type T&.
+  static void Set(T& x) {  // NOLINT
+    address_ = &x;
+  }
+
+  // Unsets the default value for type T&.
+  static void Clear() {
+    address_ = NULL;
+  }
+
+  // Returns true iff the user has set the default value for type T&.
+  static bool IsSet() { return address_ != NULL; }
+
+  // Returns true if T has a default return value set by the user or there
+  // exists a built-in default value.
+  static bool Exists() {
+    return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
+  }
+
+  // Returns the default value for type T& if the user has set one;
+  // otherwise returns the built-in default value if there is one;
+  // otherwise aborts the process.
+  static T& Get() {
+    return address_ == NULL ?
+        internal::BuiltInDefaultValue<T&>::Get() : *address_;
+  }
+
+ private:
+  static T* address_;
+};
+
+// This specialization allows DefaultValue<void>::Get() to
+// compile.
+template <>
+class DefaultValue<void> {
+ public:
+  static bool Exists() { return true; }
+  static void Get() {}
+};
+
+// Points to the user-set default value for type T.
+template <typename T>
+typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = NULL;
+
+// Points to the user-set default value for type T&.
+template <typename T>
+T* DefaultValue<T&>::address_ = NULL;
+
+// Implement this interface to define an action for function type F.
+template <typename F>
+class ActionInterface {
+ public:
+  typedef typename internal::Function<F>::Result Result;
+  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
+
+  ActionInterface() {}
+  virtual ~ActionInterface() {}
+
+  // Performs the action.  This method is not const, as in general an
+  // action can have side effects and be stateful.  For example, a
+  // get-the-next-element-from-the-collection action will need to
+  // remember the current element.
+  virtual Result Perform(const ArgumentTuple& args) = 0;
+
+ private:
+  GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface);
+};
+
+// An Action<F> is a copyable and IMMUTABLE (except by assignment)
+// object that represents an action to be taken when a mock function
+// of type F is called.  The implementation of Action<T> is just a
+// linked_ptr to const ActionInterface<T>, so copying is fairly cheap.
+// Don't inherit from Action!
+//
+// You can view an object implementing ActionInterface<F> as a
+// concrete action (including its current state), and an Action<F>
+// object as a handle to it.
+template <typename F>
+class Action {
+ public:
+  typedef typename internal::Function<F>::Result Result;
+  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
+
+  // Constructs a null Action.  Needed for storing Action objects in
+  // STL containers.
+  Action() : impl_(NULL) {}
+
+  // Constructs an Action from its implementation.  A NULL impl is
+  // used to represent the "do-default" action.
+  explicit Action(ActionInterface<F>* impl) : impl_(impl) {}
+
+  // Copy constructor.
+  Action(const Action& action) : impl_(action.impl_) {}
+
+  // This constructor allows us to turn an Action<Func> object into an
+  // Action<F>, as long as F's arguments can be implicitly converted
+  // to Func's and Func's return type can be implicitly converted to
+  // F's.
+  template <typename Func>
+  explicit Action(const Action<Func>& action);
+
+  // Returns true iff this is the DoDefault() action.
+  bool IsDoDefault() const { return impl_.get() == NULL; }
+
+  // Performs the action.  Note that this method is const even though
+  // the corresponding method in ActionInterface is not.  The reason
+  // is that a const Action<F> means that it cannot be re-bound to
+  // another concrete action, not that the concrete action it binds to
+  // cannot change state.  (Think of the difference between a const
+  // pointer and a pointer to const.)
+  Result Perform(const ArgumentTuple& args) const {
+    internal::Assert(
+        !IsDoDefault(), __FILE__, __LINE__,
+        "You are using DoDefault() inside a composite action like "
+        "DoAll() or WithArgs().  This is not supported for technical "
+        "reasons.  Please instead spell out the default action, or "
+        "assign the default action to an Action variable and use "
+        "the variable in various places.");
+    return impl_->Perform(args);
+  }
+
+ private:
+  template <typename F1, typename F2>
+  friend class internal::ActionAdaptor;
+
+  internal::linked_ptr<ActionInterface<F> > impl_;
+};
+
+// The PolymorphicAction class template makes it easy to implement a
+// polymorphic action (i.e. an action that can be used in mock
+// functions of than one type, e.g. Return()).
+//
+// To define a polymorphic action, a user first provides a COPYABLE
+// implementation class that has a Perform() method template:
+//
+//   class FooAction {
+//    public:
+//     template <typename Result, typename ArgumentTuple>
+//     Result Perform(const ArgumentTuple& args) const {
+//       // Processes the arguments and returns a result, using
+//       // tr1::get<N>(args) to get the N-th (0-based) argument in the tuple.
+//     }
+//     ...
+//   };
+//
+// Then the user creates the polymorphic action using
+// MakePolymorphicAction(object) where object has type FooAction.  See
+// the definition of Return(void) and SetArgumentPointee<N>(value) for
+// complete examples.
+template <typename Impl>
+class PolymorphicAction {
+ public:
+  explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
+
+  template <typename F>
+  operator Action<F>() const {
+    return Action<F>(new MonomorphicImpl<F>(impl_));
+  }
+
+ private:
+  template <typename F>
+  class MonomorphicImpl : public ActionInterface<F> {
+   public:
+    typedef typename internal::Function<F>::Result Result;
+    typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
+
+    explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
+
+    virtual Result Perform(const ArgumentTuple& args) {
+      return impl_.template Perform<Result>(args);
+    }
+
+   private:
+    Impl impl_;
+
+    GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
+  };
+
+  Impl impl_;
+
+  GTEST_DISALLOW_ASSIGN_(PolymorphicAction);
+};
+
+// Creates an Action from its implementation and returns it.  The
+// created Action object owns the implementation.
+template <typename F>
+Action<F> MakeAction(ActionInterface<F>* impl) {
+  return Action<F>(impl);
+}
+
+// Creates a polymorphic action from its implementation.  This is
+// easier to use than the PolymorphicAction<Impl> constructor as it
+// doesn't require you to explicitly write the template argument, e.g.
+//
+//   MakePolymorphicAction(foo);
+// vs
+//   PolymorphicAction<TypeOfFoo>(foo);
+template <typename Impl>
+inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
+  return PolymorphicAction<Impl>(impl);
+}
+
+namespace internal {
+
+// Allows an Action<F2> object to pose as an Action<F1>, as long as F2
+// and F1 are compatible.
+template <typename F1, typename F2>
+class ActionAdaptor : public ActionInterface<F1> {
+ public:
+  typedef typename internal::Function<F1>::Result Result;
+  typedef typename internal::Function<F1>::ArgumentTuple ArgumentTuple;
+
+  explicit ActionAdaptor(const Action<F2>& from) : impl_(from.impl_) {}
+
+  virtual Result Perform(const ArgumentTuple& args) {
+    return impl_->Perform(args);
+  }
+
+ private:
+  const internal::linked_ptr<ActionInterface<F2> > impl_;
+
+  GTEST_DISALLOW_ASSIGN_(ActionAdaptor);
+};
+
+// Helper struct to specialize ReturnAction to execute a move instead of a copy
+// on return. Useful for move-only types, but could be used on any type.
+template <typename T>
+struct ByMoveWrapper {
+  explicit ByMoveWrapper(T value) : payload(internal::move(value)) {}
+  T payload;
+};
+
+// Implements the polymorphic Return(x) action, which can be used in
+// any function that returns the type of x, regardless of the argument
+// types.
+//
+// Note: The value passed into Return must be converted into
+// Function<F>::Result when this action is cast to Action<F> rather than
+// when that action is performed. This is important in scenarios like
+//
+// MOCK_METHOD1(Method, T(U));
+// ...
+// {
+//   Foo foo;
+//   X x(&foo);
+//   EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
+// }
+//
+// In the example above the variable x holds reference to foo which leaves
+// scope and gets destroyed.  If copying X just copies a reference to foo,
+// that copy will be left with a hanging reference.  If conversion to T
+// makes a copy of foo, the above code is safe. To support that scenario, we
+// need to make sure that the type conversion happens inside the EXPECT_CALL
+// statement, and conversion of the result of Return to Action<T(U)> is a
+// good place for that.
+//
+template <typename R>
+class ReturnAction {
+ public:
+  // Constructs a ReturnAction object from the value to be returned.
+  // 'value' is passed by value instead of by const reference in order
+  // to allow Return("string literal") to compile.
+  explicit ReturnAction(R value) : value_(new R(internal::move(value))) {}
+
+  // This template type conversion operator allows Return(x) to be
+  // used in ANY function that returns x's type.
+  template <typename F>
+  operator Action<F>() const {
+    // Assert statement belongs here because this is the best place to verify
+    // conditions on F. It produces the clearest error messages
+    // in most compilers.
+    // Impl really belongs in this scope as a local class but can't
+    // because MSVC produces duplicate symbols in different translation units
+    // in this case. Until MS fixes that bug we put Impl into the class scope
+    // and put the typedef both here (for use in assert statement) and
+    // in the Impl class. But both definitions must be the same.
+    typedef typename Function<F>::Result Result;
+    GTEST_COMPILE_ASSERT_(
+        !is_reference<Result>::value,
+        use_ReturnRef_instead_of_Return_to_return_a_reference);
+    return Action<F>(new Impl<R, F>(value_));
+  }
+
+ private:
+  // Implements the Return(x) action for a particular function type F.
+  template <typename R_, typename F>
+  class Impl : public ActionInterface<F> {
+   public:
+    typedef typename Function<F>::Result Result;
+    typedef typename Function<F>::ArgumentTuple ArgumentTuple;
+
+    // The implicit cast is necessary when Result has more than one
+    // single-argument constructor (e.g. Result is std::vector<int>) and R
+    // has a type conversion operator template.  In that case, value_(value)
+    // won't compile as the compiler doesn't known which constructor of
+    // Result to call.  ImplicitCast_ forces the compiler to convert R to
+    // Result without considering explicit constructors, thus resolving the
+    // ambiguity. value_ is then initialized using its copy constructor.
+    explicit Impl(const linked_ptr<R>& value)
+        : value_before_cast_(*value),
+          value_(ImplicitCast_<Result>(value_before_cast_)) {}
+
+    virtual Result Perform(const ArgumentTuple&) { return value_; }
+
+   private:
+    GTEST_COMPILE_ASSERT_(!is_reference<Result>::value,
+                          Result_cannot_be_a_reference_type);
+    // We save the value before casting just in case it is being cast to a
+    // wrapper type.
+    R value_before_cast_;
+    Result value_;
+
+    GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
+  };
+
+  // Partially specialize for ByMoveWrapper. This version of ReturnAction will
+  // move its contents instead.
+  template <typename R_, typename F>
+  class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> {
+   public:
+    typedef typename Function<F>::Result Result;
+    typedef typename Function<F>::ArgumentTuple ArgumentTuple;
+
+    explicit Impl(const linked_ptr<R>& wrapper)
+        : performed_(false), wrapper_(wrapper) {}
+
+    virtual Result Perform(const ArgumentTuple&) {
+      GTEST_CHECK_(!performed_)
+          << "A ByMove() action should only be performed once.";
+      performed_ = true;
+      return internal::move(wrapper_->payload);
+    }
+
+   private:
+    bool performed_;
+    const linked_ptr<R> wrapper_;
+
+    GTEST_DISALLOW_ASSIGN_(Impl);
+  };
+
+  const linked_ptr<R> value_;
+
+  GTEST_DISALLOW_ASSIGN_(ReturnAction);
+};
+
+// Implements the ReturnNull() action.
+class ReturnNullAction {
+ public:
+  // Allows ReturnNull() to be used in any pointer-returning function. In C++11
+  // this is enforced by returning nullptr, and in non-C++11 by asserting a
+  // pointer type on compile time.
+  template <typename Result, typename ArgumentTuple>
+  static Result Perform(const ArgumentTuple&) {
+#if GTEST_LANG_CXX11
+    return nullptr;
+#else
+    GTEST_COMPILE_ASSERT_(internal::is_pointer<Result>::value,
+                          ReturnNull_can_be_used_to_return_a_pointer_only);
+    return NULL;
+#endif  // GTEST_LANG_CXX11
+  }
+};
+
+// Implements the Return() action.
+class ReturnVoidAction {
+ public:
+  // Allows Return() to be used in any void-returning function.
+  template <typename Result, typename ArgumentTuple>
+  static void Perform(const ArgumentTuple&) {
+    CompileAssertTypesEqual<void, Result>();
+  }
+};
+
+// Implements the polymorphic ReturnRef(x) action, which can be used
+// in any function that returns a reference to the type of x,
+// regardless of the argument types.
+template <typename T>
+class ReturnRefAction {
+ public:
+  // Constructs a ReturnRefAction object from the reference to be returned.
+  explicit ReturnRefAction(T& ref) : ref_(ref) {}  // NOLINT
+
+  // This template type conversion operator allows ReturnRef(x) to be
+  // used in ANY function that returns a reference to x's type.
+  template <typename F>
+  operator Action<F>() const {
+    typedef typename Function<F>::Result Result;
+    // Asserts that the function return type is a reference.  This
+    // catches the user error of using ReturnRef(x) when Return(x)
+    // should be used, and generates some helpful error message.
+    GTEST_COMPILE_ASSERT_(internal::is_reference<Result>::value,
+                          use_Return_instead_of_ReturnRef_to_return_a_value);
+    return Action<F>(new Impl<F>(ref_));
+  }
+
+ private:
+  // Implements the ReturnRef(x) action for a particular function type F.
+  template <typename F>
+  class Impl : public ActionInterface<F> {
+   public:
+    typedef typename Function<F>::Result Result;
+    typedef typename Function<F>::ArgumentTuple ArgumentTuple;
+
+    explicit Impl(T& ref) : ref_(ref) {}  // NOLINT
+
+    virtual Result Perform(const ArgumentTuple&) {
+      return ref_;
+    }
+
+   private:
+    T& ref_;
+
+    GTEST_DISALLOW_ASSIGN_(Impl);
+  };
+
+  T& ref_;
+
+  GTEST_DISALLOW_ASSIGN_(ReturnRefAction);
+};
+
+// Implements the polymorphic ReturnRefOfCopy(x) action, which can be
+// used in any function that returns a reference to the type of x,
+// regardless of the argument types.
+template <typename T>
+class ReturnRefOfCopyAction {
+ public:
+  // Constructs a ReturnRefOfCopyAction object from the reference to
+  // be returned.
+  explicit ReturnRefOfCopyAction(const T& value) : value_(value) {}  // NOLINT
+
+  // This template type conversion operator allows ReturnRefOfCopy(x) to be
+  // used in ANY function that returns a reference to x's type.
+  template <typename F>
+  operator Action<F>() const {
+    typedef typename Function<F>::Result Result;
+    // Asserts that the function return type is a reference.  This
+    // catches the user error of using ReturnRefOfCopy(x) when Return(x)
+    // should be used, and generates some helpful error message.
+    GTEST_COMPILE_ASSERT_(
+        internal::is_reference<Result>::value,
+        use_Return_instead_of_ReturnRefOfCopy_to_return_a_value);
+    return Action<F>(new Impl<F>(value_));
+  }
+
+ private:
+  // Implements the ReturnRefOfCopy(x) action for a particular function type F.
+  template <typename F>
+  class Impl : public ActionInterface<F> {
+   public:
+    typedef typename Function<F>::Result Result;
+    typedef typename Function<F>::ArgumentTuple ArgumentTuple;
+
+    explicit Impl(const T& value) : value_(value) {}  // NOLINT
+
+    virtual Result Perform(const ArgumentTuple&) {
+      return value_;
+    }
+
+   private:
+    T value_;
+
+    GTEST_DISALLOW_ASSIGN_(Impl);
+  };
+
+  const T value_;
+
+  GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction);
+};
+
+// Implements the polymorphic DoDefault() action.
+class DoDefaultAction {
+ public:
+  // This template type conversion operator allows DoDefault() to be
+  // used in any function.
+  template <typename F>
+  operator Action<F>() const { return Action<F>(NULL); }
+};
+
+// Implements the Assign action to set a given pointer referent to a
+// particular value.
+template <typename T1, typename T2>
+class AssignAction {
+ public:
+  AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
+
+  template <typename Result, typename ArgumentTuple>
+  void Perform(const ArgumentTuple& /* args */) const {
+    *ptr_ = value_;
+  }
+
+ private:
+  T1* const ptr_;
+  const T2 value_;
+
+  GTEST_DISALLOW_ASSIGN_(AssignAction);
+};
+
+#if !GTEST_OS_WINDOWS_MOBILE
+
+// Implements the SetErrnoAndReturn action to simulate return from
+// various system calls and libc functions.
+template <typename T>
+class SetErrnoAndReturnAction {
+ public:
+  SetErrnoAndReturnAction(int errno_value, T result)
+      : errno_(errno_value),
+        result_(result) {}
+  template <typename Result, typename ArgumentTuple>
+  Result Perform(const ArgumentTuple& /* args */) const {
+    errno = errno_;
+    return result_;
+  }
+
+ private:
+  const int errno_;
+  const T result_;
+
+  GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction);
+};
+
+#endif  // !GTEST_OS_WINDOWS_MOBILE
+
+// Implements the SetArgumentPointee<N>(x) action for any function
+// whose N-th argument (0-based) is a pointer to x's type.  The
+// template parameter kIsProto is true iff type A is ProtocolMessage,
+// proto2::Message, or a sub-class of those.
+template <size_t N, typename A, bool kIsProto>
+class SetArgumentPointeeAction {
+ public:
+  // Constructs an action that sets the variable pointed to by the
+  // N-th function argument to 'value'.
+  explicit SetArgumentPointeeAction(const A& value) : value_(value) {}
+
+  template <typename Result, typename ArgumentTuple>
+  void Perform(const ArgumentTuple& args) const {
+    CompileAssertTypesEqual<void, Result>();
+    *::testing::get<N>(args) = value_;
+  }
+
+ private:
+  const A value_;
+
+  GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
+};
+
+template <size_t N, typename Proto>
+class SetArgumentPointeeAction<N, Proto, true> {
+ public:
+  // Constructs an action that sets the variable pointed to by the
+  // N-th function argument to 'proto'.  Both ProtocolMessage and
+  // proto2::Message have the CopyFrom() method, so the same
+  // implementation works for both.
+  explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) {
+    proto_->CopyFrom(proto);
+  }
+
+  template <typename Result, typename ArgumentTuple>
+  void Perform(const ArgumentTuple& args) const {
+    CompileAssertTypesEqual<void, Result>();
+    ::testing::get<N>(args)->CopyFrom(*proto_);
+  }
+
+ private:
+  const internal::linked_ptr<Proto> proto_;
+
+  GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
+};
+
+// Implements the InvokeWithoutArgs(f) action.  The template argument
+// FunctionImpl is the implementation type of f, which can be either a
+// function pointer or a functor.  InvokeWithoutArgs(f) can be used as an
+// Action<F> as long as f's type is compatible with F (i.e. f can be
+// assigned to a tr1::function<F>).
+template <typename FunctionImpl>
+class InvokeWithoutArgsAction {
+ public:
+  // The c'tor makes a copy of function_impl (either a function
+  // pointer or a functor).
+  explicit InvokeWithoutArgsAction(FunctionImpl function_impl)
+      : function_impl_(function_impl) {}
+
+  // Allows InvokeWithoutArgs(f) to be used as any action whose type is
+  // compatible with f.
+  template <typename Result, typename ArgumentTuple>
+  Result Perform(const ArgumentTuple&) { return function_impl_(); }
+
+ private:
+  FunctionImpl function_impl_;
+
+  GTEST_DISALLOW_ASSIGN_(InvokeWithoutArgsAction);
+};
+
+// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
+template <class Class, typename MethodPtr>
+class InvokeMethodWithoutArgsAction {
+ public:
+  InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr)
+      : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {}
+
+  template <typename Result, typename ArgumentTuple>
+  Result Perform(const ArgumentTuple&) const {
+    return (obj_ptr_->*method_ptr_)();
+  }
+
+ private:
+  Class* const obj_ptr_;
+  const MethodPtr method_ptr_;
+
+  GTEST_DISALLOW_ASSIGN_(InvokeMethodWithoutArgsAction);
+};
+
+// Implements the IgnoreResult(action) action.
+template <typename A>
+class IgnoreResultAction {
+ public:
+  explicit IgnoreResultAction(const A& action) : action_(action) {}
+
+  template <typename F>
+  operator Action<F>() const {
+    // Assert statement belongs here because this is the best place to verify
+    // conditions on F. It produces the clearest error messages
+    // in most compilers.
+    // Impl really belongs in this scope as a local class but can't
+    // because MSVC produces duplicate symbols in different translation units
+    // in this case. Until MS fixes that bug we put Impl into the class scope
+    // and put the typedef both here (for use in assert statement) and
+    // in the Impl class. But both definitions must be the same.
+    typedef typename internal::Function<F>::Result Result;
+
+    // Asserts at compile time that F returns void.
+    CompileAssertTypesEqual<void, Result>();
+
+    return Action<F>(new Impl<F>(action_));
+  }
+
+ private:
+  template <typename F>
+  class Impl : public ActionInterface<F> {
+   public:
+    typedef typename internal::Function<F>::Result Result;
+    typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
+
+    explicit Impl(const A& action) : action_(action) {}
+
+    virtual void Perform(const ArgumentTuple& args) {
+      // Performs the action and ignores its result.
+      action_.Perform(args);
+    }
+
+   private:
+    // Type OriginalFunction is the same as F except that its return
+    // type is IgnoredValue.
+    typedef typename internal::Function<F>::MakeResultIgnoredValue
+        OriginalFunction;
+
+    const Action<OriginalFunction> action_;
+
+    GTEST_DISALLOW_ASSIGN_(Impl);
+  };
+
+  const A action_;
+
+  GTEST_DISALLOW_ASSIGN_(IgnoreResultAction);
+};
+
+// A ReferenceWrapper<T> object represents a reference to type T,
+// which can be either const or not.  It can be explicitly converted
+// from, and implicitly converted to, a T&.  Unlike a reference,
+// ReferenceWrapper<T> can be copied and can survive template type
+// inference.  This is used to support by-reference arguments in the
+// InvokeArgument<N>(...) action.  The idea was from "reference
+// wrappers" in tr1, which we don't have in our source tree yet.
+template <typename T>
+class ReferenceWrapper {
+ public:
+  // Constructs a ReferenceWrapper<T> object from a T&.
+  explicit ReferenceWrapper(T& l_value) : pointer_(&l_value) {}  // NOLINT
+
+  // Allows a ReferenceWrapper<T> object to be implicitly converted to
+  // a T&.
+  operator T&() const { return *pointer_; }
+ private:
+  T* pointer_;
+};
+
+// Allows the expression ByRef(x) to be printed as a reference to x.
+template <typename T>
+void PrintTo(const ReferenceWrapper<T>& ref, ::std::ostream* os) {
+  T& value = ref;
+  UniversalPrinter<T&>::Print(value, os);
+}
+
+// Does two actions sequentially.  Used for implementing the DoAll(a1,
+// a2, ...) action.
+template <typename Action1, typename Action2>
+class DoBothAction {
+ public:
+  DoBothAction(Action1 action1, Action2 action2)
+      : action1_(action1), action2_(action2) {}
+
+  // This template type conversion operator allows DoAll(a1, ..., a_n)
+  // to be used in ANY function of compatible type.
+  template <typename F>
+  operator Action<F>() const {
+    return Action<F>(new Impl<F>(action1_, action2_));
+  }
+
+ private:
+  // Implements the DoAll(...) action for a particular function type F.
+  template <typename F>
+  class Impl : public ActionInterface<F> {
+   public:
+    typedef typename Function<F>::Result Result;
+    typedef typename Function<F>::ArgumentTuple ArgumentTuple;
+    typedef typename Function<F>::MakeResultVoid VoidResult;
+
+    Impl(const Action<VoidResult>& action1, const Action<F>& action2)
+        : action1_(action1), action2_(action2) {}
+
+    virtual Result Perform(const ArgumentTuple& args) {
+      action1_.Perform(args);
+      return action2_.Perform(args);
+    }
+
+   private:
+    const Action<VoidResult> action1_;
+    const Action<F> action2_;
+
+    GTEST_DISALLOW_ASSIGN_(Impl);
+  };
+
+  Action1 action1_;
+  Action2 action2_;
+
+  GTEST_DISALLOW_ASSIGN_(DoBothAction);
+};
+
+}  // namespace internal
+
+// An Unused object can be implicitly constructed from ANY value.
+// This is handy when defining actions that ignore some or all of the
+// mock function arguments.  For example, given
+//
+//   MOCK_METHOD3(Foo, double(const string& label, double x, double y));
+//   MOCK_METHOD3(Bar, double(int index, double x, double y));
+//
+// instead of
+//
+//   double DistanceToOriginWithLabel(const string& label, double x, double y) {
+//     return sqrt(x*x + y*y);
+//   }
+//   double DistanceToOriginWithIndex(int index, double x, double y) {
+//     return sqrt(x*x + y*y);
+//   }
+//   ...
+//   EXEPCT_CALL(mock, Foo("abc", _, _))
+//       .WillOnce(Invoke(DistanceToOriginWithLabel));
+//   EXEPCT_CALL(mock, Bar(5, _, _))
+//       .WillOnce(Invoke(DistanceToOriginWithIndex));
+//
+// you could write
+//
+//   // We can declare any uninteresting argument as Unused.
+//   double DistanceToOrigin(Unused, double x, double y) {
+//     return sqrt(x*x + y*y);
+//   }
+//   ...
+//   EXEPCT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
+//   EXEPCT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
+typedef internal::IgnoredValue Unused;
+
+// This constructor allows us to turn an Action<From> object into an
+// Action<To>, as long as To's arguments can be implicitly converted
+// to From's and From's return type cann be implicitly converted to
+// To's.
+template <typename To>
+template <typename From>
+Action<To>::Action(const Action<From>& from)
+    : impl_(new internal::ActionAdaptor<To, From>(from)) {}
+
+// Creates an action that returns 'value'.  'value' is passed by value
+// instead of const reference - otherwise Return("string literal")
+// will trigger a compiler error about using array as initializer.
+template <typename R>
+internal::ReturnAction<R> Return(R value) {
+  return internal::ReturnAction<R>(internal::move(value));
+}
+
+// Creates an action that returns NULL.
+inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
+  return MakePolymorphicAction(internal::ReturnNullAction());
+}
+
+// Creates an action that returns from a void function.
+inline PolymorphicAction<internal::ReturnVoidAction> Return() {
+  return MakePolymorphicAction(internal::ReturnVoidAction());
+}
+
+// Creates an action that returns the reference to a variable.
+template <typename R>
+inline internal::ReturnRefAction<R> ReturnRef(R& x) {  // NOLINT
+  return internal::ReturnRefAction<R>(x);
+}
+
+// Creates an action that returns the reference to a copy of the
+// argument.  The copy is created when the action is constructed and
+// lives as long as the action.
+template <typename R>
+inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
+  return internal::ReturnRefOfCopyAction<R>(x);
+}
+
+// Modifies the parent action (a Return() action) to perform a move of the
+// argument instead of a copy.
+// Return(ByMove()) actions can only be executed once and will assert this
+// invariant.
+template <typename R>
+internal::ByMoveWrapper<R> ByMove(R x) {
+  return internal::ByMoveWrapper<R>(internal::move(x));
+}
+
+// Creates an action that does the default action for the give mock function.
+inline internal::DoDefaultAction DoDefault() {
+  return internal::DoDefaultAction();
+}
+
+// Creates an action that sets the variable pointed by the N-th
+// (0-based) function argument to 'value'.
+template <size_t N, typename T>
+PolymorphicAction<
+  internal::SetArgumentPointeeAction<
+    N, T, internal::IsAProtocolMessage<T>::value> >
+SetArgPointee(const T& x) {
+  return MakePolymorphicAction(internal::SetArgumentPointeeAction<
+      N, T, internal::IsAProtocolMessage<T>::value>(x));
+}
+
+#if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN)
+// This overload allows SetArgPointee() to accept a string literal.
+// GCC prior to the version 4.0 and Symbian C++ compiler cannot distinguish
+// this overload from the templated version and emit a compile error.
+template <size_t N>
+PolymorphicAction<
+  internal::SetArgumentPointeeAction<N, const char*, false> >
+SetArgPointee(const char* p) {
+  return MakePolymorphicAction(internal::SetArgumentPointeeAction<
+      N, const char*, false>(p));
+}
+
+template <size_t N>
+PolymorphicAction<
+  internal::SetArgumentPointeeAction<N, const wchar_t*, false> >
+SetArgPointee(const wchar_t* p) {
+  return MakePolymorphicAction(internal::SetArgumentPointeeAction<
+      N, const wchar_t*, false>(p));
+}
+#endif
+
+// The following version is DEPRECATED.
+template <size_t N, typename T>
+PolymorphicAction<
+  internal::SetArgumentPointeeAction<
+    N, T, internal::IsAProtocolMessage<T>::value> >
+SetArgumentPointee(const T& x) {
+  return MakePolymorphicAction(internal::SetArgumentPointeeAction<
+      N, T, internal::IsAProtocolMessage<T>::value>(x));
+}
+
+// Creates an action that sets a pointer referent to a given value.
+template <typename T1, typename T2>
+PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
+  return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
+}
+
+#if !GTEST_OS_WINDOWS_MOBILE
+
+// Creates an action that sets errno and returns the appropriate error.
+template <typename T>
+PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
+SetErrnoAndReturn(int errval, T result) {
+  return MakePolymorphicAction(
+      internal::SetErrnoAndReturnAction<T>(errval, result));
+}
+
+#endif  // !GTEST_OS_WINDOWS_MOBILE
+
+// Various overloads for InvokeWithoutArgs().
+
+// Creates an action that invokes 'function_impl' with no argument.
+template <typename FunctionImpl>
+PolymorphicAction<internal::InvokeWithoutArgsAction<FunctionImpl> >
+InvokeWithoutArgs(FunctionImpl function_impl) {
+  return MakePolymorphicAction(
+      internal::InvokeWithoutArgsAction<FunctionImpl>(function_impl));
+}
+
+// Creates an action that invokes the given method on the given object
+// with no argument.
+template <class Class, typename MethodPtr>
+PolymorphicAction<internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> >
+InvokeWithoutArgs(Class* obj_ptr, MethodPtr method_ptr) {
+  return MakePolymorphicAction(
+      internal::InvokeMethodWithoutArgsAction<Class, MethodPtr>(
+          obj_ptr, method_ptr));
+}
+
+// Creates an action that performs an_action and throws away its
+// result.  In other words, it changes the return type of an_action to
+// void.  an_action MUST NOT return void, or the code won't compile.
+template <typename A>
+inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
+  return internal::IgnoreResultAction<A>(an_action);
+}
+
+// Creates a reference wrapper for the given L-value.  If necessary,
+// you can explicitly specify the type of the reference.  For example,
+// suppose 'derived' is an object of type Derived, ByRef(derived)
+// would wrap a Derived&.  If you want to wrap a const Base& instead,
+// where Base is a base class of Derived, just write:
+//
+//   ByRef<const Base>(derived)
+template <typename T>
+inline internal::ReferenceWrapper<T> ByRef(T& l_value) {  // NOLINT
+  return internal::ReferenceWrapper<T>(l_value);
+}
+
+}  // namespace testing
+
+#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
+// Copyright 2007, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+// Author: wan@google.com (Zhanyong Wan)
+
+// Google Mock - a framework for writing C++ mock classes.
+//
+// This file implements some commonly used cardinalities.  More
+// cardinalities can be defined by the user implementing the
+// CardinalityInterface interface if necessary.
+
+#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
+#define GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
+
+#include <limits.h>
+#include <ostream>  // NOLINT
+
+namespace testing {
+
+// To implement a cardinality Foo, define:
+//   1. a class FooCardinality that implements the
+//      CardinalityInterface interface, and
+//   2. a factory function that creates a Cardinality object from a
+//      const FooCardinality*.
+//
+// The two-level delegation design follows that of Matcher, providing
+// consistency for extension developers.  It also eases ownership
+// management as Cardinality objects can now be copied like plain values.
+
+// The implementation of a cardinality.
+class CardinalityInterface {
+ public:
+  virtual ~CardinalityInterface() {}
+
+  // Conservative estimate on the lower/upper bound of the number of
+  // calls allowed.
+  virtual int ConservativeLowerBound() const { return 0; }
+  virtual int ConservativeUpperBound() const { return INT_MAX; }
+
+  // Returns true iff call_count calls will satisfy this cardinality.
+  virtual bool IsSatisfiedByCallCount(int call_count) const = 0;
+
+  // Returns true iff call_count calls will saturate this cardinality.
+  virtual bool IsSaturatedByCallCount(int call_count) const = 0;
+
+  // Describes self to an ostream.
+  virtual void DescribeTo(::std::ostream* os) const = 0;
+};
+
+// A Cardinality is a copyable and IMMUTABLE (except by assignment)
+// object that specifies how many times a mock function is expected to
+// be called.  The implementation of Cardinality is just a linked_ptr
+// to const CardinalityInterface, so copying is fairly cheap.
+// Don't inherit from Cardinality!
+class GTEST_API_ Cardinality {
+ public:
+  // Constructs a null cardinality.  Needed for storing Cardinality
+  // objects in STL containers.
+  Cardinality() {}
+
+  // Constructs a Cardinality from its implementation.
+  explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {}
+
+  // Conservative estimate on the lower/upper bound of the number of
+  // calls allowed.
+  int ConservativeLowerBound() const { return impl_->ConservativeLowerBound(); }
+  int ConservativeUpperBound() const { return impl_->ConservativeUpperBound(); }
+
+  // Returns true iff call_count calls will satisfy this cardinality.
+  bool IsSatisfiedByCallCount(int call_count) const {
+    return impl_->IsSatisfiedByCallCount(call_count);
+  }
+
+  // Returns true iff call_count calls will saturate this cardinality.
+  bool IsSaturatedByCallCount(int call_count) const {
+    return impl_->IsSaturatedByCallCount(call_count);
+  }
+
+  // Returns true iff call_count calls will over-saturate this
+  // cardinality, i.e. exceed the maximum number of allowed calls.
+  bool IsOverSaturatedByCallCount(int call_count) const {
+    return impl_->IsSaturatedByCallCount(call_count) &&
+        !impl_->IsSatisfiedByCallCount(call_count);
+  }
+
+  // Describes self to an ostream
+  void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
+
+  // Describes the given actual call count to an ostream.
+  static void DescribeActualCallCountTo(int actual_call_count,
+                                        ::std::ostream* os);
+
+ private:
+  internal::linked_ptr<const CardinalityInterface> impl_;
+};
+
+// Creates a cardinality that allows at least n calls.
+GTEST_API_ Cardinality AtLeast(int n);
+
+// Creates a cardinality that allows at most n calls.
+GTEST_API_ Cardinality AtMost(int n);
+
+// Creates a cardinality that allows any number of calls.
+GTEST_API_ Cardinality AnyNumber();
+
+// Creates a cardinality that allows between min and max calls.
+GTEST_API_ Cardinality Between(int min, int max);
+
+// Creates a cardinality that allows exactly n calls.
+GTEST_API_ Cardinality Exactly(int n);
+
+// Creates a cardinali

<TRUNCATED>

[43/50] [abbrv] marmotta git commit: upgraded to the recently released commons-io 2.5

Posted by wi...@apache.org.
upgraded to the recently released commons-io 2.5


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/01b2938a
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/01b2938a
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/01b2938a

Branch: refs/heads/MARMOTTA-584
Commit: 01b2938ae41e708cdc3ef9a75ba850d2d2ef206f
Parents: ff559ea
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Mon Apr 25 09:01:30 2016 +0200
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Mon Apr 25 09:01:30 2016 +0200

----------------------------------------------------------------------
 parent/pom.xml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/01b2938a/parent/pom.xml
----------------------------------------------------------------------
diff --git a/parent/pom.xml b/parent/pom.xml
index 81750b9..1e8beac 100644
--- a/parent/pom.xml
+++ b/parent/pom.xml
@@ -624,7 +624,7 @@
             <dependency>
                 <groupId>commons-io</groupId>
                 <artifactId>commons-io</artifactId>
-                <version>2.4</version>
+                <version>2.5</version>
             </dependency>
             <dependency>
                 <groupId>commons-configuration</groupId>


[20/50] [abbrv] marmotta git commit: MARMOTTA-627: applied patch by @orinciog from github, closes #17

Posted by wi...@apache.org.
MARMOTTA-627: applied patch by @orinciog from github, closes #17


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/cfdf9e60
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/cfdf9e60
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/cfdf9e60

Branch: refs/heads/MARMOTTA-584
Commit: cfdf9e604352382ede3f05dac39004c929981ebe
Parents: ea28ddb
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Thu Feb 11 14:27:43 2016 +0100
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Thu Feb 11 14:27:43 2016 +0100

----------------------------------------------------------------------
 .../kiwi/sparql/builder/eval/ValueExpressionEvaluator.java         | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/cfdf9e60/libraries/kiwi/kiwi-sparql/src/main/java/org/apache/marmotta/kiwi/sparql/builder/eval/ValueExpressionEvaluator.java
----------------------------------------------------------------------
diff --git a/libraries/kiwi/kiwi-sparql/src/main/java/org/apache/marmotta/kiwi/sparql/builder/eval/ValueExpressionEvaluator.java b/libraries/kiwi/kiwi-sparql/src/main/java/org/apache/marmotta/kiwi/sparql/builder/eval/ValueExpressionEvaluator.java
index dee6841..2d41ff9 100644
--- a/libraries/kiwi/kiwi-sparql/src/main/java/org/apache/marmotta/kiwi/sparql/builder/eval/ValueExpressionEvaluator.java
+++ b/libraries/kiwi/kiwi-sparql/src/main/java/org/apache/marmotta/kiwi/sparql/builder/eval/ValueExpressionEvaluator.java
@@ -733,7 +733,7 @@ public class ValueExpressionEvaluator extends QueryModelVisitorBase<RuntimeExcep
             case PLUS: return " + ";
             case MINUS: return " - ";
             case DIVIDE: return " / ";
-            case MULTIPLY: return " / ";
+            case MULTIPLY: return " * ";
         }
         throw new IllegalArgumentException("unsupported operator type for math expression: "+op);
     }


[29/50] [abbrv] marmotta git commit: - support SPARQL ASK queries in ostrich

Posted by wi...@apache.org.
- support SPARQL ASK queries in ostrich


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/4a5e588c
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/4a5e588c
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/4a5e588c

Branch: refs/heads/MARMOTTA-584
Commit: 4a5e588cd274794f7b7880cab49ebd88962cb72b
Parents: e764c2b
Author: Sebastian Schaffert <ss...@apache.org>
Authored: Sat Feb 13 15:25:58 2016 +0100
Committer: Sebastian Schaffert <ss...@apache.org>
Committed: Sat Feb 13 15:25:58 2016 +0100

----------------------------------------------------------------------
 libraries/ostrich/backend/client/client.cc      | 53 ++++++++++++----
 .../backend/persistence/leveldb_service.cc      | 63 ++++++++++++++------
 .../backend/persistence/leveldb_service.h       |  4 ++
 libraries/ostrich/backend/service/sparql.proto  |  4 ++
 .../ostrich/backend/sparql/rasqal_adapter.cc    | 47 +++++++++++++--
 .../ostrich/backend/sparql/rasqal_adapter.h     |  6 ++
 libraries/ostrich/backend/test/SparqlTest.cc    | 20 +++++++
 7 files changed, 164 insertions(+), 33 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/4a5e588c/libraries/ostrich/backend/client/client.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/client/client.cc b/libraries/ostrich/backend/client/client.cc
index b4a5178..8921938 100644
--- a/libraries/ostrich/backend/client/client.cc
+++ b/libraries/ostrich/backend/client/client.cc
@@ -70,19 +70,13 @@ class ClientReaderIterator : public util::CloseableIterator<T> {
  public:
     ClientReaderIterator() : finished(true) { }
 
-    ClientReaderIterator(ClientReader<Proto>* r) : reader(r) {
-        finished = !reader->Read(&buffer);
+    ClientReaderIterator(ClientReader<Proto>* r) : reader(r), finished(false) {
+        read();
     }
 
     const T& next() override {
         current_ = T(buffer);
-
-        if (!finished) {
-            finished = !reader->Read(&buffer);
-            if (finished) {
-                reader->Finish();
-            }
-        }
+        read();
         return current_;
     }
 
@@ -99,6 +93,16 @@ class ClientReaderIterator : public util::CloseableIterator<T> {
     Proto buffer;
     T current_;
     bool finished;
+
+    void read() {
+        if (!finished) {
+            finished = !reader->Read(&buffer);
+            if (finished) {
+                auto st = reader->Finish();
+                LOG_IF(FATAL, !st.ok()) << "Reading results failed: " << st.error_message();
+            }
+        }
+    }
 };
 
 typedef ClientReaderIterator<rdf::Statement, rdf::proto::Statement> StatementReader;
@@ -214,6 +218,25 @@ class MarmottaClient {
         }
     }
 
+    void askQuery(const std::string& query, std::ostream &out) {
+        ClientContext context;
+        spq::SparqlRequest request;
+        request.set_query(query);
+
+        google::protobuf::BoolValue result;
+
+        Status status = sparql_->AskQuery(&context, request, &result);
+        if (status.ok()) {
+            if (result.value()) {
+                out << "YES" << std::endl;
+            } else {
+                out << "NO" << std::endl;
+            }
+        } else {
+            LOG(FATAL) << "SPARQL query failed: " << status.error_message();
+        }
+    }
+
 
     void listNamespaces(std::ostream &out) {
         ClientContext context;
@@ -238,7 +261,7 @@ class MarmottaClient {
         if (status.ok()) {
             return result.value();
         } else {
-            return -1;
+            LOG(FATAL) << "Calculating size failed: " << status.error_message();
         }
     }
  private:
@@ -318,6 +341,16 @@ int main(int argc, char** argv) {
         }
     }
 
+    if ("ask" == std::string(argv[1])) {
+        std::string query = argv[2];
+        if (FLAGS_output != "") {
+            std::ofstream out(FLAGS_output);
+            client.askQuery(query, out);
+        } else {
+            client.askQuery(query, std::cout);
+        }
+    }
+
     if ("delete" == std::string(argv[1])) {
         rdf::proto::Statement query;
         TextFormat::ParseFromString(argv[2], &query);

http://git-wip-us.apache.org/repos/asf/marmotta/blob/4a5e588c/libraries/ostrich/backend/persistence/leveldb_service.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/persistence/leveldb_service.cc b/libraries/ostrich/backend/persistence/leveldb_service.cc
index 5ea08a1..f2637bd 100644
--- a/libraries/ostrich/backend/persistence/leveldb_service.cc
+++ b/libraries/ostrich/backend/persistence/leveldb_service.cc
@@ -22,6 +22,7 @@
 #include <model/rdf_operators.h>
 #include <util/unique.h>
 #include <util/time_logger.h>
+#include <glog/logging.h>
 
 using grpc::Status;
 using grpc::StatusCode;
@@ -242,18 +243,23 @@ grpc::Status LevelDBSparqlService::TupleQuery(
 
     rdf::URI base_uri = query->base_uri();
 
-    svc.TupleQuery(query->query(), base_uri,
-                   [&result](const SparqlService::RowType& row) {
-        spq::SparqlResponse response;
-        for (auto it = row.cbegin(); it != row.cend(); it++) {
-            auto b = response.add_binding();
-            b->set_variable(it->first);
-            *b->mutable_value() = it->second.getMessage();
-        }
-        return result->Write(response);
-    });
-
-    return Status::OK;
+    try {
+        svc.TupleQuery(query->query(), base_uri,
+                       [&result](const SparqlService::RowType& row) {
+                           spq::SparqlResponse response;
+                           for (auto it = row.cbegin(); it != row.cend(); it++) {
+                               auto b = response.add_binding();
+                               b->set_variable(it->first);
+                               *b->mutable_value() = it->second.getMessage();
+                           }
+                           return result->Write(response);
+                       });
+
+        return Status::OK;
+    } catch (sparql::SparqlException e) {
+        LOG(ERROR) << "SPARQL execution failed: " << e.what();
+        return Status(StatusCode::INVALID_ARGUMENT, e.what());
+    }
 }
 
 
@@ -265,12 +271,35 @@ grpc::Status LevelDBSparqlService::GraphQuery(grpc::ServerContext* context,
 
     rdf::URI base_uri = query->base_uri();
 
-    svc.GraphQuery(query->query(), base_uri,
-                   [&result](const rdf::Statement& triple) {
-        return result->Write(triple.getMessage());
-    });
+    try {
+        svc.GraphQuery(query->query(), base_uri,
+                       [&result](const rdf::Statement& triple) {
+                           return result->Write(triple.getMessage());
+                       });
 
-    return Status::OK;
+        return Status::OK;
+    } catch (sparql::SparqlException e) {
+        LOG(ERROR) << "SPARQL execution failed: " << e.what();
+        return Status(StatusCode::INVALID_ARGUMENT, e.what());
+    }
+}
+
+grpc::Status LevelDBSparqlService::AskQuery(grpc::ServerContext* context,
+                                            const spq::SparqlRequest* query,
+                                            google::protobuf::BoolValue* result) {
+
+    SparqlService svc(util::make_unique<LevelDBTripleSource>(persistence));
+
+    rdf::URI base_uri = query->base_uri();
+
+    try {
+        result->set_value(svc.AskQuery(query->query(), base_uri));
+
+        return Status::OK;
+    } catch (sparql::SparqlException e) {
+        LOG(ERROR) << "SPARQL execution failed: " << e.what();
+        return Status(StatusCode::INVALID_ARGUMENT, e.what());
+    }
 }
 
 

http://git-wip-us.apache.org/repos/asf/marmotta/blob/4a5e588c/libraries/ostrich/backend/persistence/leveldb_service.h
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/persistence/leveldb_service.h b/libraries/ostrich/backend/persistence/leveldb_service.h
index 44056a3..87b5b12 100644
--- a/libraries/ostrich/backend/persistence/leveldb_service.h
+++ b/libraries/ostrich/backend/persistence/leveldb_service.h
@@ -114,6 +114,10 @@ class LevelDBSparqlService : public spq::SparqlService::Service {
     grpc::Status GraphQuery(grpc::ServerContext* context,
                             const spq::SparqlRequest* pattern,
                             grpc::ServerWriter<rdf::proto::Statement>* result) override;
+
+    grpc::Status AskQuery(grpc::ServerContext* context,
+                          const spq::SparqlRequest* pattern,
+                          google::protobuf::BoolValue* result) override;
  private:
     persistence::LevelDBPersistence* persistence;
 };

http://git-wip-us.apache.org/repos/asf/marmotta/blob/4a5e588c/libraries/ostrich/backend/service/sparql.proto
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/service/sparql.proto b/libraries/ostrich/backend/service/sparql.proto
index 6d75a5f..e6da6d3 100644
--- a/libraries/ostrich/backend/service/sparql.proto
+++ b/libraries/ostrich/backend/service/sparql.proto
@@ -22,6 +22,7 @@ package marmotta.sparql.proto;
 option java_package = "org.apache.marmotta.ostrich.client.proto";
 
 import "model.proto";
+import "google/protobuf/wrappers.proto";
 
 // SPARQL request consisting of a single query string.
 message SparqlRequest {
@@ -46,4 +47,7 @@ service SparqlService {
 
     // Execute a SPARQL 1.1 graph query and stream back the triples.
     rpc GraphQuery(SparqlRequest) returns (stream marmotta.rdf.proto.Statement);
+
+    // Execute a SPARQL 1.1 ask query and return true or false.
+    rpc AskQuery(SparqlRequest) returns (google.protobuf.BoolValue);
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/marmotta/blob/4a5e588c/libraries/ostrich/backend/sparql/rasqal_adapter.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/sparql/rasqal_adapter.cc b/libraries/ostrich/backend/sparql/rasqal_adapter.cc
index 09e7bd6..1f6055b 100644
--- a/libraries/ostrich/backend/sparql/rasqal_adapter.cc
+++ b/libraries/ostrich/backend/sparql/rasqal_adapter.cc
@@ -62,7 +62,7 @@ std::string formatBindings(const std::map<std::string, rdf::Value>& bindings) {
 #endif
 
 void log_handler(void *user_data, raptor_log_message *message) {
-    LOG(ERROR) << "SPARQL Error(" << message->code << "): " << message->text;
+    LOG_IF(ERROR, message->code >= 0) << "SPARQL Error(" << message->code << "): " << message->text;
 }
 
 // Bind the current statement to the variables configured in the triple match.
@@ -262,7 +262,7 @@ void SparqlService::TupleQuery(const std::string& query, const rdf::URI& base_ur
     if (rasqal_query_prepare(q, STR(query), base) != 0) {
         raptor_free_uri(base);
         rasqal_free_query(q);
-        throw SparqlException("Query preparation failed", query);
+        throw SparqlException("could not parse query", query);
     }
 
     bool next = true;
@@ -270,14 +270,14 @@ void SparqlService::TupleQuery(const std::string& query, const rdf::URI& base_ur
     if (r == nullptr) {
         raptor_free_uri(base);
         rasqal_free_query(q);
-        throw SparqlException("Query execution failed", query);
+        throw SparqlException("query execution failed", query);
     }
 
     if (!rasqal_query_results_is_bindings(r)) {
         rasqal_free_query_results(r);
         rasqal_free_query(q);
         raptor_free_uri(base);
-        throw SparqlException("Query is not a tuple query", query);
+        throw SparqlException("query is not a tuple query", query);
     }
 
     int rowcount = 0;
@@ -313,7 +313,7 @@ void SparqlService::GraphQuery(const std::string& query, const rdf::URI& base_ur
     if (rasqal_query_prepare(q, STR(query), base) != 0) {
         raptor_free_uri(base);
         rasqal_free_query(q);
-        throw SparqlException("Query preparation failed", query);
+        throw SparqlException("could not parse query", query);
     }
 
     bool next = true;
@@ -328,7 +328,7 @@ void SparqlService::GraphQuery(const std::string& query, const rdf::URI& base_ur
         rasqal_free_query_results(r);
         rasqal_free_query(q);
         raptor_free_uri(base);
-        throw SparqlException("Query is not a graph query", query);
+        throw SparqlException("query is not a graph query", query);
     }
 
     while (next) {
@@ -341,6 +341,41 @@ void SparqlService::GraphQuery(const std::string& query, const rdf::URI& base_ur
     raptor_free_uri(base);
 }
 
+bool SparqlService::AskQuery(const std::string& query, const rdf::URI& base_uri) {
+    util::TimeLogger timeLogger("SPARQL ask query");
+
+    auto q = rasqal_new_query(world, "sparql11-query", nullptr);
+    auto base = raptor_new_uri(rasqal_world_get_raptor(world),
+                               STR(base_uri.getUri()));
+    if (rasqal_query_prepare(q, STR(query), base) != 0) {
+        raptor_free_uri(base);
+        rasqal_free_query(q);
+        throw SparqlException("could not parse query", query);
+    }
+
+    auto r = rasqal_query_execute(q);
+    if (r == nullptr || rasqal_query_results_get_boolean(r) < 0) {
+        raptor_free_uri(base);
+        rasqal_free_query(q);
+        throw SparqlException("query execution failed", query);
+    }
+
+    if (!rasqal_query_results_is_boolean(r)) {
+        rasqal_free_query_results(r);
+        rasqal_free_query(q);
+        raptor_free_uri(base);
+        throw SparqlException("query is not a boolean query", query);
+    }
+
+    bool result = rasqal_query_results_get_boolean(r) > 0;
+
+    rasqal_free_query_results(r);
+    rasqal_free_query(q);
+    raptor_free_uri(base);
+
+    return result;
+}
+
 
 }  // namespace sparql
 }  // namespace marmotta

http://git-wip-us.apache.org/repos/asf/marmotta/blob/4a5e588c/libraries/ostrich/backend/sparql/rasqal_adapter.h
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/sparql/rasqal_adapter.h b/libraries/ostrich/backend/sparql/rasqal_adapter.h
index 32e82d2..2f75887 100644
--- a/libraries/ostrich/backend/sparql/rasqal_adapter.h
+++ b/libraries/ostrich/backend/sparql/rasqal_adapter.h
@@ -98,6 +98,12 @@ class SparqlService {
     void GraphQuery(const std::string& query, const rdf::URI& base_uri,
                     std::function<bool(const rdf::Statement&)> stmt_handler);
 
+
+    /**
+     * Execute a boolean (ASK) query, returning the boolean result.
+     */
+    bool AskQuery(const std::string& query, const rdf::URI& base_uri);
+
     /**
      * Return a reference to the triple source managed by this service.
      */

http://git-wip-us.apache.org/repos/asf/marmotta/blob/4a5e588c/libraries/ostrich/backend/test/SparqlTest.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/test/SparqlTest.cc b/libraries/ostrich/backend/test/SparqlTest.cc
index 0f663f5..a45a282 100644
--- a/libraries/ostrich/backend/test/SparqlTest.cc
+++ b/libraries/ostrich/backend/test/SparqlTest.cc
@@ -267,5 +267,25 @@ TEST(SPARQLTest, Graph) {
 }
 
 
+TEST(SPARQLTest, AskTrue) {
+    rdf::Statement stmt = rdf::Statement(rdf::URI("http://example.com/s1"),
+                                         rdf::URI("http://example.com/p1"),
+                                         rdf::URI("http://example.com/o1"));
+    SparqlService svc(std::unique_ptr<TripleSource>(new MockTripleSource({stmt})));
+
+    EXPECT_TRUE(svc.AskQuery("ASK {}", base_uri));
+}
+
+
+TEST(SPARQLTest, AskFalse) {
+    rdf::Statement stmt = rdf::Statement(rdf::URI("http://example.com/s1"),
+                                         rdf::URI("http://example.com/p1"),
+                                         rdf::URI("http://example.com/o1"));
+    SparqlService svc(std::unique_ptr<TripleSource>(new MockTripleSource({stmt})));
+
+    EXPECT_FALSE(svc.AskQuery("ASK { <http://example.com/s2> ?p ?o}", base_uri));
+}
+
+
 }  // namespace sparql
 }  // namespace marmotta
\ No newline at end of file


[12/50] [abbrv] marmotta git commit: more testing

Posted by wi...@apache.org.
more testing


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/54873330
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/54873330
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/54873330

Branch: refs/heads/MARMOTTA-584
Commit: 54873330a87ff5008d52fa629d88bc733e909443
Parents: 622a300
Author: Sebastian Schaffert <ss...@apache.org>
Authored: Sat Dec 19 16:54:17 2015 +0100
Committer: Sebastian Schaffert <ss...@apache.org>
Committed: Sat Dec 19 16:54:17 2015 +0100

----------------------------------------------------------------------
 libraries/ostrich/backend/test/PersistenceTest.cc | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/54873330/libraries/ostrich/backend/test/PersistenceTest.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/test/PersistenceTest.cc b/libraries/ostrich/backend/test/PersistenceTest.cc
index fdfc604..1b2cfb2 100644
--- a/libraries/ostrich/backend/test/PersistenceTest.cc
+++ b/libraries/ostrich/backend/test/PersistenceTest.cc
@@ -112,8 +112,8 @@ TEST_F(PersistenceTest, TestGetStatements) {
     EXPECT_FALSE(it2->hasNext());
 
     rdf::Statement pattern3;
-    pattern2.setPredicate(rdf::URI("http://example.com/p1"));
-    auto it3 = db->GetStatements(pattern2.getMessage());
+    pattern3.setPredicate(rdf::URI("http://example.com/p1"));
+    auto it3 = db->GetStatements(pattern3.getMessage());
     for (int i=0; i<2; i++) {
         ASSERT_TRUE(it3->hasNext());
         EXPECT_THAT(stmts, Contains(it3->next()));


[46/50] [abbrv] marmotta git commit: MARMOTTA-636: updated documentation

Posted by wi...@apache.org.
MARMOTTA-636: updated documentation


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/0bcd0297
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/0bcd0297
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/0bcd0297

Branch: refs/heads/MARMOTTA-584
Commit: 0bcd0297057f6fdd617e26a6fa25ecf7565bfa7b
Parents: 1eb1bce
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Fri Apr 29 15:51:38 2016 +0200
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Fri Apr 29 15:51:38 2016 +0200

----------------------------------------------------------------------
 launchers/marmotta-webapp/README.md | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/0bcd0297/launchers/marmotta-webapp/README.md
----------------------------------------------------------------------
diff --git a/launchers/marmotta-webapp/README.md b/launchers/marmotta-webapp/README.md
index 9bf8f86..b3bdd21 100644
--- a/launchers/marmotta-webapp/README.md
+++ b/launchers/marmotta-webapp/README.md
@@ -24,11 +24,13 @@ and you can find the `.deb` file under `target/`.
 
 It also comes with support for creating a Docker images that you can user for developing or testing:
 
-* Build the launcher: `mvn package`
-* Build image: `docker build -t marmotta .`
-* Run the container: `docker run -p 8080:8080 marmotta`
-* Access Marmotta at [localhost:8080/marmotta](http://localhost:8080/marmotta) (IP address may be different, 
-  see point bellow).
+1. Locate at the root of the source repository
+2. Build image: `docker build -t marmotta .`
+3. Run the container: `docker run -p 8080:8080 marmotta`
+4. Access Marmotta at [localhost:8080/marmotta](http://localhost:8080/marmotta) (IP address may be different, see information bellow).
+
+An official images is [available from Docker Hub](https://hub.docker.com/r/apache/marmotta/) as an automated 
+build, so you just need to pull it from there to replace the second step above: `docker pull apache/marmotta`
 
 If you want to further work with the container, here some basic instructions:
 
@@ -46,5 +48,3 @@ If you want to further work with the container, here some basic instructions:
 
 For further instructions, please take a look to the [Docker User Guide](https://docs.docker.com/userguide/).
 
-@@TODO@@: push it to asf or docker hub
-


[39/50] [abbrv] marmotta git commit: MARMOTTA-634: added the right content

Posted by wi...@apache.org.
MARMOTTA-634: added the right content


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/aab258e6
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/aab258e6
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/aab258e6

Branch: refs/heads/MARMOTTA-584
Commit: aab258e6d2f9149ca40fb66912a8a2ce6613f51d
Parents: 3e90926
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Tue Apr 19 09:55:24 2016 +0200
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Tue Apr 19 09:55:24 2016 +0200

----------------------------------------------------------------------
 .../src/main/resources/web/admin/about.html     | 41 ++++++--------------
 1 file changed, 12 insertions(+), 29 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/aab258e6/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/about.html
----------------------------------------------------------------------
diff --git a/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/about.html b/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/about.html
index c6ad6bb..dc8bfa5 100644
--- a/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/about.html
+++ b/platform/backends/marmotta-backend-kiwi/src/main/resources/web/admin/about.html
@@ -20,41 +20,24 @@
 <html>
 <head>
     <!--###BEGIN_HEAD###-->
-    <title>Core Module</title>
+    <title>Storage Backend: KiWi</title>
     <!--###END_HEAD###-->
 </head>
 <body>
 <!--###BEGIN_CONTENT###-->
-<h1>Apache Marmotta</h1>
-<h2>
-    An Open Platform for Linked Data
-</h2>
-<p>The goal of Apache Marmotta is to provide an open implementation of a Linked Data Platform that can be used, extended, and deployed easily by organizations who want to publish Linked Data or build custom applications on Linked Data.</p>
-<p>You can find more information about the project and the supported features on <a href="http://marmotta.apache.org/">http://marmotta.apache.org</a>.</p>
-<h2>
-    Links to common features
-</h2>
-<p>You can find all installed features on the module list on the right side. To get a quick access to common functionalities, we listed some links:</p>
-<ul>
-    <li><a href="../../core/admin/import.html">Import your data:</a> RDF and non-RDF formats are supported.</li>
-    <li><a href="../../sparql/admin/squebi.html">SPARQL your data:</a> full SPARQL 1.1 support including querying and updates.</li>
-    <li><a href="configuration.html">Configure your database:</a> Marmotta comes with h2 embedded; configure your own database to handle bigger data.</li>
-    <li><a href="dataview.html">Control your data:</a> the dataview gives an overview on the current data in the system. (Attention: there might be problems with the visualisation if big data sets).</li>
-    <li><a href="../../user/admin/users.html">Manage your user accounts:</a> the user module allows creating and managing user accounts.</li>
-    <li><a href="tasks.html">Inspect your tasks:</a> check the status of the running tasks.</li>
-</ul>
+<h1>Storage Backend: KiWi</h1>
 
-<h2>Marmotta Modules</h2>
-<p>Apache Marmotta provides some modules:</p>
+<p>
+  This module allows to use the <a href="http://marmotta.apache.org/kiwi">KiWi Triplestore</a>
+  as storage backend for <a href="../../core/admin/about.html">Apache Marmotta</a>.
+</p>
+
+<h2>Options</h2>
+<p>The KiWi backend for Apache Marmotta provides the follwing options:</p>
 <dl>
-    <dt><a href="../../core/admin/about.html">Core</a></dt> <dd>provides the core RDF and Linked Data Platform capabilities.</dd>
-    <dt><a href="../../sparql/admin/about.html">SPARQL</a></dt> <dd>offers query capabilities for the triplestore.</dd>
-    <dt><a href="../../ldpath/admin/about.html">LDPath Querying</a></dt> <dd>provides support for LDPath within the platform.</dd>
-    <dt><a href="../../cache/admin/about.html">Linked Data Caching</a></dt> <dd>provides transparent mechanism to cache Web resources.</dd>
-    <dt><a href="../../reasoner/admin/about.html">Reasoner</a></dt> <dd>adds a rule-based reasoner to the triple store.</dd>
-    <dt><a href="../../security/admin/about.html">Security</a></dt> <dd>implements security mechanism.</dd>
-    <dt><a href="../../user/me.html">User</a></dt> <dd>provides the user management features.</dd>
-    <dt><a href="../../versioning/admin/about.html">Versioning</a></dt> <dd>offers versioning services on top of the triple store.</dd>
+    <dt><a href="configuration.html">Configuration</a></dt> <dd>configure the options offered</dd>
+    <dt><a href="database.html">Database</a></dt> <dd>configure the database</dd>
+    <dt><a href="console.html">Console</a></dt> <dd>manage Marmotta database</dd>
 </dl>
 <!--###END_CONTENT###-->
 </body>


[28/50] [abbrv] marmotta git commit: - support SPARQL graph queries in ostrich - cleanups

Posted by wi...@apache.org.
- support SPARQL graph queries in ostrich
- cleanups


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/e764c2bd
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/e764c2bd
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/e764c2bd

Branch: refs/heads/MARMOTTA-584
Commit: e764c2bd0edf0f1778f888e016c2cf1711565c3f
Parents: 0b07a02
Author: Sebastian Schaffert <ss...@apache.org>
Authored: Sat Feb 13 14:38:11 2016 +0100
Committer: Sebastian Schaffert <ss...@apache.org>
Committed: Sat Feb 13 14:38:11 2016 +0100

----------------------------------------------------------------------
 libraries/ostrich/backend/CMakeLists.txt        |   2 +-
 libraries/ostrich/backend/client/client.cc      |  32 ++++++
 libraries/ostrich/backend/parser/CMakeLists.txt |   4 +-
 libraries/ostrich/backend/parser/rdf_parser.cc  |  73 +-----------
 .../backend/persistence/leveldb_service.cc      |  37 +++++-
 .../backend/persistence/leveldb_service.h       |   4 +
 .../backend/serializer/serializer_raptor.cc     |   2 +-
 libraries/ostrich/backend/service/sparql.proto  |   4 +
 libraries/ostrich/backend/sparql/CMakeLists.txt |   3 +-
 .../ostrich/backend/sparql/rasqal_adapter.cc    |  63 ++++++++--
 .../ostrich/backend/sparql/rasqal_adapter.h     |  15 ++-
 libraries/ostrich/backend/sparql/rasqal_model.h |   1 -
 libraries/ostrich/backend/test/SparqlTest.cc    |  50 ++++++--
 libraries/ostrich/backend/util/CMakeLists.txt   |   5 +-
 libraries/ostrich/backend/util/raptor_util.cc   | 115 +++++++++++++++++++
 libraries/ostrich/backend/util/raptor_util.h    |  74 ++++++++++++
 libraries/ostrich/backend/util/time_logger.cc   |  17 +++
 libraries/ostrich/backend/util/time_logger.h    |  32 ++++++
 18 files changed, 433 insertions(+), 100 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/e764c2bd/libraries/ostrich/backend/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/CMakeLists.txt b/libraries/ostrich/backend/CMakeLists.txt
index 61156a5..5a8f110 100644
--- a/libraries/ostrich/backend/CMakeLists.txt
+++ b/libraries/ostrich/backend/CMakeLists.txt
@@ -17,7 +17,7 @@ find_package (GLog REQUIRED)
 find_package (Boost 1.54.0 COMPONENTS iostreams filesystem system)
 find_package (Tcmalloc)
 
-add_definitions(-DNDEBUG)
+#add_definitions(-DNDEBUG)
 
 if (Boost_IOSTREAMS_FOUND)
     message(STATUS "Enabling gzip/bzip2 support (Boost iostreams found)")

http://git-wip-us.apache.org/repos/asf/marmotta/blob/e764c2bd/libraries/ostrich/backend/client/client.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/client/client.cc b/libraries/ostrich/backend/client/client.cc
index 396389e..b4a5178 100644
--- a/libraries/ostrich/backend/client/client.cc
+++ b/libraries/ostrich/backend/client/client.cc
@@ -37,6 +37,7 @@
 #include <google/protobuf/wrappers.pb.h>
 
 #include <gflags/gflags.h>
+#include <glog/logging.h>
 
 #include "model/rdf_model.h"
 #include "parser/rdf_parser.h"
@@ -195,6 +196,25 @@ class MarmottaClient {
         delete out_;
     }
 
+    void graphQuery(const std::string& query, std::ostream &out, serializer::Format format) {
+        ClientContext context;
+        spq::SparqlRequest request;
+        request.set_query(query);
+
+        std::unique_ptr<ClientReader<rdf::proto::Statement>> reader(
+                sparql_->GraphQuery(&context, request));
+
+        StatementReader it(reader.get());
+
+        try {
+            serializer::Serializer serializer("http://www.example.com", format);
+            serializer.serialize(it, out);
+        } catch(serializer::SerializationError e) {
+            LOG(FATAL) << "Serialization error: " << e.getMessage();
+        }
+    }
+
+
     void listNamespaces(std::ostream &out) {
         ClientContext context;
 
@@ -240,6 +260,8 @@ DEFINE_bool(bzip2, false, "Input files are bzip2 compressed.");
 int main(int argc, char** argv) {
     GOOGLE_PROTOBUF_VERIFY_VERSION;
 
+    // Initialize Google's logging library.
+    google::InitGoogleLogging(argv[0]);
     google::ParseCommandLineFlags(&argc, &argv, true);
 
     MarmottaClient client(FLAGS_host + ":" + FLAGS_port);
@@ -286,6 +308,16 @@ int main(int argc, char** argv) {
         }
     }
 
+    if ("construct" == std::string(argv[1])) {
+        std::string query = argv[2];
+        if (FLAGS_output != "") {
+            std::ofstream out(FLAGS_output);
+            client.graphQuery(query, out, serializer::FormatFromString(FLAGS_format));
+        } else {
+            client.graphQuery(query, std::cout, serializer::FormatFromString(FLAGS_format));
+        }
+    }
+
     if ("delete" == std::string(argv[1])) {
         rdf::proto::Statement query;
         TextFormat::ParseFromString(argv[2], &query);

http://git-wip-us.apache.org/repos/asf/marmotta/blob/e764c2bd/libraries/ostrich/backend/parser/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/parser/CMakeLists.txt b/libraries/ostrich/backend/parser/CMakeLists.txt
index 3ed5634..e698690 100644
--- a/libraries/ostrich/backend/parser/CMakeLists.txt
+++ b/libraries/ostrich/backend/parser/CMakeLists.txt
@@ -1,4 +1,6 @@
 include_directories(.. ${CMAKE_CURRENT_BINARY_DIR}/..)
 
 add_library(marmotta_parser rdf_parser.h rdf_parser.cc)
-target_link_libraries(marmotta_parser marmotta_model ${CMAKE_THREAD_LIBS_INIT} ${RAPTOR_LIBRARY})
\ No newline at end of file
+target_link_libraries(
+        marmotta_parser marmotta_model marmotta_raptor_util
+        ${CMAKE_THREAD_LIBS_INIT} ${RAPTOR_LIBRARY} ${GLOG_LIBRARY})
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/marmotta/blob/e764c2bd/libraries/ostrich/backend/parser/rdf_parser.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/parser/rdf_parser.cc b/libraries/ostrich/backend/parser/rdf_parser.cc
index 4706e8b..cf2dc4d 100644
--- a/libraries/ostrich/backend/parser/rdf_parser.cc
+++ b/libraries/ostrich/backend/parser/rdf_parser.cc
@@ -15,8 +15,9 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#include <raptor2/raptor2.h>
 #include "rdf_parser.h"
+#include <raptor2/raptor2.h>
+#include <util/raptor_util.h>
 
 namespace marmotta {
 namespace parser {
@@ -67,75 +68,7 @@ Parser::~Parser() {
 
 void Parser::raptor_stmt_handler(void *user_data, raptor_statement *statement) {
     Parser* p = static_cast<Parser*>(user_data);
-
-    rdf::Resource subject; rdf::URI predicate; rdf::Value object; rdf::Resource context;
-    switch (statement->subject->type) {
-        case RAPTOR_TERM_TYPE_URI:
-            subject = rdf::URI((const char*)raptor_uri_as_string(statement->subject->value.uri));
-            break;
-        case RAPTOR_TERM_TYPE_BLANK:
-            subject = rdf::BNode(std::string((const char*)statement->subject->value.blank.string, statement->subject->value.blank.string_len));
-            break;
-        default:
-            raptor_parser_parse_abort(p->parser);
-            throw ParseError("invalid subject term type");
-    }
-
-    switch (statement->predicate->type) {
-        case RAPTOR_TERM_TYPE_URI:
-            predicate = rdf::URI((const char*)raptor_uri_as_string(statement->predicate->value.uri));
-            break;
-        default:
-            raptor_parser_parse_abort(p->parser);
-            throw ParseError("invalid predicate term type");
-    }
-
-    switch (statement->object->type) {
-        case RAPTOR_TERM_TYPE_URI:
-            object = rdf::URI((const char*)raptor_uri_as_string(statement->object->value.uri));
-            break;
-        case RAPTOR_TERM_TYPE_BLANK:
-            object = rdf::BNode(std::string((const char*)statement->object->value.blank.string, statement->object->value.blank.string_len));
-            break;
-        case RAPTOR_TERM_TYPE_LITERAL:
-            if(statement->object->value.literal.language != NULL) {
-                object = rdf::StringLiteral(
-                        std::string((const char*)statement->object->value.literal.string, statement->object->value.literal.string_len),
-                        std::string((const char*)statement->object->value.literal.language, statement->object->value.literal.language_len)
-                );
-            } else if(statement->object->value.literal.datatype != NULL) {
-                object = rdf::DatatypeLiteral(
-                        std::string((const char*)statement->object->value.literal.string, statement->object->value.literal.string_len),
-                        rdf::URI((const char*)raptor_uri_as_string(statement->object->value.literal.datatype))
-                );
-            } else {
-                object = rdf::StringLiteral(
-                        std::string((const char*)statement->object->value.literal.string, statement->object->value.literal.string_len)
-                );
-            }
-            break;
-        default:
-            raptor_parser_parse_abort(p->parser);
-            throw ParseError("invalid object term type");
-    }
-
-    if (statement->graph != NULL) {
-        switch (statement->graph->type) {
-            case RAPTOR_TERM_TYPE_URI:
-                context = rdf::URI((const char*)raptor_uri_as_string(statement->graph->value.uri));
-                break;
-            case RAPTOR_TERM_TYPE_BLANK:
-                context = rdf::BNode(std::string((const char*)statement->graph->value.blank.string, statement->graph->value.blank.string_len));
-                break;
-            default:
-                raptor_parser_parse_abort(p->parser);
-                throw ParseError("invalid graph term type");
-        }
-    } else {
-        context = rdf::URI();
-    }
-
-    p->stmt_handler(rdf::Statement(subject, predicate, object, context));
+    p->stmt_handler(util::raptor::ConvertStatement(statement));
 }
 
 

http://git-wip-us.apache.org/repos/asf/marmotta/blob/e764c2bd/libraries/ostrich/backend/persistence/leveldb_service.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/persistence/leveldb_service.cc b/libraries/ostrich/backend/persistence/leveldb_service.cc
index c11b002..5ea08a1 100644
--- a/libraries/ostrich/backend/persistence/leveldb_service.cc
+++ b/libraries/ostrich/backend/persistence/leveldb_service.cc
@@ -20,8 +20,8 @@
 
 #include <unordered_set>
 #include <model/rdf_operators.h>
-#include <util/iterator.h>
 #include <util/unique.h>
+#include <util/time_logger.h>
 
 using grpc::Status;
 using grpc::StatusCode;
@@ -119,6 +119,7 @@ grpc::Status LevelDBService::GetNamespaces(
 
 Status LevelDBService::AddStatements(
         ServerContext* context, ServerReader<Statement>* reader, Int64Value* result) {
+    util::TimeLogger timeLogger("Adding statements");
 
     auto it = StatementIterator(reader);
     int64_t count = persistence->AddStatements(it);
@@ -130,6 +131,7 @@ Status LevelDBService::AddStatements(
 
 Status LevelDBService::GetStatements(
         ServerContext* context, const Statement* pattern, ServerWriter<Statement>* result) {
+    util::TimeLogger timeLogger("Retrieving statements");
 
     persistence->GetStatements(*pattern, [&result](const Statement& stmt) -> bool {
         return result->Write(stmt);
@@ -140,6 +142,7 @@ Status LevelDBService::GetStatements(
 
 Status LevelDBService::RemoveStatements(
         ServerContext* context, const Statement* pattern, Int64Value* result) {
+    util::TimeLogger timeLogger("Removing statements");
 
     int64_t count = persistence->RemoveStatements(*pattern);
     result->set_value(count);
@@ -149,7 +152,7 @@ Status LevelDBService::RemoveStatements(
 
 Status LevelDBService::Clear(
         ServerContext* context, const ContextRequest* contexts, Int64Value* result) {
-
+    util::TimeLogger timeLogger("Clearing contexts");
 
     int64_t count = 0;
 
@@ -169,6 +172,7 @@ Status LevelDBService::Clear(
 
 Status LevelDBService::Size(
         ServerContext* context, const ContextRequest* contexts, Int64Value* result) {
+    util::TimeLogger timeLogger("Computing context size");
 
     int64_t count = 0;
 
@@ -194,6 +198,8 @@ Status LevelDBService::Size(
 
 grpc::Status LevelDBService::GetContexts(
         ServerContext *context, const Empty *ignored, ServerWriter<Resource> *result) {
+    util::TimeLogger timeLogger("Retrieving contexts");
+
     // Currently we need to iterate over all statements and collect the results.
     Statement pattern;
     std::unordered_set<Resource> contexts;
@@ -214,6 +220,7 @@ grpc::Status LevelDBService::GetContexts(
 grpc::Status LevelDBService::Update(grpc::ServerContext *context,
                                     grpc::ServerReader<service::proto::UpdateRequest> *reader,
                                     service::proto::UpdateResponse *result) {
+    util::TimeLogger timeLogger("Updating database");
 
     auto it = UpdateIterator(reader);
     persistence::UpdateStatistics stats = persistence->Update(it);
@@ -233,19 +240,39 @@ grpc::Status LevelDBSparqlService::TupleQuery(
 
     SparqlService svc(util::make_unique<LevelDBTripleSource>(persistence));
 
-    svc.TupleQuery(query->query(), [&result](const SparqlService::RowType& row) {
+    rdf::URI base_uri = query->base_uri();
+
+    svc.TupleQuery(query->query(), base_uri,
+                   [&result](const SparqlService::RowType& row) {
         spq::SparqlResponse response;
         for (auto it = row.cbegin(); it != row.cend(); it++) {
             auto b = response.add_binding();
             b->set_variable(it->first);
             *b->mutable_value() = it->second.getMessage();
         }
-        result->Write(response);
-        return true;
+        return result->Write(response);
     });
 
     return Status::OK;
 }
 
+
+grpc::Status LevelDBSparqlService::GraphQuery(grpc::ServerContext* context,
+                        const spq::SparqlRequest* query,
+                        grpc::ServerWriter<rdf::proto::Statement>* result) {
+
+    SparqlService svc(util::make_unique<LevelDBTripleSource>(persistence));
+
+    rdf::URI base_uri = query->base_uri();
+
+    svc.GraphQuery(query->query(), base_uri,
+                   [&result](const rdf::Statement& triple) {
+        return result->Write(triple.getMessage());
+    });
+
+    return Status::OK;
+}
+
+
 }  // namespace service
 }  // namespace marmotta
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/marmotta/blob/e764c2bd/libraries/ostrich/backend/persistence/leveldb_service.h
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/persistence/leveldb_service.h b/libraries/ostrich/backend/persistence/leveldb_service.h
index 0cf4df9..44056a3 100644
--- a/libraries/ostrich/backend/persistence/leveldb_service.h
+++ b/libraries/ostrich/backend/persistence/leveldb_service.h
@@ -110,6 +110,10 @@ class LevelDBSparqlService : public spq::SparqlService::Service {
     grpc::Status TupleQuery(grpc::ServerContext* context,
                             const spq::SparqlRequest* pattern,
                             grpc::ServerWriter<spq::SparqlResponse>* result) override;
+
+    grpc::Status GraphQuery(grpc::ServerContext* context,
+                            const spq::SparqlRequest* pattern,
+                            grpc::ServerWriter<rdf::proto::Statement>* result) override;
  private:
     persistence::LevelDBPersistence* persistence;
 };

http://git-wip-us.apache.org/repos/asf/marmotta/blob/e764c2bd/libraries/ostrich/backend/serializer/serializer_raptor.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/serializer/serializer_raptor.cc b/libraries/ostrich/backend/serializer/serializer_raptor.cc
index 551ecf2..ff37691 100644
--- a/libraries/ostrich/backend/serializer/serializer_raptor.cc
+++ b/libraries/ostrich/backend/serializer/serializer_raptor.cc
@@ -249,7 +249,7 @@ void RaptorSerializer::serialize(const rdf::Statement &stmt) {
         triple->graph = raptor_new_term_from_blank(
                 world, (unsigned char const *) stmt.getMessage().context().bnode().id().c_str());
     } else {
-        throw SerializationError("invalid context type");
+        triple->graph = nullptr;
     }
 
     raptor_serializer_serialize_statement(serializer, triple);

http://git-wip-us.apache.org/repos/asf/marmotta/blob/e764c2bd/libraries/ostrich/backend/service/sparql.proto
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/service/sparql.proto b/libraries/ostrich/backend/service/sparql.proto
index 892539b..6d75a5f 100644
--- a/libraries/ostrich/backend/service/sparql.proto
+++ b/libraries/ostrich/backend/service/sparql.proto
@@ -26,6 +26,7 @@ import "model.proto";
 // SPARQL request consisting of a single query string.
 message SparqlRequest {
     string query = 1;
+    marmotta.rdf.proto.URI base_uri = 2;
 }
 
 // SPARQL response row, containing a set of bindings.
@@ -42,4 +43,7 @@ message SparqlResponse {
 service SparqlService {
     // Execute a SPARQL 1.1 tuple query and stream back the results.
     rpc TupleQuery(SparqlRequest) returns (stream SparqlResponse);
+
+    // Execute a SPARQL 1.1 graph query and stream back the triples.
+    rpc GraphQuery(SparqlRequest) returns (stream marmotta.rdf.proto.Statement);
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/marmotta/blob/e764c2bd/libraries/ostrich/backend/sparql/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/sparql/CMakeLists.txt b/libraries/ostrich/backend/sparql/CMakeLists.txt
index 9bb00ef..89eb0d0 100644
--- a/libraries/ostrich/backend/sparql/CMakeLists.txt
+++ b/libraries/ostrich/backend/sparql/CMakeLists.txt
@@ -2,6 +2,7 @@ include_directories(.. ${CMAKE_CURRENT_BINARY_DIR}/.. ${RAPTOR_INCLUDE_DIR}/rapt
 
 add_library(marmotta_sparql
         rasqal_model.cc rasqal_model.h rasqal_adapter.cc rasqal_adapter.h)
-target_link_libraries(marmotta_sparql marmotta_model ${CMAKE_THREAD_LIBS_INIT}
+target_link_libraries(marmotta_sparql marmotta_model marmotta_util marmotta_raptor_util
+        ${CMAKE_THREAD_LIBS_INIT}
         ${PROTOBUF_LIBRARIES} ${GRPC_LIBRARIES}
         ${RASQAL_LIBRARIES} ${RAPTOR_LIBRARY} ${GLOG_LIBRARY})
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/marmotta/blob/e764c2bd/libraries/ostrich/backend/sparql/rasqal_adapter.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/sparql/rasqal_adapter.cc b/libraries/ostrich/backend/sparql/rasqal_adapter.cc
index c9c89a6..09e7bd6 100644
--- a/libraries/ostrich/backend/sparql/rasqal_adapter.cc
+++ b/libraries/ostrich/backend/sparql/rasqal_adapter.cc
@@ -24,6 +24,11 @@
 
 #include "sparql/rasqal_adapter.h"
 #include "sparql/rasqal_model.h"
+#include "util/raptor_util.h"
+#include "util/time_logger.h"
+
+// Rasqal notoriously uses unsigned strings, macro to convert C++ strings.
+#define STR(s) (const unsigned char*)s.c_str()
 
 namespace marmotta {
 namespace sparql {
@@ -247,13 +252,14 @@ SparqlService::~SparqlService() {
     rasqal_free_world(world);
 }
 
-void SparqlService::TupleQuery(const std::string& query, std::function<bool(const RowType&)> row_handler) {
-    auto start = std::chrono::steady_clock::now();
-    LOG(INFO) << "Starting SPARQL tuple query.";
+void SparqlService::TupleQuery(const std::string& query, const rdf::URI& base_uri,
+                               std::function<bool(const RowType&)> row_handler) {
+    util::TimeLogger timeLogger("SPARQL tuple query");
 
     auto q = rasqal_new_query(world, "sparql11-query", nullptr);
-    auto base = raptor_new_uri(rasqal_world_get_raptor(world), (const unsigned char*)"http://example.com");
-    if (rasqal_query_prepare(q, (const unsigned char*)query.c_str(), base) != 0) {
+    auto base = raptor_new_uri(rasqal_world_get_raptor(world),
+                               STR(base_uri.getUri()));
+    if (rasqal_query_prepare(q, STR(query), base) != 0) {
         raptor_free_uri(base);
         rasqal_free_query(q);
         throw SparqlException("Query preparation failed", query);
@@ -267,6 +273,13 @@ void SparqlService::TupleQuery(const std::string& query, std::function<bool(cons
         throw SparqlException("Query execution failed", query);
     }
 
+    if (!rasqal_query_results_is_bindings(r)) {
+        rasqal_free_query_results(r);
+        rasqal_free_query(q);
+        raptor_free_uri(base);
+        throw SparqlException("Query is not a tuple query", query);
+    }
+
     int rowcount = 0;
     while (next && rasqal_query_results_finished(r) == 0) {
         RowType row;
@@ -287,12 +300,48 @@ void SparqlService::TupleQuery(const std::string& query, std::function<bool(cons
     rasqal_free_query_results(r);
     rasqal_free_query(q);
     raptor_free_uri(base);
+}
+
+
+void SparqlService::GraphQuery(const std::string& query, const rdf::URI& base_uri,
+                               std::function<bool(const rdf::Statement&)> stmt_handler) {
+    util::TimeLogger timeLogger("SPARQL graph query");
 
-    LOG(INFO) << "SPARQL query finished (time=" << std::chrono::duration <double, std::milli> (
-            std::chrono::steady_clock::now() - start).count() << "ms).";
+    auto q = rasqal_new_query(world, "sparql11-query", nullptr);
+    auto base = raptor_new_uri(rasqal_world_get_raptor(world),
+                               STR(base_uri.getUri()));
+    if (rasqal_query_prepare(q, STR(query), base) != 0) {
+        raptor_free_uri(base);
+        rasqal_free_query(q);
+        throw SparqlException("Query preparation failed", query);
+    }
 
+    bool next = true;
+    auto r = rasqal_query_execute(q);
+    if (r == nullptr) {
+        raptor_free_uri(base);
+        rasqal_free_query(q);
+        throw SparqlException("Query execution failed", query);
+    }
+
+    if (!rasqal_query_results_is_graph(r)) {
+        rasqal_free_query_results(r);
+        rasqal_free_query(q);
+        raptor_free_uri(base);
+        throw SparqlException("Query is not a graph query", query);
+    }
+
+    while (next) {
+        next = stmt_handler(util::raptor::ConvertStatement(rasqal_query_results_get_triple(r)))
+            && rasqal_query_results_next_triple(r) == 0;
+    }
+
+    rasqal_free_query_results(r);
+    rasqal_free_query(q);
+    raptor_free_uri(base);
 }
 
+
 }  // namespace sparql
 }  // namespace marmotta
 

http://git-wip-us.apache.org/repos/asf/marmotta/blob/e764c2bd/libraries/ostrich/backend/sparql/rasqal_adapter.h
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/sparql/rasqal_adapter.h b/libraries/ostrich/backend/sparql/rasqal_adapter.h
index 48ce127..32e82d2 100644
--- a/libraries/ostrich/backend/sparql/rasqal_adapter.h
+++ b/libraries/ostrich/backend/sparql/rasqal_adapter.h
@@ -35,7 +35,6 @@ using StatementIterator = util::CloseableIterator<rdf::Statement>;
  */
 class TripleSource {
  public:
-
     /**
      * Check for presence of a complete statement.
      *
@@ -85,7 +84,19 @@ class SparqlService {
      */
     ~SparqlService();
 
-    void TupleQuery(const std::string& query, std::function<bool(const RowType&)> row_handler);
+    /**
+     * Execute a tuple (SELECT) query, calling the row handler for each set of
+     * variable bindings.
+     */
+    void TupleQuery(const std::string& query, const rdf::URI& base_uri,
+                    std::function<bool(const RowType&)> row_handler);
+
+    /**
+     * Execute a graph (CONSTRUCT) query, calling the statement handler for
+     * each triple.
+     */
+    void GraphQuery(const std::string& query, const rdf::URI& base_uri,
+                    std::function<bool(const rdf::Statement&)> stmt_handler);
 
     /**
      * Return a reference to the triple source managed by this service.

http://git-wip-us.apache.org/repos/asf/marmotta/blob/e764c2bd/libraries/ostrich/backend/sparql/rasqal_model.h
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/sparql/rasqal_model.h b/libraries/ostrich/backend/sparql/rasqal_model.h
index 549b3c4..6547c19 100644
--- a/libraries/ostrich/backend/sparql/rasqal_model.h
+++ b/libraries/ostrich/backend/sparql/rasqal_model.h
@@ -66,7 +66,6 @@ rasqal_literal* AsLiteral(rasqal_world* world, const rdf::Value& v);
  */
 rasqal_literal* AsLiteral(rasqal_world* world, const rdf::URI& u);
 
-
 }  // namespace rasqal
 }  // namespace sparql
 }  // namespace marmotta

http://git-wip-us.apache.org/repos/asf/marmotta/blob/e764c2bd/libraries/ostrich/backend/test/SparqlTest.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/test/SparqlTest.cc b/libraries/ostrich/backend/test/SparqlTest.cc
index 356e43f..0f663f5 100644
--- a/libraries/ostrich/backend/test/SparqlTest.cc
+++ b/libraries/ostrich/backend/test/SparqlTest.cc
@@ -11,14 +11,16 @@ namespace sparql {
 
 namespace {
 
+const rdf::URI base_uri("http://example.com/");
+
+
 using MockStatementIterator = util::CollectionIterator<rdf::Statement>;
 
 class MockTripleSource : public TripleSource {
 
  public:
-    MockTripleSource(std::vector<rdf::Statement> statements) : statements(statements) {
-
-    }
+    MockTripleSource(std::vector<rdf::Statement> statements)
+            : statements(statements) { }
 
     bool HasStatement(const rdf::Resource *s, const rdf::URI *p, const rdf::Value *o, const rdf::Resource *c) override {
         for (const auto& stmt : statements) {
@@ -68,6 +70,7 @@ class MockTripleSource : public TripleSource {
 
  private:
     std::vector<rdf::Statement> statements;
+
 };
 }  // namespace
 
@@ -81,7 +84,8 @@ TEST(SPARQLTest, Simple) {
 
     int count = 0;
     rdf::Value s, p, o;
-    svc.TupleQuery("SELECT * WHERE {?s ?p ?o}", [&](const SparqlService::RowType& row) {
+    svc.TupleQuery("SELECT * WHERE {?s ?p ?o}", base_uri,
+                   [&](const SparqlService::RowType& row) {
         count++;
         s = row.at("s");
         p = row.at("p");
@@ -106,7 +110,8 @@ TEST(SPARQLTest, SubjectPattern) {
 
     int count = 0;
     rdf::Value p, o;
-    svc.TupleQuery("SELECT * WHERE {<http://example.com/s1> ?p ?o}", [&](const SparqlService::RowType& row) {
+    svc.TupleQuery("SELECT * WHERE {<http://example.com/s1> ?p ?o}", base_uri,
+                   [&](const SparqlService::RowType& row) {
         count++;
         p = row.at("p");
         o = row.at("o");
@@ -129,7 +134,8 @@ TEST(SPARQLTest, PredicatePattern) {
 
     int count = 0;
     rdf::Value s, o;
-    svc.TupleQuery("SELECT * WHERE {?s <http://example.com/p1> ?o}", [&](const SparqlService::RowType& row) {
+    svc.TupleQuery("SELECT * WHERE {?s <http://example.com/p1> ?o}", base_uri,
+                   [&](const SparqlService::RowType& row) {
         count++;
         s = row.at("s");
         o = row.at("o");
@@ -152,7 +158,8 @@ TEST(SPARQLTest, ObjectPattern) {
 
     int count = 0;
     rdf::Value s, p;
-    svc.TupleQuery("SELECT * WHERE {?s ?p <http://example.com/o1>}", [&](const SparqlService::RowType& row) {
+    svc.TupleQuery("SELECT * WHERE {?s ?p <http://example.com/o1>}", base_uri,
+                   [&](const SparqlService::RowType& row) {
         count++;
         s = row.at("s");
         p = row.at("p");
@@ -175,7 +182,8 @@ TEST(SPARQLTest, BNode) {
 
     int count = 0;
     rdf::Value s, p;
-    svc.TupleQuery("SELECT * WHERE {?s ?p <http://example.com/o1>}", [&](const SparqlService::RowType& row) {
+    svc.TupleQuery("SELECT * WHERE {?s ?p <http://example.com/o1>}", base_uri,
+                   [&](const SparqlService::RowType& row) {
         count++;
         s = row.at("s");
         p = row.at("p");
@@ -198,7 +206,8 @@ TEST(SPARQLTest, Filter) {
 
     int count = 0;
     rdf::Value s, p, o;
-    svc.TupleQuery("SELECT * WHERE {?s ?p ?o . FILTER(?o = <http://example.com/o1>)}", [&](const SparqlService::RowType& row) {
+    svc.TupleQuery("SELECT * WHERE {?s ?p ?o . FILTER(?o = <http://example.com/o1>)}", base_uri,
+                   [&](const SparqlService::RowType& row) {
         count++;
         s = row.at("s");
         p = row.at("p");
@@ -223,7 +232,8 @@ TEST(SPARQLTest, Join) {
 
     int count = 0;
     rdf::Value s, o;
-    svc.TupleQuery("SELECT * WHERE {?s ?p1 ?o1 . ?o1 ?p2 ?o }", [&](const SparqlService::RowType& row) {
+    svc.TupleQuery("SELECT * WHERE {?s ?p1 ?o1 . ?o1 ?p2 ?o }", base_uri,
+                   [&](const SparqlService::RowType& row) {
         count++;
         s = row.at("s");
         o = row.at("o");
@@ -236,6 +246,26 @@ TEST(SPARQLTest, Join) {
     EXPECT_EQ("http://example.com/o2", o.stringValue());
 }
 
+TEST(SPARQLTest, Graph) {
+    rdf::Statement stmt = rdf::Statement(rdf::URI("http://example.com/s1"),
+                                         rdf::URI("http://example.com/p1"),
+                                         rdf::URI("http://example.com/o1"));
+    SparqlService svc(std::unique_ptr<TripleSource>(new MockTripleSource({stmt})));
+
+    int count = 0;
+    rdf::Value s, p, o;
+    svc.GraphQuery("CONSTRUCT { ?s ?p ?o . } WHERE {?s ?p ?o}", base_uri,
+                   [&](const rdf::Statement& row) {
+        count++;
+
+        EXPECT_EQ(stmt, row);
+
+        return true;
+    });
+
+    EXPECT_EQ(1, count);
+}
+
 
 }  // namespace sparql
 }  // namespace marmotta
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/marmotta/blob/e764c2bd/libraries/ostrich/backend/util/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/util/CMakeLists.txt b/libraries/ostrich/backend/util/CMakeLists.txt
index ac87cd8..73710ec 100644
--- a/libraries/ostrich/backend/util/CMakeLists.txt
+++ b/libraries/ostrich/backend/util/CMakeLists.txt
@@ -1,3 +1,6 @@
 include_directories(.. ${CMAKE_CURRENT_BINARY_DIR}/..)
 
-add_library(marmotta_util murmur3.cc murmur3.h split.cc split.h iterator.h unique.h)
\ No newline at end of file
+add_library(marmotta_util murmur3.cc murmur3.h split.cc split.h iterator.h unique.h time_logger.cc time_logger.h)
+
+add_library(marmotta_raptor_util raptor_util.h raptor_util.cc)
+target_link_libraries(marmotta_raptor_util marmotta_model ${CMAKE_THREAD_LIBS_INIT} ${RAPTOR_LIBRARY})
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/marmotta/blob/e764c2bd/libraries/ostrich/backend/util/raptor_util.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/util/raptor_util.cc b/libraries/ostrich/backend/util/raptor_util.cc
new file mode 100644
index 0000000..bbeaecd
--- /dev/null
+++ b/libraries/ostrich/backend/util/raptor_util.cc
@@ -0,0 +1,115 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+#include "raptor_util.h"
+#include <glog/logging.h>
+
+namespace marmotta {
+namespace util {
+namespace raptor {
+
+// Helper macros. Some Rasqal functions copy the input string themselves, others don't.
+#define STR(s) (const unsigned char*)s.c_str()
+#define CPSTR(s) (const unsigned char*)strdup(s.c_str())
+
+rdf::Resource ConvertResource(raptor_term *node) {
+    if (node == nullptr) {
+        return rdf::Resource();
+    }
+
+    switch (node->type) {
+        case RAPTOR_TERM_TYPE_URI:
+            return rdf::URI(std::string((const char*)raptor_uri_as_string(node->value.uri)));
+        case RAPTOR_TERM_TYPE_BLANK:
+            return rdf::BNode(std::string((const char*)node->value.blank.string,
+                                          node->value.blank.string_len));
+        default:
+            LOG(INFO) << "Error: unsupported resource type " << node->type;
+            return rdf::Resource();
+    }
+}
+
+
+rdf::Value ConvertValue(raptor_term *node) {
+    if (node == nullptr) {
+        return rdf::Value();
+    }
+
+    switch (node->type) {
+        case RAPTOR_TERM_TYPE_URI:
+            return rdf::URI((const char*)raptor_uri_as_string(node->value.uri));
+        case RAPTOR_TERM_TYPE_BLANK:
+            return rdf::BNode(std::string((const char*)node->value.blank.string,
+                                          node->value.blank.string_len));
+        case RAPTOR_TERM_TYPE_LITERAL:
+            if(node->value.literal.language != nullptr) {
+                return rdf::StringLiteral(
+                        std::string((const char*)node->value.literal.string, node->value.literal.string_len),
+                        std::string((const char*)node->value.literal.language, node->value.literal.language_len)
+                );
+            } else if(node->value.literal.datatype != nullptr) {
+                return rdf::DatatypeLiteral(
+                        std::string((const char*)node->value.literal.string, node->value.literal.string_len),
+                        rdf::URI((const char*)raptor_uri_as_string(node->value.literal.datatype))
+                );
+            } else {
+                return rdf::StringLiteral(
+                        std::string((const char*)node->value.literal.string, node->value.literal.string_len)
+                );
+            }
+        default:
+            LOG(INFO) << "Error: unsupported node type " << node->type;
+            return rdf::Value();
+    }
+}
+
+
+rdf::URI ConvertURI(raptor_term *node) {
+    if (node == nullptr) {
+        return rdf::URI();
+    }
+
+    switch (node->type) {
+        case RAPTOR_TERM_TYPE_URI:
+            return rdf::URI((const char*)raptor_uri_as_string(node->value.uri));
+        default:
+            return rdf::URI();
+    }
+}
+
+
+rdf::Statement ConvertStatement(raptor_statement *triple) {
+    if (triple->graph != nullptr) {
+        return rdf::Statement(
+                ConvertResource(triple->subject),
+                ConvertURI(triple->predicate),
+                ConvertValue(triple->object),
+                ConvertResource(triple->graph)
+        );
+    } else {
+        return rdf::Statement(
+                ConvertResource(triple->subject),
+                ConvertURI(triple->predicate),
+                ConvertValue(triple->object)
+        );
+
+    }
+}
+}  // namespace raptor
+}  // namespace util
+}  // namespace marmotta
+

http://git-wip-us.apache.org/repos/asf/marmotta/blob/e764c2bd/libraries/ostrich/backend/util/raptor_util.h
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/util/raptor_util.h b/libraries/ostrich/backend/util/raptor_util.h
new file mode 100644
index 0000000..1899235
--- /dev/null
+++ b/libraries/ostrich/backend/util/raptor_util.h
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+#ifndef MARMOTTA_RAPTOR_MODEL_H
+#define MARMOTTA_RAPTOR_MODEL_H
+
+#include <memory>
+#include <raptor2/raptor2.h>
+
+#include "model/rdf_model.h"
+
+namespace marmotta {
+namespace util {
+namespace raptor {
+
+/*
+ * Convert a raptor term into a Marmotta Resource. Returns empty in case
+ * the node cannot be converted.
+ */
+rdf::Resource ConvertResource(raptor_term* node);
+
+/*
+ * Convert a raptor term into a Marmotta Value. Returns empty in case
+ * the node cannot be converted.
+ */
+rdf::Value ConvertValue(raptor_term* node);
+
+/*
+ * Convert a raptor term into a Marmotta URI. Returns empty in case
+ * the node cannot be converted.
+ */
+rdf::URI ConvertURI(raptor_term* node);
+
+/*
+ * Convert a raptor triple into a Marmotta Statement. Returns empty in case
+ * the node cannot be converted.
+ */
+rdf::Statement ConvertStatement(raptor_statement* triple);
+
+/*
+ * Convert a Marmotta Resource into a raptor term.
+ */
+raptor_term* AsLiteral(raptor_world* world, const rdf::Resource& r);
+
+/*
+ * Convert a Marmotta Value into a raptor term.
+ */
+raptor_term* AsLiteral(raptor_world* world, const rdf::Value& v);
+
+/*
+ * Convert a Marmotta URI into a raptor term.
+ */
+raptor_term* AsLiteral(raptor_world* world, const rdf::URI& u);
+
+}  // namespace raptor
+}  // namespace util
+}  // namespace marmotta
+
+
+#endif //MARMOTTA_RAPTOR_MODEL_H

http://git-wip-us.apache.org/repos/asf/marmotta/blob/e764c2bd/libraries/ostrich/backend/util/time_logger.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/util/time_logger.cc b/libraries/ostrich/backend/util/time_logger.cc
new file mode 100644
index 0000000..e836b61
--- /dev/null
+++ b/libraries/ostrich/backend/util/time_logger.cc
@@ -0,0 +1,17 @@
+//
+// Created by wastl on 13.02.16.
+//
+
+#include <glog/logging.h>
+#include "time_logger.h"
+
+marmotta::util::TimeLogger::TimeLogger(const std::string &name)
+        : start_(std::chrono::steady_clock::now())
+        , name_(name) {
+    LOG(INFO) << name << " started.";
+}
+
+marmotta::util::TimeLogger::~TimeLogger() {
+    LOG(INFO) << name_ << " finished (time=" << std::chrono::duration <double, std::milli> (
+            std::chrono::steady_clock::now() - start_).count() << "ms).";
+}

http://git-wip-us.apache.org/repos/asf/marmotta/blob/e764c2bd/libraries/ostrich/backend/util/time_logger.h
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/util/time_logger.h b/libraries/ostrich/backend/util/time_logger.h
new file mode 100644
index 0000000..cf1929b
--- /dev/null
+++ b/libraries/ostrich/backend/util/time_logger.h
@@ -0,0 +1,32 @@
+//
+// Created by wastl on 13.02.16.
+//
+
+#ifndef MARMOTTA_TIME_LOGGER_H
+#define MARMOTTA_TIME_LOGGER_H
+
+#include <string>
+#include <chrono>
+
+namespace marmotta {
+namespace util {
+
+/**
+ * A time logger, writes a logging message when initialised and timing
+ * information when destructed.
+ */
+class TimeLogger {
+ public:
+    TimeLogger(const std::string& name);
+
+    ~TimeLogger();
+
+ private:
+    std::string name_;
+    std::chrono::time_point<std::chrono::steady_clock> start_;
+};
+
+}  // namespace util
+}  // namespace marmotta
+
+#endif //MARMOTTA_TIME_LOGGER_H


[14/50] [abbrv] marmotta git commit: more tests, fixed some bugs discovered by tests

Posted by wi...@apache.org.
more tests, fixed some bugs discovered by tests


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/185c41a8
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/185c41a8
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/185c41a8

Branch: refs/heads/MARMOTTA-584
Commit: 185c41a85a64bf503f116b97f36d0c1ccc7231be
Parents: 0064d33
Author: Sebastian Schaffert <ss...@apache.org>
Authored: Sat Dec 19 18:50:53 2015 +0100
Committer: Sebastian Schaffert <ss...@apache.org>
Committed: Sat Dec 19 18:50:53 2015 +0100

----------------------------------------------------------------------
 libraries/ostrich/backend/model/rdf_model.h     |   8 +-
 .../ostrich/backend/test/PersistenceTest.cc     | 100 +++++++++++++++++++
 2 files changed, 104 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/185c41a8/libraries/ostrich/backend/model/rdf_model.h
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/model/rdf_model.h b/libraries/ostrich/backend/model/rdf_model.h
index ee5c5bb..6793f85 100644
--- a/libraries/ostrich/backend/model/rdf_model.h
+++ b/libraries/ostrich/backend/model/rdf_model.h
@@ -89,7 +89,7 @@ class Namespace {
     /**
      * Set the prefix used to identify this namespace.
      */
-    void setPrefix(std::string &prefix) {
+    void setPrefix(const std::string &prefix) {
         internal_.set_prefix(prefix);
     }
 
@@ -103,7 +103,7 @@ class Namespace {
     /**
      * Set the URI identified by this namespace.
      */
-    void setUri(std::string &uri) {
+    void setUri(const std::string &uri) {
         internal_.set_uri(uri);
     }
 
@@ -183,7 +183,7 @@ class URI {
     /**
      * Set the string representation of the URI.
      */
-    void setUri(std::string &uri) {
+    void setUri(const std::string &uri) {
         internal_.set_uri(uri);
     }
 
@@ -279,7 +279,7 @@ class BNode {
     /**
      * Set the id of this blank node.
      */
-    void setId(std::string &id) {
+    void setId(const std::string &id) {
         internal_.set_id(id);
     }
 

http://git-wip-us.apache.org/repos/asf/marmotta/blob/185c41a8/libraries/ostrich/backend/test/PersistenceTest.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/test/PersistenceTest.cc b/libraries/ostrich/backend/test/PersistenceTest.cc
index 301692e..8fb60c9 100644
--- a/libraries/ostrich/backend/test/PersistenceTest.cc
+++ b/libraries/ostrich/backend/test/PersistenceTest.cc
@@ -53,6 +53,42 @@ class PersistenceTest : public ::testing::Test {
     path testdir;
 };
 
+TEST_F(PersistenceTest, TestAddNamespaces) {
+    std::vector<rdf::proto::Namespace> ns = {
+            rdf::Namespace("ex", "http://www.example.com/").getMessage(),
+            rdf::Namespace("foo", "http://www.foo.com/").getMessage(),
+    };
+
+    util::CollectionIterator<rdf::proto::Namespace> it(ns);
+    db->AddNamespaces(it);
+
+    {
+        rdf::Namespace pattern;
+        pattern.setPrefix("foo");
+        auto it = db->GetNamespaces(pattern.getMessage());
+        EXPECT_TRUE(it->hasNext());
+        EXPECT_EQ(ns[1], it->next());
+        EXPECT_FALSE(it->hasNext());
+    }
+
+    {
+        rdf::Namespace pattern;
+        pattern.setPrefix("bar");
+        auto it = db->GetNamespaces(pattern.getMessage());
+        EXPECT_FALSE(it->hasNext());
+    }
+
+    {
+        rdf::Namespace pattern;
+        pattern.setUri("http://www.example.com/");
+        auto it = db->GetNamespaces(pattern.getMessage());
+        EXPECT_TRUE(it->hasNext());
+        EXPECT_EQ(ns[0], it->next());
+        EXPECT_FALSE(it->hasNext());
+    }
+}
+
+
 TEST_F(PersistenceTest, TestAddStatements) {
     std::vector<rdf::proto::Statement> stmts = {
             rdf::Statement(rdf::URI("http://example.com/s1"), rdf::URI("http://example.com/p1"),
@@ -163,6 +199,70 @@ TEST_F(PersistenceTest, TestGetStatementsFiltered) {
 }
 
 
+TEST_F(PersistenceTest, TestRemoveStatements) {
+    std::vector<rdf::proto::Statement> stmts = {
+            rdf::Statement(rdf::URI("http://example.com/s1"), rdf::URI("http://example.com/p1"),
+                           rdf::URI("http://example.com/o1")).getMessage(),
+            rdf::Statement(rdf::URI("http://example.com/s2"), rdf::URI("http://example.com/p2"),
+                           rdf::URI("http://example.com/o2")).getMessage()
+    };
+
+    util::CollectionIterator<rdf::proto::Statement> it(stmts);
+    db->AddStatements(it);
+    ASSERT_EQ(2, db->Size());
+
+    {
+        auto it1 = db->GetStatements(stmts[0]);
+        EXPECT_TRUE(it1->hasNext());
+    }
+
+    db->RemoveStatements(stmts[0]);
+    EXPECT_EQ(1, db->Size());
+
+    {
+        auto it2 = db->GetStatements(stmts[0]);
+        EXPECT_FALSE(it2->hasNext());
+    }
+
+}
+
+TEST_F(PersistenceTest, TestUpdates) {
+    std::vector<rdf::proto::Statement> stmts = {
+            rdf::Statement(rdf::URI("http://example.com/s1"), rdf::URI("http://example.com/p1"),
+                           rdf::URI("http://example.com/o1")).getMessage(),
+            rdf::Statement(rdf::URI("http://example.com/s2"), rdf::URI("http://example.com/p2"),
+                           rdf::URI("http://example.com/o2")).getMessage()
+    };
+
+    util::CollectionIterator<rdf::proto::Statement> it(stmts);
+    db->AddStatements(it);
+    ASSERT_EQ(2, db->Size());
+
+    service::proto::UpdateRequest removeReq;
+    *removeReq.mutable_stmt_removed() = stmts[0];
+    service::proto::UpdateRequest addReq;
+    *addReq.mutable_stmt_added() =
+            rdf::Statement(rdf::URI("http://example.com/s1"), rdf::URI("http://example.com/p1"),
+                           rdf::URI("http://example.com/o3")).getMessage();
+
+
+    util::CollectionIterator<service::proto::UpdateRequest> updates({ removeReq, addReq });
+    db->Update(updates);
+    ASSERT_EQ(2, db->Size());
+
+    {
+        auto it = db->GetStatements(stmts[0]);
+        EXPECT_FALSE(it->hasNext());
+    }
+
+    {
+        auto it = db->GetStatements(addReq.stmt_added());
+        EXPECT_TRUE(it->hasNext());
+    }
+
+}
+
+
 }
 }
 }


[19/50] [abbrv] marmotta git commit: MARMOTTA-620: Merged patch from @marktriggs on github, closes PR #15

Posted by wi...@apache.org.
MARMOTTA-620: Merged patch from @marktriggs on github, closes PR #15


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/83be62b4
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/83be62b4
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/83be62b4

Branch: refs/heads/MARMOTTA-584
Commit: 83be62b495ce73e49313c97ebc4dfd3ac7881a26
Parents: ea28ddb
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Tue Feb 2 10:27:53 2016 +0100
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Tue Feb 2 10:27:53 2016 +0100

----------------------------------------------------------------------
 .../marmotta/kiwi/sail/KiWiValueFactory.java    | 28 ++++++++++++++++----
 1 file changed, 23 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/83be62b4/libraries/kiwi/kiwi-triplestore/src/main/java/org/apache/marmotta/kiwi/sail/KiWiValueFactory.java
----------------------------------------------------------------------
diff --git a/libraries/kiwi/kiwi-triplestore/src/main/java/org/apache/marmotta/kiwi/sail/KiWiValueFactory.java b/libraries/kiwi/kiwi-triplestore/src/main/java/org/apache/marmotta/kiwi/sail/KiWiValueFactory.java
index 42dd4ed..3a717a2 100644
--- a/libraries/kiwi/kiwi-triplestore/src/main/java/org/apache/marmotta/kiwi/sail/KiWiValueFactory.java
+++ b/libraries/kiwi/kiwi-triplestore/src/main/java/org/apache/marmotta/kiwi/sail/KiWiValueFactory.java
@@ -565,6 +565,8 @@ public class KiWiValueFactory implements ValueFactory {
 
             KiWiTriple result = new KiWiTriple(ksubject,kpredicate,kobject,kcontext);
 
+            boolean needsDBLookup = false;
+
             synchronized (registry) {
                 long tripleId = registry.lookupKey(cacheKey);
 
@@ -575,13 +577,29 @@ public class KiWiValueFactory implements ValueFactory {
                     registry.registerKey(cacheKey, connection.getTransactionId(), result.getId());
                 } else {
                     // not found in registry, try loading from database
-                    result.setId(connection.getTripleId(ksubject,kpredicate,kobject,kcontext));
+                    needsDBLookup = true;
                 }
+            }
+
+            if(needsDBLookup) {
+                result.setId(connection.getTripleId(ksubject,kpredicate,kobject,kcontext));
+            }
 
-                // triple has no id from registry or database, so we create one and flag it for reasoning
-                if(result.getId() < 0) {
-                    result.setId(connection.getNextSequence());
-                    result.setNewTriple(true);
+            // triple has no id from registry or database, so we create one and flag it for reasoning
+            if(result.getId() < 0) {
+                synchronized (registry) {
+                    // It's possible a concurrent thread might have created this
+                    // triple while we were blocked.  Check the registry again.
+                    long tripleId = registry.lookupKey(cacheKey);
+
+                    if(tripleId >= 0) {
+                        // A concurrent thread got in first.  Take the one it created.
+                        result.setId(tripleId);
+                    } else {
+                        // Create the new triple
+                        result.setId(connection.getNextSequence());
+                        result.setNewTriple(true);
+                    }
 
                     registry.registerKey(cacheKey, connection.getTransactionId(), result.getId());
                 }


[15/50] [abbrv] marmotta git commit: iterator simplifications

Posted by wi...@apache.org.
iterator simplifications


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/767ef4a7
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/767ef4a7
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/767ef4a7

Branch: refs/heads/MARMOTTA-584
Commit: 767ef4a75969d3fd3da73598466450ce6a8b7c3e
Parents: 185c41a
Author: Sebastian Schaffert <ss...@apache.org>
Authored: Sat Dec 19 19:03:28 2015 +0100
Committer: Sebastian Schaffert <ss...@apache.org>
Committed: Sat Dec 19 19:03:28 2015 +0100

----------------------------------------------------------------------
 .../backend/persistence/leveldb_sparql.cc       | 28 ++++-----------
 libraries/ostrich/backend/util/iterator.h       | 37 ++++++++++++++++++++
 2 files changed, 43 insertions(+), 22 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/767ef4a7/libraries/ostrich/backend/persistence/leveldb_sparql.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/persistence/leveldb_sparql.cc b/libraries/ostrich/backend/persistence/leveldb_sparql.cc
index 274c247..a71dc46 100644
--- a/libraries/ostrich/backend/persistence/leveldb_sparql.cc
+++ b/libraries/ostrich/backend/persistence/leveldb_sparql.cc
@@ -23,29 +23,14 @@ namespace sparql {
 
 using ::marmotta::sparql::StatementIterator;
 
-class WrapProtoStatementIterator : public StatementIterator {
-
+class WrapProtoStatementIterator : public util::ConvertingIterator<rdf::proto::Statement, rdf::Statement> {
  public:
-    WrapProtoStatementIterator(std::unique_ptr<persistence::LevelDBPersistence::StatementIterator> it)
-            : it(std::move(it)) { }
-
-    const rdf::Statement& next() override {
-        current_ = std::move(it->next());
-        return current_;
-    };
+    WrapProtoStatementIterator(util::CloseableIterator<rdf::proto::Statement> *it) : ConvertingIterator(it) { }
 
-    const rdf::Statement& current() const override {
-        return current_;
+ protected:
+    rdf::Statement convert(const rdf::proto::Statement &from) override {
+        return std::move(rdf::Statement(std::move(from)));
     };
-
-    bool hasNext() override {
-        return it->hasNext();
-    }
-
- private:
-    std::unique_ptr<persistence::LevelDBPersistence::StatementIterator> it;
-    rdf::Statement current_;
-    bool parsed;
 };
 
 
@@ -93,9 +78,8 @@ std::unique_ptr<sparql::StatementIterator> LevelDBTripleSource::GetStatements(
     }
 
     return std::unique_ptr<sparql::StatementIterator>(
-            new WrapProtoStatementIterator(persistence->GetStatements(pattern)));
+            new WrapProtoStatementIterator(persistence->GetStatements(pattern).release()));
 }
-
 }  // namespace sparql
 }  // namespace persistence
 }  // namespace marmotta
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/marmotta/blob/767ef4a7/libraries/ostrich/backend/util/iterator.h
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/util/iterator.h b/libraries/ostrich/backend/util/iterator.h
index 8ba1497..fd29cc4 100644
--- a/libraries/ostrich/backend/util/iterator.h
+++ b/libraries/ostrich/backend/util/iterator.h
@@ -208,6 +208,43 @@ class FilteringIterator : public CloseableIterator<T> {
 };
 
 /**
+ * An abstract iterator implementation supporting to convert values
+ * from one type to another. Subclasses must implement the convert() method.
+ */
+template<typename F, typename T>
+class ConvertingIterator : public CloseableIterator<T> {
+ public:
+    ConvertingIterator(CloseableIterator<F>* it) : it(it) { }
+
+    /**
+     * Increment iterator to next element.
+     */
+    const T& next() override {
+        current_ = std::move(convert(it->next()));
+        return current_;
+    };
+
+    const T& current() const override {
+        return current_;
+    };
+
+    /**
+     * Return true in case the iterator has more elements.
+     */
+    bool hasNext() override {
+        return it->hasNext();
+    };
+
+ protected:
+    virtual T convert(const F& from) = 0;
+
+ private:
+    std::unique_ptr<CloseableIterator<F>> it;
+    T current_;
+};
+
+
+/**
  * A multi-threaded iterator supporting iteration over the results
  * successively added by a producer. Blocks while the internal queue
  * is empty and the producer is not yet finished reporting. The


[08/50] [abbrv] marmotta git commit: refactor iterator implementations, they were broken

Posted by wi...@apache.org.
refactor iterator implementations, they were broken


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/2e32da5d
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/2e32da5d
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/2e32da5d

Branch: refs/heads/MARMOTTA-584
Commit: 2e32da5d9cc298272edce2a64e22088335107f21
Parents: 27889eb
Author: Sebastian Schaffert <ss...@apache.org>
Authored: Sat Dec 19 16:15:46 2015 +0100
Committer: Sebastian Schaffert <ss...@apache.org>
Committed: Sat Dec 19 16:15:46 2015 +0100

----------------------------------------------------------------------
 libraries/ostrich/backend/CMakeLists.txt        |     4 +-
 libraries/ostrich/backend/client/client.cc      |    27 +-
 .../ostrich/backend/model/rdf_operators.cc      |     8 +-
 .../ostrich/backend/persistence/CMakeLists.txt  |    22 +-
 .../backend/persistence/leveldb_persistence.cc  |    63 +-
 .../backend/persistence/leveldb_service.cc      |    22 +-
 .../backend/persistence/leveldb_sparql.cc       |    25 +-
 .../backend/persistence/marmotta_updatedb.cc    |   225 +
 .../backend/serializer/serializer_base.h        |     4 +-
 .../ostrich/backend/sparql/rasqal_adapter.cc    |    13 +-
 libraries/ostrich/backend/test/CMakeLists.txt   |    17 +-
 .../ostrich/backend/test/PersistenceTest.cc     |    76 +
 libraries/ostrich/backend/test/SparqlTest.cc    |    29 +-
 libraries/ostrich/backend/test/StatementTest.cc |     2 +-
 .../ostrich/backend/test/gmock-gtest-all.cc     | 12243 ++++++++++
 libraries/ostrich/backend/test/gmock/gmock.h    | 14978 ++++++++++++
 libraries/ostrich/backend/test/gtest-all.cc     |  9592 --------
 libraries/ostrich/backend/test/gtest.h          | 20061 ----------------
 libraries/ostrich/backend/test/gtest/gtest.h    | 21197 +++++++++++++++++
 libraries/ostrich/backend/test/main.cc          |     2 +-
 libraries/ostrich/backend/util/iterator.h       |   173 +-
 21 files changed, 48949 insertions(+), 29834 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/2e32da5d/libraries/ostrich/backend/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/CMakeLists.txt b/libraries/ostrich/backend/CMakeLists.txt
index 6a96f63..e05c28b 100644
--- a/libraries/ostrich/backend/CMakeLists.txt
+++ b/libraries/ostrich/backend/CMakeLists.txt
@@ -14,10 +14,10 @@ find_package (Protobuf REQUIRED)
 find_package (GRPC REQUIRED)
 find_package (LevelDB REQUIRED)
 find_package (GLog REQUIRED)
-find_package (Boost 1.54.0 COMPONENTS iostreams)
+find_package (Boost 1.54.0 COMPONENTS iostreams filesystem system)
 find_package (Tcmalloc)
 
-add_definitions(-DNDEBUG)
+#add_definitions(-DNDEBUG)
 
 if (Boost_IOSTREAMS_FOUND)
     message(STATUS "Enabling gzip/bzip2 support (Boost iostreams found)")

http://git-wip-us.apache.org/repos/asf/marmotta/blob/2e32da5d/libraries/ostrich/backend/client/client.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/client/client.cc b/libraries/ostrich/backend/client/client.cc
index da875a4..396389e 100644
--- a/libraries/ostrich/backend/client/client.cc
+++ b/libraries/ostrich/backend/client/client.cc
@@ -69,28 +69,24 @@ class ClientReaderIterator : public util::CloseableIterator<T> {
  public:
     ClientReaderIterator() : finished(true) { }
 
-    ClientReaderIterator(ClientReader<Proto>* r) : reader(r), finished(false) {
-        // Immediately move to first element.
-        operator++();
+    ClientReaderIterator(ClientReader<Proto>* r) : reader(r) {
+        finished = !reader->Read(&buffer);
     }
 
-    ClientReaderIterator& operator++() override {
+    const T& next() override {
+        current_ = T(buffer);
+
         if (!finished) {
             finished = !reader->Read(&buffer);
-            current = T(buffer);
             if (finished) {
                 reader->Finish();
             }
         }
-        return *this;
-    }
-
-    T& operator*() override {
-        return current;
+        return current_;
     }
 
-    T* operator->() override {
-        return &current;
+    const T& current() const override {
+        return current_;
     }
 
     bool hasNext() override {
@@ -100,7 +96,7 @@ class ClientReaderIterator : public util::CloseableIterator<T> {
  private:
     ClientReader<Proto>* reader;
     Proto buffer;
-    T current;
+    T current_;
     bool finished;
 };
 
@@ -208,8 +204,9 @@ class MarmottaClient {
                 stub_->GetNamespaces(&context, pattern));
 
         NamespaceReader it(reader.get());
-        for (; it.hasNext(); ++it) {
-            out << (*it).getPrefix() << " = " << (*it).getUri() << std::endl;
+        while (it.hasNext()) {
+            const auto& ns = it.next();
+            out << ns.getPrefix() << " = " << ns.getUri() << std::endl;
         }
     }
 

http://git-wip-us.apache.org/repos/asf/marmotta/blob/2e32da5d/libraries/ostrich/backend/model/rdf_operators.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/model/rdf_operators.cc b/libraries/ostrich/backend/model/rdf_operators.cc
index b9e49ad..b2bc2a3 100644
--- a/libraries/ostrich/backend/model/rdf_operators.cc
+++ b/libraries/ostrich/backend/model/rdf_operators.cc
@@ -28,14 +28,18 @@ bool operator==(const Value &lhs, const Value &rhs) {
         } else if (lhs.resource().has_bnode() && rhs.resource().has_bnode()) {
             return lhs.resource().bnode() == rhs.resource().bnode();
         }
+        return (lhs.resource().has_uri() == rhs.resource().has_uri()) &&
+                (lhs.resource().has_bnode() == rhs.resource().has_bnode());
     } else if(lhs.has_literal() && rhs.has_literal()) {
         if (lhs.literal().has_stringliteral() && rhs.literal().has_stringliteral()) {
             return lhs.literal().stringliteral() == rhs.literal().stringliteral();
         } else if (lhs.literal().has_dataliteral() && rhs.literal().has_dataliteral()) {
             return lhs.literal().dataliteral() == rhs.literal().dataliteral();
         }
+        return (lhs.literal().has_stringliteral() == rhs.literal().has_stringliteral()) &&
+               (lhs.literal().has_dataliteral() == rhs.literal().has_dataliteral());
     }
-    return false;
+    return (lhs.has_resource() == rhs.has_resource()) && (lhs.has_literal() == rhs.has_literal());
 }
 
 bool operator==(const Resource &lhs, const Resource &rhs) {
@@ -44,7 +48,7 @@ bool operator==(const Resource &lhs, const Resource &rhs) {
     } else if (lhs.has_bnode() && rhs.has_bnode()) {
         return lhs.bnode() == rhs.bnode();
     }
-    return false;
+    return (lhs.has_uri() == rhs.has_uri()) && (lhs.has_bnode() == rhs.has_bnode());
 }
 
 bool operator==(const Statement &lhs, const Statement &rhs) {

http://git-wip-us.apache.org/repos/asf/marmotta/blob/2e32da5d/libraries/ostrich/backend/persistence/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/persistence/CMakeLists.txt b/libraries/ostrich/backend/persistence/CMakeLists.txt
index d4a274a..8392c61 100644
--- a/libraries/ostrich/backend/persistence/CMakeLists.txt
+++ b/libraries/ostrich/backend/persistence/CMakeLists.txt
@@ -1,11 +1,21 @@
 include_directories(.. ${CMAKE_CURRENT_BINARY_DIR}/.. ${CMAKE_CURRENT_BINARY_DIR}/../model ${RAPTOR_INCLUDE_DIR}/raptor2)
 
+# Shared Marmotta Ostrich persistence implementation
+add_library(marmotta_leveldb
+        leveldb_persistence.cc leveldb_persistence.h leveldb_sparql.cc leveldb_sparql.h)
+target_link_libraries(marmotta_leveldb
+        marmotta_model marmotta_util marmotta_sparql marmotta_service
+        ${LevelDB_LIBRARY} ${GLOG_LIBRARY} ${PROTOBUF_LIBRARIES})
+
+# Server binary
 add_executable(marmotta_persistence
-        leveldb_persistence.cc leveldb_persistence.h leveldb_service.cc leveldb_service.h
-        leveldb_server.cc leveldb_sparql.cc leveldb_sparql.h)
-target_link_libraries(marmotta_persistence
-        marmotta_model marmotta_service marmotta_util marmotta_sparql
-        ${LevelDB_LIBRARY} ${GFLAGS_LIBRARY} ${GLOG_LIBRARY}
-        ${CMAKE_THREAD_LIBS_INIT} ${PROTOBUF_LIBRARIES} ${GRPC_LIBRARIES} ${Tcmalloc_LIBRARIES})
+        leveldb_service.cc leveldb_service.h leveldb_server.cc )
+target_link_libraries(marmotta_persistence marmotta_service marmotta_leveldb
+        ${GFLAGS_LIBRARY} ${CMAKE_THREAD_LIBS_INIT} ${GRPC_LIBRARIES} ${Tcmalloc_LIBRARIES})
 install(TARGETS marmotta_persistence DESTINATION bin)
 
+# Command line admin tool
+add_executable(marmotta_updatedb marmotta_updatedb.cc)
+target_link_libraries(marmotta_updatedb marmotta_leveldb marmotta_parser marmotta_serializer
+        ${GFLAGS_LIBRARY} ${Boost_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT} ${Tcmalloc_LIBRARIES})
+install(TARGETS marmotta_updatedb DESTINATION bin)

http://git-wip-us.apache.org/repos/asf/marmotta/blob/2e32da5d/libraries/ostrich/backend/persistence/leveldb_persistence.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/persistence/leveldb_persistence.cc b/libraries/ostrich/backend/persistence/leveldb_persistence.cc
index 5f18eff..dd9eef9 100644
--- a/libraries/ostrich/backend/persistence/leveldb_persistence.cc
+++ b/libraries/ostrich/backend/persistence/leveldb_persistence.cc
@@ -187,7 +187,7 @@ class LevelDBIterator : public util::CloseableIterator<T> {
  public:
 
     LevelDBIterator(leveldb::Iterator *it)
-        : it(it), parsed(false) {
+        : it(it) {
         it->SeekToFirst();
     }
 
@@ -195,35 +195,24 @@ class LevelDBIterator : public util::CloseableIterator<T> {
         delete it;
     };
 
-    util::CloseableIterator<T> &operator++() override {
+    const T& next() override {
+        // Parse current position, then iterate to next position for next call.
+        proto.ParseFromString(it->value().ToString());
         it->Next();
-        parsed = false;
-        return *this;
-    };
-
-    T &operator*() override {
-        if (!parsed)
-            proto.ParseFromString(it->value().ToString());
         return proto;
     };
 
-    T *operator->() override {
-        if (!parsed)
-            proto.ParseFromString(it->value().ToString());
-        return &proto;
+    const T& current() const override {
+        return proto;
     };
 
     virtual bool hasNext() override {
         return it->Valid();
     }
 
-
-
  protected:
     leveldb::Iterator* it;
-
     T proto;
-    bool parsed;
 };
 
 
@@ -313,6 +302,11 @@ LevelDBPersistence::LevelDBPersistence(const std::string &path, int64_t cacheSiz
         t.join();
     }
 
+    CHECK_NOTNULL(db_spoc.get());
+    CHECK_NOTNULL(db_cspo.get());
+    CHECK_NOTNULL(db_opsc.get());
+    CHECK_NOTNULL(db_pcos.get());
+
     LOG(INFO) << "LevelDB Database initialised.";
 }
 
@@ -323,8 +317,8 @@ int64_t LevelDBPersistence::AddNamespaces(NamespaceIterator& it) {
 
     leveldb::WriteBatch batch_prefix, batch_url;
 
-    for (; it.hasNext(); ++it) {
-        AddNamespace(*it, batch_prefix, batch_url);
+    while (it.hasNext()) {
+        AddNamespace(it.next(), batch_prefix, batch_url);
         count++;
     }
     CHECK_STATUS(db_ns_prefix->Write(leveldb::WriteOptions(), &batch_prefix));
@@ -374,8 +368,8 @@ void LevelDBPersistence::GetNamespaces(
     int64_t count = 0;
 
     bool cbsuccess = true;
-    for(auto it = GetNamespaces(pattern); cbsuccess && it->hasNext(); ++(*it)) {
-        cbsuccess = callback(**it);
+    for(auto it = GetNamespaces(pattern); cbsuccess && it->hasNext();) {
+        cbsuccess = callback(it->next());
         count++;
     }
 
@@ -389,8 +383,8 @@ int64_t LevelDBPersistence::AddStatements(StatementIterator& it) {
     int64_t count = 0;
 
     leveldb::WriteBatch batch_spoc, batch_cspo, batch_opsc, batch_pcos;
-    for (; it.hasNext(); ++it) {
-        AddStatement(*it, batch_spoc, batch_cspo, batch_opsc, batch_pcos);
+    while (it.hasNext()) {
+        AddStatement(it.next(), batch_spoc, batch_cspo, batch_opsc, batch_pcos);
         count++;
     }
 
@@ -473,8 +467,8 @@ void LevelDBPersistence::GetStatements(
     int64_t count = 0;
 
     bool cbsuccess = true;
-    for(auto it = GetStatements(pattern); cbsuccess && it->hasNext(); ++(*it)) {
-        cbsuccess = callback(**it);
+    for(auto it = GetStatements(pattern); cbsuccess && it->hasNext(); ) {
+        cbsuccess = callback(it->next());
         count++;
     }
 
@@ -528,18 +522,19 @@ UpdateStatistics LevelDBPersistence::Update(LevelDBPersistence::UpdateIterator &
     UpdateStatistics stats;
 
     WriteBatch b_spoc, b_cspo, b_opsc, b_pcos, b_prefix, b_url;
-    for (; it.hasNext(); ++it) {
-        if (it->has_stmt_added()) {
-            AddStatement(it->stmt_added(), b_spoc, b_cspo, b_opsc, b_pcos);
+    while (it.hasNext()) {
+        auto next = it.next();
+        if (next.has_stmt_added()) {
+            AddStatement(next.stmt_added(), b_spoc, b_cspo, b_opsc, b_pcos);
             stats.added_stmts++;
-        } else if (it->has_stmt_removed()) {
+        } else if (next.has_stmt_removed()) {
             stats.removed_stmts +=
-                    RemoveStatements(it->stmt_removed(), b_spoc, b_cspo, b_opsc, b_pcos);
-        } else if(it->has_ns_added()) {
-            AddNamespace(it->ns_added(), b_prefix, b_url);
+                    RemoveStatements(next.stmt_removed(), b_spoc, b_cspo, b_opsc, b_pcos);
+        } else if(next.has_ns_added()) {
+            AddNamespace(next.ns_added(), b_prefix, b_url);
             stats.added_ns++;
-        } else if(it->has_ns_removed()) {
-            RemoveNamespace(it->ns_removed(), b_prefix, b_url);
+        } else if(next.has_ns_removed()) {
+            RemoveNamespace(next.ns_removed(), b_prefix, b_url);
         }
     }
     std::vector<std::thread> writers;

http://git-wip-us.apache.org/repos/asf/marmotta/blob/2e32da5d/libraries/ostrich/backend/persistence/leveldb_service.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/persistence/leveldb_service.cc b/libraries/ostrich/backend/persistence/leveldb_service.cc
index e31af2d..9ab9fd8 100644
--- a/libraries/ostrich/backend/persistence/leveldb_service.cc
+++ b/libraries/ostrich/backend/persistence/leveldb_service.cc
@@ -48,24 +48,21 @@ template <class Proto>
 class ReaderIterator : public util::CloseableIterator<Proto> {
  public:
 
-    ReaderIterator(grpc::ServerReader<Proto>* r) : reader(r), finished(false) {
+    ReaderIterator(grpc::ServerReader<Proto>* r) : reader(r) {
         // Immediately move to first element.
-        operator++();
+        finished = !reader->Read(&next_);
     }
 
-    util::CloseableIterator<Proto>& operator++() override {
+    const Proto& next() override {
+        current_.Swap(&next_);
         if (!finished) {
-            finished = !reader->Read(&buffer);
+            finished = !reader->Read(&next_);
         }
-        return *this;
+        return current_;
     }
 
-    Proto& operator*() override {
-        return buffer;
-    }
-
-    Proto* operator->() override {
-        return &buffer;
+    const Proto& current() const override {
+        return current_;
     }
 
     bool hasNext() override {
@@ -74,7 +71,8 @@ class ReaderIterator : public util::CloseableIterator<Proto> {
 
  private:
     grpc::ServerReader<Proto>* reader;
-    Proto buffer;
+    Proto current_;
+    Proto next_;
     bool finished;
 };
 

http://git-wip-us.apache.org/repos/asf/marmotta/blob/2e32da5d/libraries/ostrich/backend/persistence/leveldb_sparql.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/persistence/leveldb_sparql.cc b/libraries/ostrich/backend/persistence/leveldb_sparql.cc
index 5d44db6..274c247 100644
--- a/libraries/ostrich/backend/persistence/leveldb_sparql.cc
+++ b/libraries/ostrich/backend/persistence/leveldb_sparql.cc
@@ -29,26 +29,13 @@ class WrapProtoStatementIterator : public StatementIterator {
     WrapProtoStatementIterator(std::unique_ptr<persistence::LevelDBPersistence::StatementIterator> it)
             : it(std::move(it)) { }
 
-    util::CloseableIterator<rdf::Statement> &operator++() override {
-        ++(*it);
-        parsed = false;
-        return *this;
+    const rdf::Statement& next() override {
+        current_ = std::move(it->next());
+        return current_;
     };
 
-    rdf::Statement &operator*() override {
-        if (!parsed) {
-            current = std::move(**it);
-            parsed = true;
-        }
-        return current;
-    };
-
-    rdf::Statement *operator->() override {
-        if (!parsed) {
-            current = std::move(**it);
-            parsed = true;
-        }
-        return &current;
+    const rdf::Statement& current() const override {
+        return current_;
     };
 
     bool hasNext() override {
@@ -57,7 +44,7 @@ class WrapProtoStatementIterator : public StatementIterator {
 
  private:
     std::unique_ptr<persistence::LevelDBPersistence::StatementIterator> it;
-    rdf::Statement current;
+    rdf::Statement current_;
     bool parsed;
 };
 

http://git-wip-us.apache.org/repos/asf/marmotta/blob/2e32da5d/libraries/ostrich/backend/persistence/marmotta_updatedb.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/persistence/marmotta_updatedb.cc b/libraries/ostrich/backend/persistence/marmotta_updatedb.cc
new file mode 100644
index 0000000..b26b019
--- /dev/null
+++ b/libraries/ostrich/backend/persistence/marmotta_updatedb.cc
@@ -0,0 +1,225 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+#include <fstream>
+
+#ifdef HAVE_IOSTREAMS
+// support b/gzipped files
+#include <boost/iostreams/filtering_streambuf.hpp>
+#include <boost/iostreams/copy.hpp>
+#include <boost/iostreams/filter/gzip.hpp>
+#include <boost/iostreams/filter/bzip2.hpp>
+#endif
+
+#include <google/protobuf/text_format.h>
+#include <google/protobuf/empty.pb.h>
+#include <google/protobuf/wrappers.pb.h>
+
+#include <gflags/gflags.h>
+#include <thread>
+#include <glog/logging.h>
+#include <sys/stat.h>
+
+#include "model/rdf_model.h"
+#include "parser/rdf_parser.h"
+#include "serializer/serializer.h"
+#include "persistence/leveldb_persistence.h"
+
+using namespace marmotta;
+using google::protobuf::TextFormat;
+
+#ifdef HAVE_IOSTREAMS
+using namespace boost::iostreams;
+#endif
+
+class MarmottaClient {
+ public:
+    MarmottaClient(marmotta::persistence::LevelDBPersistence* db)
+            : db(db){ }
+
+    void importDataset(std::istream& in, parser::Format format) {
+        auto start = std::chrono::steady_clock::now();
+        int64_t count = 0;
+
+        parser::Parser p("http://www.example.com", format);
+        util::ProducerConsumerIterator<rdf::proto::Statement> stmtit;
+        util::ProducerConsumerIterator<rdf::proto::Namespace> nsit;
+        p.setStatementHandler([&stmtit](const rdf::Statement& stmt) {
+            stmtit.add(stmt.getMessage());
+        });
+        p.setNamespaceHandler([&nsit](const rdf::Namespace& ns) {
+            nsit.add(ns.getMessage());
+        });
+
+        std::thread([&p, &in, &stmtit, &nsit]() {
+            p.parse(in);
+            stmtit.finish();
+            nsit.finish();
+        });
+
+        db->AddStatements(stmtit);
+        db->AddNamespaces(nsit);
+    }
+
+
+    void patternQuery(const rdf::Statement &pattern, std::ostream &out, serializer::Format format) {
+    }
+
+    void patternDelete(const rdf::Statement &pattern) {
+        db->RemoveStatements(pattern.getMessage());
+    }
+
+    void tupleQuery(const std::string& query, std::ostream &out) {
+        /*
+        ClientContext context;
+        spq::SparqlRequest request;
+        request.set_query(query);
+
+        std::unique_ptr<ClientReader<spq::SparqlResponse>> reader(
+                sparql_->TupleQuery(&context, request));
+
+        auto out_ = new google::protobuf::io::OstreamOutputStream(&out);
+        spq::SparqlResponse result;
+        while (reader->Read(&result)) {
+            TextFormat::Print(result, dynamic_cast<google::protobuf::io::ZeroCopyOutputStream*>(out_));
+        }
+        delete out_;
+         */
+    }
+
+    void listNamespaces(std::ostream &out) {
+        /*
+        ClientContext context;
+
+        google::protobuf::Empty pattern;
+
+        std::unique_ptr<ClientReader<rdf::proto::Namespace> > reader(
+                stub_->GetNamespaces(&context, pattern));
+
+        NamespaceReader it(reader.get());
+        for (; it.hasNext(); ++it) {
+            out << (*it).getPrefix() << " = " << (*it).getUri() << std::endl;
+        }
+         */
+    }
+
+    int64_t size() {
+        /*
+        ClientContext context;
+        google::protobuf::Int64Value result;
+
+        Status status = stub_->Size(&context, r, &result);
+        if (status.ok()) {
+            return result.value();
+        } else {
+            return -1;
+        }
+         */
+    }
+ private:
+    marmotta::persistence::LevelDBPersistence* db;
+};
+
+
+DEFINE_string(format, "rdfxml", "RDF format to use for parsing/serializing.");
+DEFINE_string(output, "", "File to write result to.");
+DEFINE_string(db, "/tmp/testdb", "Path to database. Will be created if non-existant.");
+DEFINE_int64(cache_size, 100 * 1048576, "Cache size used by the database (in bytes).");
+
+#ifdef HAVE_IOSTREAMS
+DEFINE_bool(gzip, false, "Input files are gzip compressed.");
+DEFINE_bool(bzip2, false, "Input files are bzip2 compressed.");
+#endif
+
+int main(int argc, char** argv) {
+    GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+    // Initialize Google's logging library.
+    google::InitGoogleLogging(argv[0]);
+    google::ParseCommandLineFlags(&argc, &argv, true);
+
+    mkdir(FLAGS_db.c_str(), 0700);
+    marmotta::persistence::LevelDBPersistence persistence(FLAGS_db, FLAGS_cache_size);
+
+    MarmottaClient client(&persistence);
+
+    if ("import" == std::string(argv[1])) {
+#ifdef HAVE_IOSTREAMS
+        std::ifstream file(argv[2]);
+        filtering_streambuf<input> cin;
+        if (FLAGS_bzip2) {
+            cin.push(bzip2_decompressor());
+        }
+        if (FLAGS_gzip) {
+            cin.push(gzip_decompressor());
+        }
+        cin.push(file);
+
+        std::istream in(&cin);
+#else
+        std::ifstream in(argv[2]);
+#endif
+        std::cout << "Importing " << argv[2] << " ... " << std::endl;
+        client.importDataset(in, parser::FormatFromString(FLAGS_format));
+        std::cout << "Finished!" << std::endl;
+    }
+
+    if ("select" == std::string(argv[1])) {
+        rdf::proto::Statement query;
+        TextFormat::ParseFromString(argv[2], &query);
+        if (FLAGS_output != "") {
+            std::ofstream out(FLAGS_output);
+            client.patternQuery(rdf::Statement(query), out, serializer::FormatFromString(FLAGS_format));
+        } else {
+            client.patternQuery(rdf::Statement(query), std::cout, serializer::FormatFromString(FLAGS_format));
+        }
+    }
+
+    if ("sparql" == std::string(argv[1])) {
+        std::string query = argv[2];
+        if (FLAGS_output != "") {
+            std::ofstream out(FLAGS_output);
+            client.tupleQuery(query, out);
+        } else {
+            client.tupleQuery(query, std::cout);
+        }
+    }
+
+    if ("delete" == std::string(argv[1])) {
+        rdf::proto::Statement query;
+        TextFormat::ParseFromString(argv[2], &query);
+        client.patternDelete(rdf::Statement(query));
+    }
+
+    if ("size" == std::string(argv[1])) {
+        std::cout << "Size: " << client.size() << std::endl;
+    }
+
+
+    if ("namespaces" == std::string(argv[1])) {
+        if (FLAGS_output != "") {
+            std::ofstream out(FLAGS_output);
+            client.listNamespaces(out);
+        } else {
+            client.listNamespaces(std::cout);
+        }
+    }
+
+    google::protobuf::ShutdownProtobufLibrary();
+
+    return 0;
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/marmotta/blob/2e32da5d/libraries/ostrich/backend/serializer/serializer_base.h
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/serializer/serializer_base.h b/libraries/ostrich/backend/serializer/serializer_base.h
index 24a64f9..168da98 100644
--- a/libraries/ostrich/backend/serializer/serializer_base.h
+++ b/libraries/ostrich/backend/serializer/serializer_base.h
@@ -65,8 +65,8 @@ class SerializerBase {
 
     void serialize(StatementIterator &it, std::ostream &out) {
         prepare(out);
-        for (; it.hasNext(); ++it) {
-            serialize(*it);
+        while (it.hasNext()) {
+            serialize(it.next());
         }
         close();
     };

http://git-wip-us.apache.org/repos/asf/marmotta/blob/2e32da5d/libraries/ostrich/backend/sparql/rasqal_adapter.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/sparql/rasqal_adapter.cc b/libraries/ostrich/backend/sparql/rasqal_adapter.cc
index 7fc3cad..c9c89a6 100644
--- a/libraries/ostrich/backend/sparql/rasqal_adapter.cc
+++ b/libraries/ostrich/backend/sparql/rasqal_adapter.cc
@@ -65,26 +65,27 @@ rasqal_triple_parts bind_match(
         struct rasqal_triples_match_s *rtm, void *user_data,
         rasqal_variable *bindings[4], rasqal_triple_parts parts) {
     StatementIterator *it = (StatementIterator *) rtm->user_data;
+    const rdf::Statement& s = it->next();
 
     int r = 0;
 
 #ifndef NDEBUG
-    DLOG(INFO) << "Binding variables " << formatVariables(bindings) << " for statement " << (*it)->as_turtle();
+    DLOG(INFO) << "Binding variables " << formatVariables(bindings) << " for statement " << s.as_turtle();
 #endif
     if ((parts & RASQAL_TRIPLE_SUBJECT) != 0) {
-        rasqal_variable_set_value(bindings[0], rasqal::AsLiteral(rtm->world, (*it)->getSubject()));
+        rasqal_variable_set_value(bindings[0], rasqal::AsLiteral(rtm->world, s.getSubject()));
         r |= RASQAL_TRIPLE_SUBJECT;
     }
     if ((parts & RASQAL_TRIPLE_PREDICATE) != 0) {
-        rasqal_variable_set_value(bindings[1], rasqal::AsLiteral(rtm->world, (*it)->getPredicate()));
+        rasqal_variable_set_value(bindings[1], rasqal::AsLiteral(rtm->world, s.getPredicate()));
         r |= RASQAL_TRIPLE_PREDICATE;
     }
     if ((parts & RASQAL_TRIPLE_OBJECT) != 0) {
-        rasqal_variable_set_value(bindings[2], rasqal::AsLiteral(rtm->world, (*it)->getObject()));
+        rasqal_variable_set_value(bindings[2], rasqal::AsLiteral(rtm->world, s.getObject()));
         r |= RASQAL_TRIPLE_OBJECT;
     }
     if ((parts & RASQAL_TRIPLE_ORIGIN) != 0) {
-        rasqal_variable_set_value(bindings[3], rasqal::AsLiteral(rtm->world, (*it)->getContext()));
+        rasqal_variable_set_value(bindings[3], rasqal::AsLiteral(rtm->world, s.getContext()));
         r |= RASQAL_TRIPLE_ORIGIN;
     }
 
@@ -94,8 +95,6 @@ rasqal_triple_parts bind_match(
 // Increment the iterator contained in the triple match user data.
 void next_match(struct rasqal_triples_match_s *rtm, void *user_data) {
     DLOG(INFO) << "Next result";
-    StatementIterator *it = (StatementIterator *) rtm->user_data;
-    ++(*it);
 }
 
 // Return true in case the iterator has no next element.

http://git-wip-us.apache.org/repos/asf/marmotta/blob/2e32da5d/libraries/ostrich/backend/test/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/test/CMakeLists.txt b/libraries/ostrich/backend/test/CMakeLists.txt
index 841b982..660f40f 100644
--- a/libraries/ostrich/backend/test/CMakeLists.txt
+++ b/libraries/ostrich/backend/test/CMakeLists.txt
@@ -1,6 +1,11 @@
-include_directories(.. ${CMAKE_CURRENT_BINARY_DIR}/.. ${RAPTOR_INCLUDE_DIR}/raptor2)
+enable_testing()
+include_directories(${GTEST_INCLUDE_DIRS})
+include_directories(..)
+include_directories(${CMAKE_CURRENT_BINARY_DIR}/..)
+include_directories(${CMAKE_CURRENT_BINARY_DIR}/../model)
+include_directories(${RAPTOR_INCLUDE_DIR}/raptor2)
 
-add_library(gtest STATIC gtest.h gtest-all.cc)
+add_library(gtest STATIC gtest/gtest.h gmock/gmock.h gmock-gtest-all.cc)
 
 add_executable(model_tests StatementTest.cc main.cc)
 target_link_libraries(model_tests gtest marmotta_model ${GLOG_LIBRARY})
@@ -8,5 +13,9 @@ target_link_libraries(model_tests gtest marmotta_model ${GLOG_LIBRARY})
 add_executable(sparql_tests SparqlTest.cc main.cc)
 target_link_libraries(sparql_tests gtest marmotta_model marmotta_sparql ${GLOG_LIBRARY})
 
-add_test(NAME ModelTest
-         COMMAND model_tests)
+add_executable(persistence_tests main.cc PersistenceTest.cc)
+target_link_libraries(persistence_tests gtest marmotta_leveldb ${GLOG_LIBRARY} ${Boost_LIBRARIES})
+
+add_test(NAME ModelTest COMMAND model_tests)
+add_test(NAME SparqlTest COMMAND sparql_tests)
+add_test(NAME PersistenceTest COMMAND persistence_tests)
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/marmotta/blob/2e32da5d/libraries/ostrich/backend/test/PersistenceTest.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/test/PersistenceTest.cc b/libraries/ostrich/backend/test/PersistenceTest.cc
new file mode 100644
index 0000000..9878cd6
--- /dev/null
+++ b/libraries/ostrich/backend/test/PersistenceTest.cc
@@ -0,0 +1,76 @@
+//
+// Created by wastl on 19.12.15.
+//
+#include <cstdlib>
+#include <vector>
+
+#include <glog/logging.h>
+
+#include "gtest/gtest.h"
+#include "gmock/gmock.h"
+#include "boost/filesystem.hpp"
+
+#include "util/iterator.h"
+#include "model/rdf_operators.h"
+#include "persistence/leveldb_persistence.h"
+
+using namespace boost::filesystem;
+
+namespace marmotta {
+namespace rdf {
+namespace proto {
+std::ostream& operator<<(std::ostream& out, const Statement& stmt) {
+    out << rdf::Statement(stmt).as_turtle();
+    return out;
+}
+}
+}
+
+namespace persistence {
+namespace {
+
+
+class PersistenceTest : public ::testing::Test {
+ protected:
+    PersistenceTest() {
+        testdir = temp_directory_path()/unique_path();
+        create_directory(testdir);
+
+        LOG(INFO) << "Test DB Path: " << testdir.string();
+
+        db = new LevelDBPersistence(testdir.string(), 10 * 1048576);
+    }
+
+    ~PersistenceTest() {
+        LOG(INFO) << "Destroying Test DB";
+        delete db;
+        remove_all(testdir);
+    }
+
+    LevelDBPersistence* db;
+    path testdir;
+};
+
+TEST_F(PersistenceTest, TestAddStatements) {
+    std::vector<rdf::proto::Statement> stmts = {
+            rdf::Statement(rdf::URI("http://example.com/s1"), rdf::URI("http://example.com/p1"),
+                           rdf::URI("http://example.com/o1")).getMessage(),
+            rdf::Statement(rdf::URI("http://example.com/s2"), rdf::URI("http://example.com/p2"),
+                           rdf::URI("http://example.com/o2")).getMessage()
+    };
+
+    util::CollectionIterator<rdf::proto::Statement> it(stmts);
+    db->AddStatements(it);
+
+    EXPECT_EQ(2, db->Size());
+    for (const auto& stmt : stmts) {
+        auto it = db->GetStatements(stmt);
+        ASSERT_TRUE(it->hasNext());
+        EXPECT_EQ(stmt, it->next());
+        EXPECT_FALSE(it->hasNext());
+    }
+}
+
+}
+}
+}

http://git-wip-us.apache.org/repos/asf/marmotta/blob/2e32da5d/libraries/ostrich/backend/test/SparqlTest.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/test/SparqlTest.cc b/libraries/ostrich/backend/test/SparqlTest.cc
index 7e56eba..356e43f 100644
--- a/libraries/ostrich/backend/test/SparqlTest.cc
+++ b/libraries/ostrich/backend/test/SparqlTest.cc
@@ -2,7 +2,7 @@
 // Created by wastl on 09.12.15.
 //
 #include <glog/logging.h>
-#include "gtest.h"
+#include "gtest/gtest.h"
 #include "sparql/rasqal_adapter.h"
 #include "model/rdf_operators.h"
 
@@ -10,33 +10,8 @@ namespace marmotta {
 namespace sparql {
 
 namespace {
-class MockStatementIterator : public StatementIterator {
- public:
-    MockStatementIterator(std::vector<rdf::Statement> statements)
-            : statements(statements), index(0) {
-    }
-
-    StatementIterator& operator++() override {
-        index++;
-        return *this;
-    };
-
-    rdf::Statement& operator*() override {
-        return statements[index];
-    };
-
-    rdf::Statement* operator->() override {
-        return &statements[index];
-    };
 
-    bool hasNext() override {
-        return index < statements.size();
-    };
-
- private:
-    std::vector<rdf::Statement> statements;
-    int index;
-};
+using MockStatementIterator = util::CollectionIterator<rdf::Statement>;
 
 class MockTripleSource : public TripleSource {
 

http://git-wip-us.apache.org/repos/asf/marmotta/blob/2e32da5d/libraries/ostrich/backend/test/StatementTest.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/test/StatementTest.cc b/libraries/ostrich/backend/test/StatementTest.cc
index 56fb11e..458f037 100644
--- a/libraries/ostrich/backend/test/StatementTest.cc
+++ b/libraries/ostrich/backend/test/StatementTest.cc
@@ -2,7 +2,7 @@
 // Created by wastl on 18.04.15.
 //
 
-#include "gtest.h"
+#include "gtest/gtest.h"
 #include "model/rdf_model.h"
 #include "model/rdf_operators.h"
 


[10/50] [abbrv] marmotta git commit: debug logging

Posted by wi...@apache.org.
debug logging


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/299272ac
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/299272ac
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/299272ac

Branch: refs/heads/MARMOTTA-584
Commit: 299272acfd02911e511a68a07c7213be50ff2ac1
Parents: ba1168d
Author: Sebastian Schaffert <ss...@apache.org>
Authored: Sat Dec 19 16:39:19 2015 +0100
Committer: Sebastian Schaffert <ss...@apache.org>
Committed: Sat Dec 19 16:39:19 2015 +0100

----------------------------------------------------------------------
 libraries/ostrich/backend/persistence/leveldb_persistence.cc | 2 ++
 1 file changed, 2 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/299272ac/libraries/ostrich/backend/persistence/leveldb_persistence.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/persistence/leveldb_persistence.cc b/libraries/ostrich/backend/persistence/leveldb_persistence.cc
index 1157869..f29895c 100644
--- a/libraries/ostrich/backend/persistence/leveldb_persistence.cc
+++ b/libraries/ostrich/backend/persistence/leveldb_persistence.cc
@@ -478,12 +478,14 @@ std::unique_ptr<LevelDBPersistence::StatementIterator> LevelDBPersistence::GetSt
     };
 
     if (query.NeedsFilter()) {
+        DLOG(INFO) << "Retrieving statements with filter.";
         return std::unique_ptr<StatementIterator>(
                 new util::FilteringIterator<Statement>(
                         new StatementRangeIterator(
                                 db->NewIterator(leveldb::ReadOptions()), query.MinKey(), query.MaxKey()),
                         [&pattern](const Statement& stmt) -> bool { return Matches(pattern, stmt); }));
     } else {
+        DLOG(INFO) << "Retrieving statements without filter.";
         return std::unique_ptr<StatementIterator>(
                 new StatementRangeIterator(
                         db->NewIterator(leveldb::ReadOptions()), query.MinKey(), query.MaxKey()));


[21/50] [abbrv] marmotta git commit: MARMOTTA-627: added some tests

Posted by wi...@apache.org.
MARMOTTA-627: added some tests


Project: http://git-wip-us.apache.org/repos/asf/marmotta/repo
Commit: http://git-wip-us.apache.org/repos/asf/marmotta/commit/1413bb85
Tree: http://git-wip-us.apache.org/repos/asf/marmotta/tree/1413bb85
Diff: http://git-wip-us.apache.org/repos/asf/marmotta/diff/1413bb85

Branch: refs/heads/MARMOTTA-584
Commit: 1413bb858b24c61600cd82ba80ff1de784d3056a
Parents: cfdf9e6
Author: Sergio Fern�ndez <wi...@apache.org>
Authored: Thu Feb 11 14:32:49 2016 +0100
Committer: Sergio Fern�ndez <wi...@apache.org>
Committed: Thu Feb 11 14:32:49 2016 +0100

----------------------------------------------------------------------
 .../kiwi/sparql/test/KiWiSparqlTest.java        | 51 ++++++++++++++++++++
 1 file changed, 51 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/marmotta/blob/1413bb85/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java
----------------------------------------------------------------------
diff --git a/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java b/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java
index c3a2868..510e504 100644
--- a/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java
+++ b/libraries/kiwi/kiwi-sparql/src/test/java/org/apache/marmotta/kiwi/sparql/test/KiWiSparqlTest.java
@@ -23,6 +23,7 @@ import info.aduna.iteration.Iterations;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.io.IOUtils;
 import org.apache.marmotta.kiwi.config.KiWiConfiguration;
+import org.apache.marmotta.kiwi.persistence.pgsql.PostgreSQLDialect;
 import org.apache.marmotta.kiwi.sail.KiWiStore;
 import org.apache.marmotta.kiwi.sparql.sail.KiWiSparqlSail;
 import org.apache.marmotta.kiwi.test.junit.KiWiDatabaseRunner;
@@ -54,6 +55,7 @@ import java.util.Set;
  * @author Sergio Fern�mdez
  */
 @RunWith(KiWiDatabaseRunner.class)
+@KiWiDatabaseRunner.ForDialects(PostgreSQLDialect.class)
 public class KiWiSparqlTest {
 
     final Logger log = LoggerFactory.getLogger(this.getClass());
@@ -272,4 +274,53 @@ public class KiWiSparqlTest {
         }
     }
 
+    private void testMarmotta627(String queryString, double expected) throws RepositoryException, MalformedQueryException, QueryEvaluationException {
+        RepositoryConnection conn = repository.getConnection();
+        try {
+            conn.begin();
+            final TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
+            final TupleQueryResult results = query.evaluate();
+            try {
+                Assert.assertTrue(results.hasNext());
+                final BindingSet bindingSet = results.next();
+                Assert.assertNotNull(bindingSet);
+                Assert.assertTrue(bindingSet.getValue("c") instanceof Literal);
+                final Literal c = (Literal) bindingSet.getValue("c");
+                Assert.assertEquals("http://www.w3.org/2001/XMLSchema#decimal", c.getDatatype().stringValue());
+                Assert.assertEquals(expected, c.doubleValue(), 0);
+                Assert.assertFalse(results.hasNext());
+            } finally {
+                results.close();
+            }
+        } finally {
+            conn.close();
+        }
+    }
+
+    @Test
+    public void testMarmotta627_1() throws Exception {
+        testMarmotta627("SELECT ( (4.5-4.4)*0.1 as ?c )  WHERE {}", 0.01);
+    }
+
+    @Test
+    public void testMarmotta627_2() throws Exception {
+        testMarmotta627("SELECT ( 0.1*0.1 as ?c )  WHERE {}", 0.01);
+    }
+
+    @Test
+    public void testMarmotta627_3() throws Exception {
+        testMarmotta627("SELECT ( 0.10*0.01 as ?c )  WHERE {}", 0.001);
+    }
+
+    @Test
+    public void testMarmotta627_4() throws Exception {
+        testMarmotta627("SELECT ( 1.00*3.10 as ?c )  WHERE {}", 3.10);
+    }
+
+    @Test
+    public void testMarmotta627_5() throws Exception {
+        testMarmotta627("SELECT ( 2.00*4.00 as ?c )  WHERE {}", 8.00);
+    }
+
+
 }


[07/50] [abbrv] marmotta git commit: refactor iterator implementations, they were broken

Posted by wi...@apache.org.
http://git-wip-us.apache.org/repos/asf/marmotta/blob/2e32da5d/libraries/ostrich/backend/test/gmock-gtest-all.cc
----------------------------------------------------------------------
diff --git a/libraries/ostrich/backend/test/gmock-gtest-all.cc b/libraries/ostrich/backend/test/gmock-gtest-all.cc
new file mode 100644
index 0000000..025e389
--- /dev/null
+++ b/libraries/ostrich/backend/test/gmock-gtest-all.cc
@@ -0,0 +1,12243 @@
+// Copyright 2008, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+// Author: mheule@google.com (Markus Heule)
+//
+// Google C++ Testing Framework (Google Test)
+//
+// Sometimes it's desirable to build Google Test by compiling a single file.
+// This file serves this purpose.
+
+// This line ensures that gtest.h can be compiled on its own, even
+// when it's fused.
+#include "gtest/gtest.h"
+
+// The following lines pull in the real gtest *.cc files.
+// Copyright 2005, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+// Author: wan@google.com (Zhanyong Wan)
+//
+// The Google C++ Testing Framework (Google Test)
+
+// Copyright 2007, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+// Author: wan@google.com (Zhanyong Wan)
+//
+// Utilities for testing Google Test itself and code that uses Google Test
+// (e.g. frameworks built on top of Google Test).
+
+#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
+#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
+
+
+namespace testing {
+
+// This helper class can be used to mock out Google Test failure reporting
+// so that we can test Google Test or code that builds on Google Test.
+//
+// An object of this class appends a TestPartResult object to the
+// TestPartResultArray object given in the constructor whenever a Google Test
+// failure is reported. It can either intercept only failures that are
+// generated in the same thread that created this object or it can intercept
+// all generated failures. The scope of this mock object can be controlled with
+// the second argument to the two arguments constructor.
+class GTEST_API_ ScopedFakeTestPartResultReporter
+    : public TestPartResultReporterInterface {
+ public:
+  // The two possible mocking modes of this object.
+  enum InterceptMode {
+    INTERCEPT_ONLY_CURRENT_THREAD,  // Intercepts only thread local failures.
+    INTERCEPT_ALL_THREADS           // Intercepts all failures.
+  };
+
+  // The c'tor sets this object as the test part result reporter used
+  // by Google Test.  The 'result' parameter specifies where to report the
+  // results. This reporter will only catch failures generated in the current
+  // thread. DEPRECATED
+  explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
+
+  // Same as above, but you can choose the interception scope of this object.
+  ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
+                                   TestPartResultArray* result);
+
+  // The d'tor restores the previous test part result reporter.
+  virtual ~ScopedFakeTestPartResultReporter();
+
+  // Appends the TestPartResult object to the TestPartResultArray
+  // received in the constructor.
+  //
+  // This method is from the TestPartResultReporterInterface
+  // interface.
+  virtual void ReportTestPartResult(const TestPartResult& result);
+ private:
+  void Init();
+
+  const InterceptMode intercept_mode_;
+  TestPartResultReporterInterface* old_reporter_;
+  TestPartResultArray* const result_;
+
+  GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
+};
+
+namespace internal {
+
+// A helper class for implementing EXPECT_FATAL_FAILURE() and
+// EXPECT_NONFATAL_FAILURE().  Its destructor verifies that the given
+// TestPartResultArray contains exactly one failure that has the given
+// type and contains the given substring.  If that's not the case, a
+// non-fatal failure will be generated.
+class GTEST_API_ SingleFailureChecker {
+ public:
+  // The constructor remembers the arguments.
+  SingleFailureChecker(const TestPartResultArray* results,
+                       TestPartResult::Type type,
+                       const string& substr);
+  ~SingleFailureChecker();
+ private:
+  const TestPartResultArray* const results_;
+  const TestPartResult::Type type_;
+  const string substr_;
+
+  GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
+};
+
+}  // namespace internal
+
+}  // namespace testing
+
+// A set of macros for testing Google Test assertions or code that's expected
+// to generate Google Test fatal failures.  It verifies that the given
+// statement will cause exactly one fatal Google Test failure with 'substr'
+// being part of the failure message.
+//
+// There are two different versions of this macro. EXPECT_FATAL_FAILURE only
+// affects and considers failures generated in the current thread and
+// EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
+//
+// The verification of the assertion is done correctly even when the statement
+// throws an exception or aborts the current function.
+//
+// Known restrictions:
+//   - 'statement' cannot reference local non-static variables or
+//     non-static members of the current object.
+//   - 'statement' cannot return a value.
+//   - You cannot stream a failure message to this macro.
+//
+// Note that even though the implementations of the following two
+// macros are much alike, we cannot refactor them to use a common
+// helper macro, due to some peculiarity in how the preprocessor
+// works.  The AcceptsMacroThatExpandsToUnprotectedComma test in
+// gtest_unittest.cc will fail to compile if we do that.
+#define EXPECT_FATAL_FAILURE(statement, substr) \
+  do { \
+    class GTestExpectFatalFailureHelper {\
+     public:\
+      static void Execute() { statement; }\
+    };\
+    ::testing::TestPartResultArray gtest_failures;\
+    ::testing::internal::SingleFailureChecker gtest_checker(\
+        &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
+    {\
+      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
+          ::testing::ScopedFakeTestPartResultReporter:: \
+          INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
+      GTestExpectFatalFailureHelper::Execute();\
+    }\
+  } while (::testing::internal::AlwaysFalse())
+
+#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
+  do { \
+    class GTestExpectFatalFailureHelper {\
+     public:\
+      static void Execute() { statement; }\
+    };\
+    ::testing::TestPartResultArray gtest_failures;\
+    ::testing::internal::SingleFailureChecker gtest_checker(\
+        &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
+    {\
+      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
+          ::testing::ScopedFakeTestPartResultReporter:: \
+          INTERCEPT_ALL_THREADS, &gtest_failures);\
+      GTestExpectFatalFailureHelper::Execute();\
+    }\
+  } while (::testing::internal::AlwaysFalse())
+
+// A macro for testing Google Test assertions or code that's expected to
+// generate Google Test non-fatal failures.  It asserts that the given
+// statement will cause exactly one non-fatal Google Test failure with 'substr'
+// being part of the failure message.
+//
+// There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
+// affects and considers failures generated in the current thread and
+// EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
+//
+// 'statement' is allowed to reference local variables and members of
+// the current object.
+//
+// The verification of the assertion is done correctly even when the statement
+// throws an exception or aborts the current function.
+//
+// Known restrictions:
+//   - You cannot stream a failure message to this macro.
+//
+// Note that even though the implementations of the following two
+// macros are much alike, we cannot refactor them to use a common
+// helper macro, due to some peculiarity in how the preprocessor
+// works.  If we do that, the code won't compile when the user gives
+// EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
+// expands to code containing an unprotected comma.  The
+// AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
+// catches that.
+//
+// For the same reason, we have to write
+//   if (::testing::internal::AlwaysTrue()) { statement; }
+// instead of
+//   GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
+// to avoid an MSVC warning on unreachable code.
+#define EXPECT_NONFATAL_FAILURE(statement, substr) \
+  do {\
+    ::testing::TestPartResultArray gtest_failures;\
+    ::testing::internal::SingleFailureChecker gtest_checker(\
+        &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
+        (substr));\
+    {\
+      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
+          ::testing::ScopedFakeTestPartResultReporter:: \
+          INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
+      if (::testing::internal::AlwaysTrue()) { statement; }\
+    }\
+  } while (::testing::internal::AlwaysFalse())
+
+#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
+  do {\
+    ::testing::TestPartResultArray gtest_failures;\
+    ::testing::internal::SingleFailureChecker gtest_checker(\
+        &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
+        (substr));\
+    {\
+      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
+          ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
+          &gtest_failures);\
+      if (::testing::internal::AlwaysTrue()) { statement; }\
+    }\
+  } while (::testing::internal::AlwaysFalse())
+
+#endif  // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
+
+#include <ctype.h>
+#include <math.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <time.h>
+#include <wchar.h>
+#include <wctype.h>
+
+#include <algorithm>
+#include <iomanip>
+#include <limits>
+#include <list>
+#include <map>
+#include <ostream>  // NOLINT
+#include <sstream>
+#include <vector>
+
+#if GTEST_OS_LINUX
+
+// TODO(kenton@google.com): Use autoconf to detect availability of
+// gettimeofday().
+# define GTEST_HAS_GETTIMEOFDAY_ 1
+
+# include <fcntl.h>  // NOLINT
+# include <limits.h>  // NOLINT
+# include <sched.h>  // NOLINT
+// Declares vsnprintf().  This header is not available on Windows.
+# include <strings.h>  // NOLINT
+# include <sys/mman.h>  // NOLINT
+# include <sys/time.h>  // NOLINT
+# include <unistd.h>  // NOLINT
+# include <string>
+
+#elif GTEST_OS_SYMBIAN
+# define GTEST_HAS_GETTIMEOFDAY_ 1
+# include <sys/time.h>  // NOLINT
+
+#elif GTEST_OS_ZOS
+# define GTEST_HAS_GETTIMEOFDAY_ 1
+# include <sys/time.h>  // NOLINT
+
+// On z/OS we additionally need strings.h for strcasecmp.
+# include <strings.h>  // NOLINT
+
+#elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.
+
+# include <windows.h>  // NOLINT
+# undef min
+
+#elif GTEST_OS_WINDOWS  // We are on Windows proper.
+
+# include <io.h>  // NOLINT
+# include <sys/timeb.h>  // NOLINT
+# include <sys/types.h>  // NOLINT
+# include <sys/stat.h>  // NOLINT
+
+# if GTEST_OS_WINDOWS_MINGW
+// MinGW has gettimeofday() but not _ftime64().
+// TODO(kenton@google.com): Use autoconf to detect availability of
+//   gettimeofday().
+// TODO(kenton@google.com): There are other ways to get the time on
+//   Windows, like GetTickCount() or GetSystemTimeAsFileTime().  MinGW
+//   supports these.  consider using them instead.
+#  define GTEST_HAS_GETTIMEOFDAY_ 1
+#  include <sys/time.h>  // NOLINT
+# endif  // GTEST_OS_WINDOWS_MINGW
+
+// cpplint thinks that the header is already included, so we want to
+// silence it.
+# include <windows.h>  // NOLINT
+# undef min
+
+#else
+
+// Assume other platforms have gettimeofday().
+// TODO(kenton@google.com): Use autoconf to detect availability of
+//   gettimeofday().
+# define GTEST_HAS_GETTIMEOFDAY_ 1
+
+// cpplint thinks that the header is already included, so we want to
+// silence it.
+# include <sys/time.h>  // NOLINT
+# include <unistd.h>  // NOLINT
+
+#endif  // GTEST_OS_LINUX
+
+#if GTEST_HAS_EXCEPTIONS
+# include <stdexcept>
+#endif
+
+#if GTEST_CAN_STREAM_RESULTS_
+# include <arpa/inet.h>  // NOLINT
+# include <netdb.h>  // NOLINT
+# include <sys/socket.h>  // NOLINT
+# include <sys/types.h>  // NOLINT
+#endif
+
+// Indicates that this translation unit is part of Google Test's
+// implementation.  It must come before gtest-internal-inl.h is
+// included, or there will be a compiler error.  This trick is to
+// prevent a user from accidentally including gtest-internal-inl.h in
+// his code.
+#define GTEST_IMPLEMENTATION_ 1
+// Copyright 2005, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Utility functions and classes used by the Google C++ testing framework.
+//
+// Author: wan@google.com (Zhanyong Wan)
+//
+// This file contains purely Google Test's internal implementation.  Please
+// DO NOT #INCLUDE IT IN A USER PROGRAM.
+
+#ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
+#define GTEST_SRC_GTEST_INTERNAL_INL_H_
+
+// GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
+// part of Google Test's implementation; otherwise it's undefined.
+#if !GTEST_IMPLEMENTATION_
+// If this file is included from the user's code, just say no.
+# error "gtest-internal-inl.h is part of Google Test's internal implementation."
+# error "It must not be included except by Google Test itself."
+#endif  // GTEST_IMPLEMENTATION_
+
+#ifndef _WIN32_WCE
+# include <errno.h>
+#endif  // !_WIN32_WCE
+#include <stddef.h>
+#include <stdlib.h>  // For strtoll/_strtoul64/malloc/free.
+#include <string.h>  // For memmove.
+
+#include <algorithm>
+#include <string>
+#include <vector>
+
+
+#if GTEST_CAN_STREAM_RESULTS_
+# include <arpa/inet.h>  // NOLINT
+# include <netdb.h>  // NOLINT
+#endif
+
+#if GTEST_OS_WINDOWS
+# include <windows.h>  // NOLINT
+#endif  // GTEST_OS_WINDOWS
+
+
+namespace testing {
+
+// Declares the flags.
+//
+// We don't want the users to modify this flag in the code, but want
+// Google Test's own unit tests to be able to access it. Therefore we
+// declare it here as opposed to in gtest.h.
+GTEST_DECLARE_bool_(death_test_use_fork);
+
+namespace internal {
+
+// The value of GetTestTypeId() as seen from within the Google Test
+// library.  This is solely for testing GetTestTypeId().
+GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
+
+// Names of the flags (needed for parsing Google Test flags).
+const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
+const char kBreakOnFailureFlag[] = "break_on_failure";
+const char kCatchExceptionsFlag[] = "catch_exceptions";
+const char kColorFlag[] = "color";
+const char kFilterFlag[] = "filter";
+const char kListTestsFlag[] = "list_tests";
+const char kOutputFlag[] = "output";
+const char kPrintTimeFlag[] = "print_time";
+const char kRandomSeedFlag[] = "random_seed";
+const char kRepeatFlag[] = "repeat";
+const char kShuffleFlag[] = "shuffle";
+const char kStackTraceDepthFlag[] = "stack_trace_depth";
+const char kStreamResultToFlag[] = "stream_result_to";
+const char kThrowOnFailureFlag[] = "throw_on_failure";
+const char kFlagfileFlag[] = "flagfile";
+
+// A valid random seed must be in [1, kMaxRandomSeed].
+const int kMaxRandomSeed = 99999;
+
+// g_help_flag is true iff the --help flag or an equivalent form is
+// specified on the command line.
+GTEST_API_ extern bool g_help_flag;
+
+// Returns the current time in milliseconds.
+GTEST_API_ TimeInMillis GetTimeInMillis();
+
+// Returns true iff Google Test should use colors in the output.
+GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
+
+// Formats the given time in milliseconds as seconds.
+GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
+
+// Converts the given time in milliseconds to a date string in the ISO 8601
+// format, without the timezone information.  N.B.: due to the use the
+// non-reentrant localtime() function, this function is not thread safe.  Do
+// not use it in any code that can be called from multiple threads.
+GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
+
+// Parses a string for an Int32 flag, in the form of "--flag=value".
+//
+// On success, stores the value of the flag in *value, and returns
+// true.  On failure, returns false without changing *value.
+GTEST_API_ bool ParseInt32Flag(
+    const char* str, const char* flag, Int32* value);
+
+// Returns a random seed in range [1, kMaxRandomSeed] based on the
+// given --gtest_random_seed flag value.
+inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
+  const unsigned int raw_seed = (random_seed_flag == 0) ?
+      static_cast<unsigned int>(GetTimeInMillis()) :
+      static_cast<unsigned int>(random_seed_flag);
+
+  // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
+  // it's easy to type.
+  const int normalized_seed =
+      static_cast<int>((raw_seed - 1U) %
+                       static_cast<unsigned int>(kMaxRandomSeed)) + 1;
+  return normalized_seed;
+}
+
+// Returns the first valid random seed after 'seed'.  The behavior is
+// undefined if 'seed' is invalid.  The seed after kMaxRandomSeed is
+// considered to be 1.
+inline int GetNextRandomSeed(int seed) {
+  GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
+      << "Invalid random seed " << seed << " - must be in [1, "
+      << kMaxRandomSeed << "].";
+  const int next_seed = seed + 1;
+  return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
+}
+
+// This class saves the values of all Google Test flags in its c'tor, and
+// restores them in its d'tor.
+class GTestFlagSaver {
+ public:
+  // The c'tor.
+  GTestFlagSaver() {
+    also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
+    break_on_failure_ = GTEST_FLAG(break_on_failure);
+    catch_exceptions_ = GTEST_FLAG(catch_exceptions);
+    color_ = GTEST_FLAG(color);
+    death_test_style_ = GTEST_FLAG(death_test_style);
+    death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
+    filter_ = GTEST_FLAG(filter);
+    internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
+    list_tests_ = GTEST_FLAG(list_tests);
+    output_ = GTEST_FLAG(output);
+    print_time_ = GTEST_FLAG(print_time);
+    random_seed_ = GTEST_FLAG(random_seed);
+    repeat_ = GTEST_FLAG(repeat);
+    shuffle_ = GTEST_FLAG(shuffle);
+    stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
+    stream_result_to_ = GTEST_FLAG(stream_result_to);
+    throw_on_failure_ = GTEST_FLAG(throw_on_failure);
+  }
+
+  // The d'tor is not virtual.  DO NOT INHERIT FROM THIS CLASS.
+  ~GTestFlagSaver() {
+    GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
+    GTEST_FLAG(break_on_failure) = break_on_failure_;
+    GTEST_FLAG(catch_exceptions) = catch_exceptions_;
+    GTEST_FLAG(color) = color_;
+    GTEST_FLAG(death_test_style) = death_test_style_;
+    GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
+    GTEST_FLAG(filter) = filter_;
+    GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
+    GTEST_FLAG(list_tests) = list_tests_;
+    GTEST_FLAG(output) = output_;
+    GTEST_FLAG(print_time) = print_time_;
+    GTEST_FLAG(random_seed) = random_seed_;
+    GTEST_FLAG(repeat) = repeat_;
+    GTEST_FLAG(shuffle) = shuffle_;
+    GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
+    GTEST_FLAG(stream_result_to) = stream_result_to_;
+    GTEST_FLAG(throw_on_failure) = throw_on_failure_;
+  }
+
+ private:
+  // Fields for saving the original values of flags.
+  bool also_run_disabled_tests_;
+  bool break_on_failure_;
+  bool catch_exceptions_;
+  std::string color_;
+  std::string death_test_style_;
+  bool death_test_use_fork_;
+  std::string filter_;
+  std::string internal_run_death_test_;
+  bool list_tests_;
+  std::string output_;
+  bool print_time_;
+  internal::Int32 random_seed_;
+  internal::Int32 repeat_;
+  bool shuffle_;
+  internal::Int32 stack_trace_depth_;
+  std::string stream_result_to_;
+  bool throw_on_failure_;
+} GTEST_ATTRIBUTE_UNUSED_;
+
+// Converts a Unicode code point to a narrow string in UTF-8 encoding.
+// code_point parameter is of type UInt32 because wchar_t may not be
+// wide enough to contain a code point.
+// If the code_point is not a valid Unicode code point
+// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
+// to "(Invalid Unicode 0xXXXXXXXX)".
+GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
+
+// Converts a wide string to a narrow string in UTF-8 encoding.
+// The wide string is assumed to have the following encoding:
+//   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
+//   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
+// Parameter str points to a null-terminated wide string.
+// Parameter num_chars may additionally limit the number
+// of wchar_t characters processed. -1 is used when the entire string
+// should be processed.
+// If the string contains code points that are not valid Unicode code points
+// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
+// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
+// and contains invalid UTF-16 surrogate pairs, values in those pairs
+// will be encoded as individual Unicode characters from Basic Normal Plane.
+GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
+
+// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
+// if the variable is present. If a file already exists at this location, this
+// function will write over it. If the variable is present, but the file cannot
+// be created, prints an error and exits.
+void WriteToShardStatusFileIfNeeded();
+
+// Checks whether sharding is enabled by examining the relevant
+// environment variable values. If the variables are present,
+// but inconsistent (e.g., shard_index >= total_shards), prints
+// an error and exits. If in_subprocess_for_death_test, sharding is
+// disabled because it must only be applied to the original test
+// process. Otherwise, we could filter out death tests we intended to execute.
+GTEST_API_ bool ShouldShard(const char* total_shards_str,
+                            const char* shard_index_str,
+                            bool in_subprocess_for_death_test);
+
+// Parses the environment variable var as an Int32. If it is unset,
+// returns default_val. If it is not an Int32, prints an error and
+// and aborts.
+GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
+
+// Given the total number of shards, the shard index, and the test id,
+// returns true iff the test should be run on this shard. The test id is
+// some arbitrary but unique non-negative integer assigned to each test
+// method. Assumes that 0 <= shard_index < total_shards.
+GTEST_API_ bool ShouldRunTestOnShard(
+    int total_shards, int shard_index, int test_id);
+
+// STL container utilities.
+
+// Returns the number of elements in the given container that satisfy
+// the given predicate.
+template <class Container, typename Predicate>
+inline int CountIf(const Container& c, Predicate predicate) {
+  // Implemented as an explicit loop since std::count_if() in libCstd on
+  // Solaris has a non-standard signature.
+  int count = 0;
+  for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
+    if (predicate(*it))
+      ++count;
+  }
+  return count;
+}
+
+// Applies a function/functor to each element in the container.
+template <class Container, typename Functor>
+void ForEach(const Container& c, Functor functor) {
+  std::for_each(c.begin(), c.end(), functor);
+}
+
+// Returns the i-th element of the vector, or default_value if i is not
+// in range [0, v.size()).
+template <typename E>
+inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
+  return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
+}
+
+// Performs an in-place shuffle of a range of the vector's elements.
+// 'begin' and 'end' are element indices as an STL-style range;
+// i.e. [begin, end) are shuffled, where 'end' == size() means to
+// shuffle to the end of the vector.
+template <typename E>
+void ShuffleRange(internal::Random* random, int begin, int end,
+                  std::vector<E>* v) {
+  const int size = static_cast<int>(v->size());
+  GTEST_CHECK_(0 <= begin && begin <= size)
+      << "Invalid shuffle range start " << begin << ": must be in range [0, "
+      << size << "].";
+  GTEST_CHECK_(begin <= end && end <= size)
+      << "Invalid shuffle range finish " << end << ": must be in range ["
+      << begin << ", " << size << "].";
+
+  // Fisher-Yates shuffle, from
+  // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
+  for (int range_width = end - begin; range_width >= 2; range_width--) {
+    const int last_in_range = begin + range_width - 1;
+    const int selected = begin + random->Generate(range_width);
+    std::swap((*v)[selected], (*v)[last_in_range]);
+  }
+}
+
+// Performs an in-place shuffle of the vector's elements.
+template <typename E>
+inline void Shuffle(internal::Random* random, std::vector<E>* v) {
+  ShuffleRange(random, 0, static_cast<int>(v->size()), v);
+}
+
+// A function for deleting an object.  Handy for being used as a
+// functor.
+template <typename T>
+static void Delete(T* x) {
+  delete x;
+}
+
+// A predicate that checks the key of a TestProperty against a known key.
+//
+// TestPropertyKeyIs is copyable.
+class TestPropertyKeyIs {
+ public:
+  // Constructor.
+  //
+  // TestPropertyKeyIs has NO default constructor.
+  explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
+
+  // Returns true iff the test name of test property matches on key_.
+  bool operator()(const TestProperty& test_property) const {
+    return test_property.key() == key_;
+  }
+
+ private:
+  std::string key_;
+};
+
+// Class UnitTestOptions.
+//
+// This class contains functions for processing options the user
+// specifies when running the tests.  It has only static members.
+//
+// In most cases, the user can specify an option using either an
+// environment variable or a command line flag.  E.g. you can set the
+// test filter using either GTEST_FILTER or --gtest_filter.  If both
+// the variable and the flag are present, the latter overrides the
+// former.
+class GTEST_API_ UnitTestOptions {
+ public:
+  // Functions for processing the gtest_output flag.
+
+  // Returns the output format, or "" for normal printed output.
+  static std::string GetOutputFormat();
+
+  // Returns the absolute path of the requested output file, or the
+  // default (test_detail.xml in the original working directory) if
+  // none was explicitly specified.
+  static std::string GetAbsolutePathToOutputFile();
+
+  // Functions for processing the gtest_filter flag.
+
+  // Returns true iff the wildcard pattern matches the string.  The
+  // first ':' or '\0' character in pattern marks the end of it.
+  //
+  // This recursive algorithm isn't very efficient, but is clear and
+  // works well enough for matching test names, which are short.
+  static bool PatternMatchesString(const char *pattern, const char *str);
+
+  // Returns true iff the user-specified filter matches the test case
+  // name and the test name.
+  static bool FilterMatchesTest(const std::string &test_case_name,
+                                const std::string &test_name);
+
+#if GTEST_OS_WINDOWS
+  // Function for supporting the gtest_catch_exception flag.
+
+  // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
+  // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
+  // This function is useful as an __except condition.
+  static int GTestShouldProcessSEH(DWORD exception_code);
+#endif  // GTEST_OS_WINDOWS
+
+  // Returns true if "name" matches the ':' separated list of glob-style
+  // filters in "filter".
+  static bool MatchesFilter(const std::string& name, const char* filter);
+};
+
+// Returns the current application's name, removing directory path if that
+// is present.  Used by UnitTestOptions::GetOutputFile.
+GTEST_API_ FilePath GetCurrentExecutableName();
+
+// The role interface for getting the OS stack trace as a string.
+class OsStackTraceGetterInterface {
+ public:
+  OsStackTraceGetterInterface() {}
+  virtual ~OsStackTraceGetterInterface() {}
+
+  // Returns the current OS stack trace as an std::string.  Parameters:
+  //
+  //   max_depth  - the maximum number of stack frames to be included
+  //                in the trace.
+  //   skip_count - the number of top frames to be skipped; doesn't count
+  //                against max_depth.
+  virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;
+
+  // UponLeavingGTest() should be called immediately before Google Test calls
+  // user code. It saves some information about the current stack that
+  // CurrentStackTrace() will use to find and hide Google Test stack frames.
+  virtual void UponLeavingGTest() = 0;
+
+  // This string is inserted in place of stack frames that are part of
+  // Google Test's implementation.
+  static const char* const kElidedFramesMarker;
+
+ private:
+  GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
+};
+
+// A working implementation of the OsStackTraceGetterInterface interface.
+class OsStackTraceGetter : public OsStackTraceGetterInterface {
+ public:
+  OsStackTraceGetter() {}
+
+  virtual string CurrentStackTrace(int max_depth, int skip_count);
+  virtual void UponLeavingGTest();
+
+ private:
+  GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
+};
+
+// Information about a Google Test trace point.
+struct TraceInfo {
+  const char* file;
+  int line;
+  std::string message;
+};
+
+// This is the default global test part result reporter used in UnitTestImpl.
+// This class should only be used by UnitTestImpl.
+class DefaultGlobalTestPartResultReporter
+  : public TestPartResultReporterInterface {
+ public:
+  explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
+  // Implements the TestPartResultReporterInterface. Reports the test part
+  // result in the current test.
+  virtual void ReportTestPartResult(const TestPartResult& result);
+
+ private:
+  UnitTestImpl* const unit_test_;
+
+  GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
+};
+
+// This is the default per thread test part result reporter used in
+// UnitTestImpl. This class should only be used by UnitTestImpl.
+class DefaultPerThreadTestPartResultReporter
+    : public TestPartResultReporterInterface {
+ public:
+  explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
+  // Implements the TestPartResultReporterInterface. The implementation just
+  // delegates to the current global test part result reporter of *unit_test_.
+  virtual void ReportTestPartResult(const TestPartResult& result);
+
+ private:
+  UnitTestImpl* const unit_test_;
+
+  GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
+};
+
+// The private implementation of the UnitTest class.  We don't protect
+// the methods under a mutex, as this class is not accessible by a
+// user and the UnitTest class that delegates work to this class does
+// proper locking.
+class GTEST_API_ UnitTestImpl {
+ public:
+  explicit UnitTestImpl(UnitTest* parent);
+  virtual ~UnitTestImpl();
+
+  // There are two different ways to register your own TestPartResultReporter.
+  // You can register your own repoter to listen either only for test results
+  // from the current thread or for results from all threads.
+  // By default, each per-thread test result repoter just passes a new
+  // TestPartResult to the global test result reporter, which registers the
+  // test part result for the currently running test.
+
+  // Returns the global test part result reporter.
+  TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
+
+  // Sets the global test part result reporter.
+  void SetGlobalTestPartResultReporter(
+      TestPartResultReporterInterface* reporter);
+
+  // Returns the test part result reporter for the current thread.
+  TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
+
+  // Sets the test part result reporter for the current thread.
+  void SetTestPartResultReporterForCurrentThread(
+      TestPartResultReporterInterface* reporter);
+
+  // Gets the number of successful test cases.
+  int successful_test_case_count() const;
+
+  // Gets the number of failed test cases.
+  int failed_test_case_count() const;
+
+  // Gets the number of all test cases.
+  int total_test_case_count() const;
+
+  // Gets the number of all test cases that contain at least one test
+  // that should run.
+  int test_case_to_run_count() const;
+
+  // Gets the number of successful tests.
+  int successful_test_count() const;
+
+  // Gets the number of failed tests.
+  int failed_test_count() const;
+
+  // Gets the number of disabled tests that will be reported in the XML report.
+  int reportable_disabled_test_count() const;
+
+  // Gets the number of disabled tests.
+  int disabled_test_count() const;
+
+  // Gets the number of tests to be printed in the XML report.
+  int reportable_test_count() const;
+
+  // Gets the number of all tests.
+  int total_test_count() const;
+
+  // Gets the number of tests that should run.
+  int test_to_run_count() const;
+
+  // Gets the time of the test program start, in ms from the start of the
+  // UNIX epoch.
+  TimeInMillis start_timestamp() const { return start_timestamp_; }
+
+  // Gets the elapsed time, in milliseconds.
+  TimeInMillis elapsed_time() const { return elapsed_time_; }
+
+  // Returns true iff the unit test passed (i.e. all test cases passed).
+  bool Passed() const { return !Failed(); }
+
+  // Returns true iff the unit test failed (i.e. some test case failed
+  // or something outside of all tests failed).
+  bool Failed() const {
+    return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
+  }
+
+  // Gets the i-th test case among all the test cases. i can range from 0 to
+  // total_test_case_count() - 1. If i is not in that range, returns NULL.
+  const TestCase* GetTestCase(int i) const {
+    const int index = GetElementOr(test_case_indices_, i, -1);
+    return index < 0 ? NULL : test_cases_[i];
+  }
+
+  // Gets the i-th test case among all the test cases. i can range from 0 to
+  // total_test_case_count() - 1. If i is not in that range, returns NULL.
+  TestCase* GetMutableTestCase(int i) {
+    const int index = GetElementOr(test_case_indices_, i, -1);
+    return index < 0 ? NULL : test_cases_[index];
+  }
+
+  // Provides access to the event listener list.
+  TestEventListeners* listeners() { return &listeners_; }
+
+  // Returns the TestResult for the test that's currently running, or
+  // the TestResult for the ad hoc test if no test is running.
+  TestResult* current_test_result();
+
+  // Returns the TestResult for the ad hoc test.
+  const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
+
+  // Sets the OS stack trace getter.
+  //
+  // Does nothing if the input and the current OS stack trace getter
+  // are the same; otherwise, deletes the old getter and makes the
+  // input the current getter.
+  void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
+
+  // Returns the current OS stack trace getter if it is not NULL;
+  // otherwise, creates an OsStackTraceGetter, makes it the current
+  // getter, and returns it.
+  OsStackTraceGetterInterface* os_stack_trace_getter();
+
+  // Returns the current OS stack trace as an std::string.
+  //
+  // The maximum number of stack frames to be included is specified by
+  // the gtest_stack_trace_depth flag.  The skip_count parameter
+  // specifies the number of top frames to be skipped, which doesn't
+  // count against the number of frames to be included.
+  //
+  // For example, if Foo() calls Bar(), which in turn calls
+  // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
+  // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
+  std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
+
+  // Finds and returns a TestCase with the given name.  If one doesn't
+  // exist, creates one and returns it.
+  //
+  // Arguments:
+  //
+  //   test_case_name: name of the test case
+  //   type_param:     the name of the test's type parameter, or NULL if
+  //                   this is not a typed or a type-parameterized test.
+  //   set_up_tc:      pointer to the function that sets up the test case
+  //   tear_down_tc:   pointer to the function that tears down the test case
+  TestCase* GetTestCase(const char* test_case_name,
+                        const char* type_param,
+                        Test::SetUpTestCaseFunc set_up_tc,
+                        Test::TearDownTestCaseFunc tear_down_tc);
+
+  // Adds a TestInfo to the unit test.
+  //
+  // Arguments:
+  //
+  //   set_up_tc:    pointer to the function that sets up the test case
+  //   tear_down_tc: pointer to the function that tears down the test case
+  //   test_info:    the TestInfo object
+  void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
+                   Test::TearDownTestCaseFunc tear_down_tc,
+                   TestInfo* test_info) {
+    // In order to support thread-safe death tests, we need to
+    // remember the original working directory when the test program
+    // was first invoked.  We cannot do this in RUN_ALL_TESTS(), as
+    // the user may have changed the current directory before calling
+    // RUN_ALL_TESTS().  Therefore we capture the current directory in
+    // AddTestInfo(), which is called to register a TEST or TEST_F
+    // before main() is reached.
+    if (original_working_dir_.IsEmpty()) {
+      original_working_dir_.Set(FilePath::GetCurrentDir());
+      GTEST_CHECK_(!original_working_dir_.IsEmpty())
+          << "Failed to get the current working directory.";
+    }
+
+    GetTestCase(test_info->test_case_name(),
+                test_info->type_param(),
+                set_up_tc,
+                tear_down_tc)->AddTestInfo(test_info);
+  }
+
+#if GTEST_HAS_PARAM_TEST
+  // Returns ParameterizedTestCaseRegistry object used to keep track of
+  // value-parameterized tests and instantiate and register them.
+  internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
+    return parameterized_test_registry_;
+  }
+#endif  // GTEST_HAS_PARAM_TEST
+
+  // Sets the TestCase object for the test that's currently running.
+  void set_current_test_case(TestCase* a_current_test_case) {
+    current_test_case_ = a_current_test_case;
+  }
+
+  // Sets the TestInfo object for the test that's currently running.  If
+  // current_test_info is NULL, the assertion results will be stored in
+  // ad_hoc_test_result_.
+  void set_current_test_info(TestInfo* a_current_test_info) {
+    current_test_info_ = a_current_test_info;
+  }
+
+  // Registers all parameterized tests defined using TEST_P and
+  // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
+  // combination. This method can be called more then once; it has guards
+  // protecting from registering the tests more then once.  If
+  // value-parameterized tests are disabled, RegisterParameterizedTests is
+  // present but does nothing.
+  void RegisterParameterizedTests();
+
+  // Runs all tests in this UnitTest object, prints the result, and
+  // returns true if all tests are successful.  If any exception is
+  // thrown during a test, this test is considered to be failed, but
+  // the rest of the tests will still be run.
+  bool RunAllTests();
+
+  // Clears the results of all tests, except the ad hoc tests.
+  void ClearNonAdHocTestResult() {
+    ForEach(test_cases_, TestCase::ClearTestCaseResult);
+  }
+
+  // Clears the results of ad-hoc test assertions.
+  void ClearAdHocTestResult() {
+    ad_hoc_test_result_.Clear();
+  }
+
+  // Adds a TestProperty to the current TestResult object when invoked in a
+  // context of a test or a test case, or to the global property set. If the
+  // result already contains a property with the same key, the value will be
+  // updated.
+  void RecordProperty(const TestProperty& test_property);
+
+  enum ReactionToSharding {
+    HONOR_SHARDING_PROTOCOL,
+    IGNORE_SHARDING_PROTOCOL
+  };
+
+  // Matches the full name of each test against the user-specified
+  // filter to decide whether the test should run, then records the
+  // result in each TestCase and TestInfo object.
+  // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
+  // based on sharding variables in the environment.
+  // Returns the number of tests that should run.
+  int FilterTests(ReactionToSharding shard_tests);
+
+  // Prints the names of the tests matching the user-specified filter flag.
+  void ListTestsMatchingFilter();
+
+  const TestCase* current_test_case() const { return current_test_case_; }
+  TestInfo* current_test_info() { return current_test_info_; }
+  const TestInfo* current_test_info() const { return current_test_info_; }
+
+  // Returns the vector of environments that need to be set-up/torn-down
+  // before/after the tests are run.
+  std::vector<Environment*>& environments() { return environments_; }
+
+  // Getters for the per-thread Google Test trace stack.
+  std::vector<TraceInfo>& gtest_trace_stack() {
+    return *(gtest_trace_stack_.pointer());
+  }
+  const std::vector<TraceInfo>& gtest_trace_stack() const {
+    return gtest_trace_stack_.get();
+  }
+
+#if GTEST_HAS_DEATH_TEST
+  void InitDeathTestSubprocessControlInfo() {
+    internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
+  }
+  // Returns a pointer to the parsed --gtest_internal_run_death_test
+  // flag, or NULL if that flag was not specified.
+  // This information is useful only in a death test child process.
+  // Must not be called before a call to InitGoogleTest.
+  const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
+    return internal_run_death_test_flag_.get();
+  }
+
+  // Returns a pointer to the current death test factory.
+  internal::DeathTestFactory* death_test_factory() {
+    return death_test_factory_.get();
+  }
+
+  void SuppressTestEventsIfInSubprocess();
+
+  friend class ReplaceDeathTestFactory;
+#endif  // GTEST_HAS_DEATH_TEST
+
+  // Initializes the event listener performing XML output as specified by
+  // UnitTestOptions. Must not be called before InitGoogleTest.
+  void ConfigureXmlOutput();
+
+#if GTEST_CAN_STREAM_RESULTS_
+  // Initializes the event listener for streaming test results to a socket.
+  // Must not be called before InitGoogleTest.
+  void ConfigureStreamingOutput();
+#endif
+
+  // Performs initialization dependent upon flag values obtained in
+  // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
+  // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
+  // this function is also called from RunAllTests.  Since this function can be
+  // called more than once, it has to be idempotent.
+  void PostFlagParsingInit();
+
+  // Gets the random seed used at the start of the current test iteration.
+  int random_seed() const { return random_seed_; }
+
+  // Gets the random number generator.
+  internal::Random* random() { return &random_; }
+
+  // Shuffles all test cases, and the tests within each test case,
+  // making sure that death tests are still run first.
+  void ShuffleTests();
+
+  // Restores the test cases and tests to their order before the first shuffle.
+  void UnshuffleTests();
+
+  // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
+  // UnitTest::Run() starts.
+  bool catch_exceptions() const { return catch_exceptions_; }
+
+ private:
+  friend class ::testing::UnitTest;
+
+  // Used by UnitTest::Run() to capture the state of
+  // GTEST_FLAG(catch_exceptions) at the moment it starts.
+  void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
+
+  // The UnitTest object that owns this implementation object.
+  UnitTest* const parent_;
+
+  // The working directory when the first TEST() or TEST_F() was
+  // executed.
+  internal::FilePath original_working_dir_;
+
+  // The default test part result reporters.
+  DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
+  DefaultPerThreadTestPartResultReporter
+      default_per_thread_test_part_result_reporter_;
+
+  // Points to (but doesn't own) the global test part result reporter.
+  TestPartResultReporterInterface* global_test_part_result_repoter_;
+
+  // Protects read and write access to global_test_part_result_reporter_.
+  internal::Mutex global_test_part_result_reporter_mutex_;
+
+  // Points to (but doesn't own) the per-thread test part result reporter.
+  internal::ThreadLocal<TestPartResultReporterInterface*>
+      per_thread_test_part_result_reporter_;
+
+  // The vector of environments that need to be set-up/torn-down
+  // before/after the tests are run.
+  std::vector<Environment*> environments_;
+
+  // The vector of TestCases in their original order.  It owns the
+  // elements in the vector.
+  std::vector<TestCase*> test_cases_;
+
+  // Provides a level of indirection for the test case list to allow
+  // easy shuffling and restoring the test case order.  The i-th
+  // element of this vector is the index of the i-th test case in the
+  // shuffled order.
+  std::vector<int> test_case_indices_;
+
+#if GTEST_HAS_PARAM_TEST
+  // ParameterizedTestRegistry object used to register value-parameterized
+  // tests.
+  internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
+
+  // Indicates whether RegisterParameterizedTests() has been called already.
+  bool parameterized_tests_registered_;
+#endif  // GTEST_HAS_PARAM_TEST
+
+  // Index of the last death test case registered.  Initially -1.
+  int last_death_test_case_;
+
+  // This points to the TestCase for the currently running test.  It
+  // changes as Google Test goes through one test case after another.
+  // When no test is running, this is set to NULL and Google Test
+  // stores assertion results in ad_hoc_test_result_.  Initially NULL.
+  TestCase* current_test_case_;
+
+  // This points to the TestInfo for the currently running test.  It
+  // changes as Google Test goes through one test after another.  When
+  // no test is running, this is set to NULL and Google Test stores
+  // assertion results in ad_hoc_test_result_.  Initially NULL.
+  TestInfo* current_test_info_;
+
+  // Normally, a user only writes assertions inside a TEST or TEST_F,
+  // or inside a function called by a TEST or TEST_F.  Since Google
+  // Test keeps track of which test is current running, it can
+  // associate such an assertion with the test it belongs to.
+  //
+  // If an assertion is encountered when no TEST or TEST_F is running,
+  // Google Test attributes the assertion result to an imaginary "ad hoc"
+  // test, and records the result in ad_hoc_test_result_.
+  TestResult ad_hoc_test_result_;
+
+  // The list of event listeners that can be used to track events inside
+  // Google Test.
+  TestEventListeners listeners_;
+
+  // The OS stack trace getter.  Will be deleted when the UnitTest
+  // object is destructed.  By default, an OsStackTraceGetter is used,
+  // but the user can set this field to use a custom getter if that is
+  // desired.
+  OsStackTraceGetterInterface* os_stack_trace_getter_;
+
+  // True iff PostFlagParsingInit() has been called.
+  bool post_flag_parse_init_performed_;
+
+  // The random number seed used at the beginning of the test run.
+  int random_seed_;
+
+  // Our random number generator.
+  internal::Random random_;
+
+  // The time of the test program start, in ms from the start of the
+  // UNIX epoch.
+  TimeInMillis start_timestamp_;
+
+  // How long the test took to run, in milliseconds.
+  TimeInMillis elapsed_time_;
+
+#if GTEST_HAS_DEATH_TEST
+  // The decomposed components of the gtest_internal_run_death_test flag,
+  // parsed when RUN_ALL_TESTS is called.
+  internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
+  internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
+#endif  // GTEST_HAS_DEATH_TEST
+
+  // A per-thread stack of traces created by the SCOPED_TRACE() macro.
+  internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
+
+  // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
+  // starts.
+  bool catch_exceptions_;
+
+  GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
+};  // class UnitTestImpl
+
+// Convenience function for accessing the global UnitTest
+// implementation object.
+inline UnitTestImpl* GetUnitTestImpl() {
+  return UnitTest::GetInstance()->impl();
+}
+
+#if GTEST_USES_SIMPLE_RE
+
+// Internal helper functions for implementing the simple regular
+// expression matcher.
+GTEST_API_ bool IsInSet(char ch, const char* str);
+GTEST_API_ bool IsAsciiDigit(char ch);
+GTEST_API_ bool IsAsciiPunct(char ch);
+GTEST_API_ bool IsRepeat(char ch);
+GTEST_API_ bool IsAsciiWhiteSpace(char ch);
+GTEST_API_ bool IsAsciiWordChar(char ch);
+GTEST_API_ bool IsValidEscape(char ch);
+GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
+GTEST_API_ bool ValidateRegex(const char* regex);
+GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
+GTEST_API_ bool MatchRepetitionAndRegexAtHead(
+    bool escaped, char ch, char repeat, const char* regex, const char* str);
+GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
+
+#endif  // GTEST_USES_SIMPLE_RE
+
+// Parses the command line for Google Test flags, without initializing
+// other parts of Google Test.
+GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
+GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
+
+#if GTEST_HAS_DEATH_TEST
+
+// Returns the message describing the last system error, regardless of the
+// platform.
+GTEST_API_ std::string GetLastErrnoDescription();
+
+// Attempts to parse a string into a positive integer pointed to by the
+// number parameter.  Returns true if that is possible.
+// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
+// it here.
+template <typename Integer>
+bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
+  // Fail fast if the given string does not begin with a digit;
+  // this bypasses strtoXXX's "optional leading whitespace and plus
+  // or minus sign" semantics, which are undesirable here.
+  if (str.empty() || !IsDigit(str[0])) {
+    return false;
+  }
+  errno = 0;
+
+  char* end;
+  // BiggestConvertible is the largest integer type that system-provided
+  // string-to-number conversion routines can return.
+
+# if GTEST_OS_WINDOWS && !defined(__GNUC__)
+
+  // MSVC and C++ Builder define __int64 instead of the standard long long.
+  typedef unsigned __int64 BiggestConvertible;
+  const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
+
+# else
+
+  typedef unsigned long long BiggestConvertible;  // NOLINT
+  const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
+
+# endif  // GTEST_OS_WINDOWS && !defined(__GNUC__)
+
+  const bool parse_success = *end == '\0' && errno == 0;
+
+  // TODO(vladl@google.com): Convert this to compile time assertion when it is
+  // available.
+  GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
+
+  const Integer result = static_cast<Integer>(parsed);
+  if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
+    *number = result;
+    return true;
+  }
+  return false;
+}
+#endif  // GTEST_HAS_DEATH_TEST
+
+// TestResult contains some private methods that should be hidden from
+// Google Test user but are required for testing. This class allow our tests
+// to access them.
+//
+// This class is supplied only for the purpose of testing Google Test's own
+// constructs. Do not use it in user tests, either directly or indirectly.
+class TestResultAccessor {
+ public:
+  static void RecordProperty(TestResult* test_result,
+                             const std::string& xml_element,
+                             const TestProperty& property) {
+    test_result->RecordProperty(xml_element, property);
+  }
+
+  static void ClearTestPartResults(TestResult* test_result) {
+    test_result->ClearTestPartResults();
+  }
+
+  static const std::vector<testing::TestPartResult>& test_part_results(
+      const TestResult& test_result) {
+    return test_result.test_part_results();
+  }
+};
+
+#if GTEST_CAN_STREAM_RESULTS_
+
+// Streams test results to the given port on the given host machine.
+class GTEST_API_ StreamingListener : public EmptyTestEventListener {
+ public:
+  // Abstract base class for writing strings to a socket.
+  class AbstractSocketWriter {
+   public:
+    virtual ~AbstractSocketWriter() {}
+
+    // Sends a string to the socket.
+    virtual void Send(const string& message) = 0;
+
+    // Closes the socket.
+    virtual void CloseConnection() {}
+
+    // Sends a string and a newline to the socket.
+    void SendLn(const string& message) {
+      Send(message + "\n");
+    }
+  };
+
+  // Concrete class for actually writing strings to a socket.
+  class SocketWriter : public AbstractSocketWriter {
+   public:
+    SocketWriter(const string& host, const string& port)
+        : sockfd_(-1), host_name_(host), port_num_(port) {
+      MakeConnection();
+    }
+
+    virtual ~SocketWriter() {
+      if (sockfd_ != -1)
+        CloseConnection();
+    }
+
+    // Sends a string to the socket.
+    virtual void Send(const string& message) {
+      GTEST_CHECK_(sockfd_ != -1)
+          << "Send() can be called only when there is a connection.";
+
+      const int len = static_cast<int>(message.length());
+      if (write(sockfd_, message.c_str(), len) != len) {
+        GTEST_LOG_(WARNING)
+            << "stream_result_to: failed to stream to "
+            << host_name_ << ":" << port_num_;
+      }
+    }
+
+   private:
+    // Creates a client socket and connects to the server.
+    void MakeConnection();
+
+    // Closes the socket.
+    void CloseConnection() {
+      GTEST_CHECK_(sockfd_ != -1)
+          << "CloseConnection() can be called only when there is a connection.";
+
+      close(sockfd_);
+      sockfd_ = -1;
+    }
+
+    int sockfd_;  // socket file descriptor
+    const string host_name_;
+    const string port_num_;
+
+    GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
+  };  // class SocketWriter
+
+  // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
+  static string UrlEncode(const char* str);
+
+  StreamingListener(const string& host, const string& port)
+      : socket_writer_(new SocketWriter(host, port)) { Start(); }
+
+  explicit StreamingListener(AbstractSocketWriter* socket_writer)
+      : socket_writer_(socket_writer) { Start(); }
+
+  void OnTestProgramStart(const UnitTest& /* unit_test */) {
+    SendLn("event=TestProgramStart");
+  }
+
+  void OnTestProgramEnd(const UnitTest& unit_test) {
+    // Note that Google Test current only report elapsed time for each
+    // test iteration, not for the entire test program.
+    SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
+
+    // Notify the streaming server to stop.
+    socket_writer_->CloseConnection();
+  }
+
+  void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
+    SendLn("event=TestIterationStart&iteration=" +
+           StreamableToString(iteration));
+  }
+
+  void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
+    SendLn("event=TestIterationEnd&passed=" +
+           FormatBool(unit_test.Passed()) + "&elapsed_time=" +
+           StreamableToString(unit_test.elapsed_time()) + "ms");
+  }
+
+  void OnTestCaseStart(const TestCase& test_case) {
+    SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
+  }
+
+  void OnTestCaseEnd(const TestCase& test_case) {
+    SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
+           + "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
+           + "ms");
+  }
+
+  void OnTestStart(const TestInfo& test_info) {
+    SendLn(std::string("event=TestStart&name=") + test_info.name());
+  }
+
+  void OnTestEnd(const TestInfo& test_info) {
+    SendLn("event=TestEnd&passed=" +
+           FormatBool((test_info.result())->Passed()) +
+           "&elapsed_time=" +
+           StreamableToString((test_info.result())->elapsed_time()) + "ms");
+  }
+
+  void OnTestPartResult(const TestPartResult& test_part_result) {
+    const char* file_name = test_part_result.file_name();
+    if (file_name == NULL)
+      file_name = "";
+    SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
+           "&line=" + StreamableToString(test_part_result.line_number()) +
+           "&message=" + UrlEncode(test_part_result.message()));
+  }
+
+ private:
+  // Sends the given message and a newline to the socket.
+  void SendLn(const string& message) { socket_writer_->SendLn(message); }
+
+  // Called at the start of streaming to notify the receiver what
+  // protocol we are using.
+  void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
+
+  string FormatBool(bool value) { return value ? "1" : "0"; }
+
+  const scoped_ptr<AbstractSocketWriter> socket_writer_;
+
+  GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
+};  // class StreamingListener
+
+#endif  // GTEST_CAN_STREAM_RESULTS_
+
+}  // namespace internal
+}  // namespace testing
+
+#endif  // GTEST_SRC_GTEST_INTERNAL_INL_H_
+#undef GTEST_IMPLEMENTATION_
+
+#if GTEST_OS_WINDOWS
+# define vsnprintf _vsnprintf
+#endif  // GTEST_OS_WINDOWS
+
+namespace testing {
+
+using internal::CountIf;
+using internal::ForEach;
+using internal::GetElementOr;
+using internal::Shuffle;
+
+// Constants.
+
+// A test whose test case name or test name matches this filter is
+// disabled and not run.
+static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
+
+// A test case whose name matches this filter is considered a death
+// test case and will be run before test cases whose name doesn't
+// match this filter.
+static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
+
+// A test filter that matches everything.
+static const char kUniversalFilter[] = "*";
+
+// The default output file for XML output.
+static const char kDefaultOutputFile[] = "test_detail.xml";
+
+// The environment variable name for the test shard index.
+static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
+// The environment variable name for the total number of test shards.
+static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
+// The environment variable name for the test shard status file.
+static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
+
+namespace internal {
+
+// The text used in failure messages to indicate the start of the
+// stack trace.
+const char kStackTraceMarker[] = "\nStack trace:\n";
+
+// g_help_flag is true iff the --help flag or an equivalent form is
+// specified on the command line.
+bool g_help_flag = false;
+
+}  // namespace internal
+
+static const char* GetDefaultFilter() {
+#ifdef GTEST_TEST_FILTER_ENV_VAR_
+  const char* const testbridge_test_only = getenv(GTEST_TEST_FILTER_ENV_VAR_);
+  if (testbridge_test_only != NULL) {
+    return testbridge_test_only;
+  }
+#endif  // GTEST_TEST_FILTER_ENV_VAR_
+  return kUniversalFilter;
+}
+
+GTEST_DEFINE_bool_(
+    also_run_disabled_tests,
+    internal::BoolFromGTestEnv("also_run_disabled_tests", false),
+    "Run disabled tests too, in addition to the tests normally being run.");
+
+GTEST_DEFINE_bool_(
+    break_on_failure,
+    internal::BoolFromGTestEnv("break_on_failure", false),
+    "True iff a failed assertion should be a debugger break-point.");
+
+GTEST_DEFINE_bool_(
+    catch_exceptions,
+    internal::BoolFromGTestEnv("catch_exceptions", true),
+    "True iff " GTEST_NAME_
+    " should catch exceptions and treat them as test failures.");
+
+GTEST_DEFINE_string_(
+    color,
+    internal::StringFromGTestEnv("color", "auto"),
+    "Whether to use colors in the output.  Valid values: yes, no, "
+    "and auto.  'auto' means to use colors if the output is "
+    "being sent to a terminal and the TERM environment variable "
+    "is set to a terminal type that supports colors.");
+
+GTEST_DEFINE_string_(
+    filter,
+    internal::StringFromGTestEnv("filter", GetDefaultFilter()),
+    "A colon-separated list of glob (not regex) patterns "
+    "for filtering the tests to run, optionally followed by a "
+    "'-' and a : separated list of negative patterns (tests to "
+    "exclude).  A test is run if it matches one of the positive "
+    "patterns and does not match any of the negative patterns.");
+
+GTEST_DEFINE_bool_(list_tests, false,
+                   "List all tests without running them.");
+
+GTEST_DEFINE_string_(
+    output,
+    internal::StringFromGTestEnv("output", ""),
+    "A format (currently must be \"xml\"), optionally followed "
+    "by a colon and an output file name or directory. A directory "
+    "is indicated by a trailing pathname separator. "
+    "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
+    "If a directory is specified, output files will be created "
+    "within that directory, with file-names based on the test "
+    "executable's name and, if necessary, made unique by adding "
+    "digits.");
+
+GTEST_DEFINE_bool_(
+    print_time,
+    internal::BoolFromGTestEnv("print_time", true),
+    "True iff " GTEST_NAME_
+    " should display elapsed time in text output.");
+
+GTEST_DEFINE_int32_(
+    random_seed,
+    internal::Int32FromGTestEnv("random_seed", 0),
+    "Random number seed to use when shuffling test orders.  Must be in range "
+    "[1, 99999], or 0 to use a seed based on the current time.");
+
+GTEST_DEFINE_int32_(
+    repeat,
+    internal::Int32FromGTestEnv("repeat", 1),
+    "How many times to repeat each test.  Specify a negative number "
+    "for repeating forever.  Useful for shaking out flaky tests.");
+
+GTEST_DEFINE_bool_(
+    show_internal_stack_frames, false,
+    "True iff " GTEST_NAME_ " should include internal stack frames when "
+    "printing test failure stack traces.");
+
+GTEST_DEFINE_bool_(
+    shuffle,
+    internal::BoolFromGTestEnv("shuffle", false),
+    "True iff " GTEST_NAME_
+    " should randomize tests' order on every run.");
+
+GTEST_DEFINE_int32_(
+    stack_trace_depth,
+    internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
+    "The maximum number of stack frames to print when an "
+    "assertion fails.  The valid range is 0 through 100, inclusive.");
+
+GTEST_DEFINE_string_(
+    stream_result_to,
+    internal::StringFromGTestEnv("stream_result_to", ""),
+    "This flag specifies the host name and the port number on which to stream "
+    "test results. Example: \"localhost:555\". The flag is effective only on "
+    "Linux.");
+
+GTEST_DEFINE_bool_(
+    throw_on_failure,
+    internal::BoolFromGTestEnv("throw_on_failure", false),
+    "When this flag is specified, a failed assertion will throw an exception "
+    "if exceptions are enabled or exit the program with a non-zero code "
+    "otherwise.");
+
+#if GTEST_USE_OWN_FLAGFILE_FLAG_
+GTEST_DEFINE_string_(
+    flagfile,
+    internal::StringFromGTestEnv("flagfile", ""),
+    "This flag specifies the flagfile to read command-line flags from.");
+#endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
+
+namespace internal {
+
+// Generates a random number from [0, range), using a Linear
+// Congruential Generator (LCG).  Crashes if 'range' is 0 or greater
+// than kMaxRange.
+UInt32 Random::Generate(UInt32 range) {
+  // These constants are the same as are used in glibc's rand(3).
+  state_ = (1103515245U*state_ + 12345U) % kMaxRange;
+
+  GTEST_CHECK_(range > 0)
+      << "Cannot generate a number in the range [0, 0).";
+  GTEST_CHECK_(range <= kMaxRange)
+      << "Generation of a number in [0, " << range << ") was requested, "
+      << "but this can only generate numbers in [0, " << kMaxRange << ").";
+
+  // Converting via modulus introduces a bit of downward bias, but
+  // it's simple, and a linear congruential generator isn't too good
+  // to begin with.
+  return state_ % range;
+}
+
+// GTestIsInitialized() returns true iff the user has initialized
+// Google Test.  Useful for catching the user mistake of not initializing
+// Google Test before calling RUN_ALL_TESTS().
+static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
+
+// Iterates over a vector of TestCases, keeping a running sum of the
+// results of calling a given int-returning method on each.
+// Returns the sum.
+static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
+                               int (TestCase::*method)() const) {
+  int sum = 0;
+  for (size_t i = 0; i < case_list.size(); i++) {
+    sum += (case_list[i]->*method)();
+  }
+  return sum;
+}
+
+// Returns true iff the test case passed.
+static bool TestCasePassed(const TestCase* test_case) {
+  return test_case->should_run() && test_case->Passed();
+}
+
+// Returns true iff the test case failed.
+static bool TestCaseFailed(const TestCase* test_case) {
+  return test_case->should_run() && test_case->Failed();
+}
+
+// Returns true iff test_case contains at least one test that should
+// run.
+static bool ShouldRunTestCase(const TestCase* test_case) {
+  return test_case->should_run();
+}
+
+// AssertHelper constructor.
+AssertHelper::AssertHelper(TestPartResult::Type type,
+                           const char* file,
+                           int line,
+                           const char* message)
+    : data_(new AssertHelperData(type, file, line, message)) {
+}
+
+AssertHelper::~AssertHelper() {
+  delete data_;
+}
+
+// Message assignment, for assertion streaming support.
+void AssertHelper::operator=(const Message& message) const {
+  UnitTest::GetInstance()->
+    AddTestPartResult(data_->type, data_->file, data_->line,
+                      AppendUserMessage(data_->message, message),
+                      UnitTest::GetInstance()->impl()
+                      ->CurrentOsStackTraceExceptTop(1)
+                      // Skips the stack frame for this function itself.
+                      );  // NOLINT
+}
+
+// Mutex for linked pointers.
+GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
+
+// A copy of all command line arguments.  Set by InitGoogleTest().
+::std::vector<testing::internal::string> g_argvs;
+
+const ::std::vector<testing::internal::string>& GetArgvs() {
+#if defined(GTEST_CUSTOM_GET_ARGVS_)
+  return GTEST_CUSTOM_GET_ARGVS_();
+#else  // defined(GTEST_CUSTOM_GET_ARGVS_)
+  return g_argvs;
+#endif  // defined(GTEST_CUSTOM_GET_ARGVS_)
+}
+
+// Returns the current application's name, removing directory path if that
+// is present.
+FilePath GetCurrentExecutableName() {
+  FilePath result;
+
+#if GTEST_OS_WINDOWS
+  result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
+#else
+  result.Set(FilePath(GetArgvs()[0]));
+#endif  // GTEST_OS_WINDOWS
+
+  return result.RemoveDirectoryName();
+}
+
+// Functions for processing the gtest_output flag.
+
+// Returns the output format, or "" for normal printed output.
+std::string UnitTestOptions::GetOutputFormat() {
+  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
+  if (gtest_output_flag == NULL) return std::string("");
+
+  const char* const colon = strchr(gtest_output_flag, ':');
+  return (colon == NULL) ?
+      std::string(gtest_output_flag) :
+      std::string(gtest_output_flag, colon - gtest_output_flag);
+}
+
+// Returns the name of the requested output file, or the default if none
+// was explicitly specified.
+std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
+  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
+  if (gtest_output_flag == NULL)
+    return "";
+
+  const char* const colon = strchr(gtest_output_flag, ':');
+  if (colon == NULL)
+    return internal::FilePath::ConcatPaths(
+        internal::FilePath(
+            UnitTest::GetInstance()->original_working_dir()),
+        internal::FilePath(kDefaultOutputFile)).string();
+
+  internal::FilePath output_name(colon + 1);
+  if (!output_name.IsAbsolutePath())
+    // TODO(wan@google.com): on Windows \some\path is not an absolute
+    // path (as its meaning depends on the current drive), yet the
+    // following logic for turning it into an absolute path is wrong.
+    // Fix it.
+    output_name = internal::FilePath::ConcatPaths(
+        internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
+        internal::FilePath(colon + 1));
+
+  if (!output_name.IsDirectory())
+    return output_name.string();
+
+  internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
+      output_name, internal::GetCurrentExecutableName(),
+      GetOutputFormat().c_str()));
+  return result.string();
+}
+
+// Returns true iff the wildcard pattern matches the string.  The
+// first ':' or '\0' character in pattern marks the end of it.
+//
+// This recursive algorithm isn't very efficient, but is clear and
+// works well enough for matching test names, which are short.
+bool UnitTestOptions::PatternMatchesString(const char *pattern,
+                                           const char *str) {
+  switch (*pattern) {
+    case '\0':
+    case ':':  // Either ':' or '\0' marks the end of the pattern.
+      return *str == '\0';
+    case '?':  // Matches any single character.
+      return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
+    case '*':  // Matches any string (possibly empty) of characters.
+      return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
+          PatternMatchesString(pattern + 1, str);
+    default:  // Non-special character.  Matches itself.
+      return *pattern == *str &&
+          PatternMatchesString(pattern + 1, str + 1);
+  }
+}
+
+bool UnitTestOptions::MatchesFilter(
+    const std::string& name, const char* filter) {
+  const char *cur_pattern = filter;
+  for (;;) {
+    if (PatternMatchesString(cur_pattern, name.c_str())) {
+      return true;
+    }
+
+    // Finds the next pattern in the filter.
+    cur_pattern = strchr(cur_pattern, ':');
+
+    // Returns if no more pattern can be found.
+    if (cur_pattern == NULL) {
+      return false;
+    }
+
+    // Skips the pattern separater (the ':' character).
+    cur_pattern++;
+  }
+}
+
+// Returns true iff the user-specified filter matches the test case
+// name and the test name.
+bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
+                                        const std::string &test_name) {
+  const std::string& full_name = test_case_name + "." + test_name.c_str();
+
+  // Split --gtest_filter at '-', if there is one, to separate into
+  // positive filter and negative filter portions
+  const char* const p = GTEST_FLAG(filter).c_str();
+  const char* const dash = strchr(p, '-');
+  std::string positive;
+  std::string negative;
+  if (dash == NULL) {
+    positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter
+    negative = "";
+  } else {
+    positive = std::string(p, dash);   // Everything up to the dash
+    negative = std::string(dash + 1);  // Everything after the dash
+    if (positive.empty()) {
+      // Treat '-test1' as the same as '*-test1'
+      positive = kUniversalFilter;
+    }
+  }
+
+  // A filter is a colon-separated list of patterns.  It matches a
+  // test if any pattern in it matches the test.
+  return (MatchesFilter(full_name, positive.c_str()) &&
+          !MatchesFilter(full_name, negative.c_str()));
+}
+
+#if GTEST_HAS_SEH
+// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
+// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
+// This function is useful as an __except condition.
+int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
+  // Google Test should handle a SEH exception if:
+  //   1. the user wants it to, AND
+  //   2. this is not a breakpoint exception, AND
+  //   3. this is not a C++ exception (VC++ implements them via SEH,
+  //      apparently).
+  //
+  // SEH exception code for C++ exceptions.
+  // (see http://support.microsoft.com/kb/185294 for more information).
+  const DWORD kCxxExceptionCode = 0xe06d7363;
+
+  bool should_handle = true;
+
+  if (!GTEST_FLAG(catch_exceptions))
+    should_handle = false;
+  else if (exception_code == EXCEPTION_BREAKPOINT)
+    should_handle = false;
+  else if (exception_code == kCxxExceptionCode)
+    should_handle = false;
+
+  return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
+}
+#endif  // GTEST_HAS_SEH
+
+}  // namespace internal
+
+// The c'tor sets this object as the test part result reporter used by
+// Google Test.  The 'result' parameter specifies where to report the
+// results. Intercepts only failures from the current thread.
+ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
+    TestPartResultArray* result)
+    : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
+      result_(result) {
+  Init();
+}
+
+// The c'tor sets this object as the test part result reporter used by
+// Google Test.  The 'result' parameter specifies where to report the
+// results.
+ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
+    InterceptMode intercept_mode, TestPartResultArray* result)
+    : intercept_mode_(intercept_mode),
+      result_(result) {
+  Init();
+}
+
+void ScopedFakeTestPartResultReporter::Init() {
+  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
+  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
+    old_reporter_ = impl->GetGlobalTestPartResultReporter();
+    impl->SetGlobalTestPartResultReporter(this);
+  } else {
+    old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
+    impl->SetTestPartResultReporterForCurrentThread(this);
+  }
+}
+
+// The d'tor restores the test part result reporter used by Google Test
+// before.
+ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
+  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
+  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
+    impl->SetGlobalTestPartResultReporter(old_reporter_);
+  } else {
+    impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
+  }
+}
+
+// Increments the test part result count and remembers the result.
+// This method is from the TestPartResultReporterInterface interface.
+void ScopedFakeTestPartResultReporter::ReportTestPartResult(
+    const TestPartResult& result) {
+  result_->Append(result);
+}
+
+namespace internal {
+
+// Returns the type ID of ::testing::Test.  We should always call this
+// instead of GetTypeId< ::testing::Test>() to get the type ID of
+// testing::Test.  This is to work around a suspected linker bug when
+// using Google Test as a framework on Mac OS X.  The bug causes
+// GetTypeId< ::testing::Test>() to return different values depending
+// on whether the call is from the Google Test framework itself or
+// from user test code.  GetTestTypeId() is guaranteed to always
+// return the same value, as it always calls GetTypeId<>() from the
+// gtest.cc, which is within the Google Test framework.
+TypeId GetTestTypeId() {
+  return GetTypeId<Test>();
+}
+
+// The value of GetTestTypeId() as seen from within the Google Test
+// library.  This is solely for testing GetTestTypeId().
+extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
+
+// This predicate-formatter checks that 'results' contains a test part
+// failure of the given type and that the failure message contains the
+// given substring.
+AssertionResult HasOneFailure(const char* /* results_expr */,
+                              const char* /* type_expr */,
+                              const char* /* substr_expr */,
+                              const TestPartResultArray& results,
+                              TestPartResult::Type type,
+                              const string& substr) {
+  const std::string expected(type == TestPartResult::kFatalFailure ?
+                        "1 fatal failure" :
+                        "1 non-fatal failure");
+  Message msg;
+  if (results.size() != 1) {
+    msg << "Expected: " << expected << "\n"
+        << "  Actual: " << results.size() << " failures";
+    for (int i = 0; i < results.size(); i++) {
+      msg << "\n" << results.GetTestPartResult(i);
+    }
+    return AssertionFailure() << msg;
+  }
+
+  const TestPartResult& r = results.GetTestPartResult(0);
+  if (r.type() != type) {
+    return AssertionFailure() << "Expected: " << expected << "\n"
+                              << "  Actual:\n"
+                              << r;
+  }
+
+  if (strstr(r.message(), substr.c_str()) == NULL) {
+    return AssertionFailure() << "Expected: " << expected << " containing \""
+                              << substr << "\"\n"
+                              << "  Actual:\n"
+                              << r;
+  }
+
+  return AssertionSuccess();
+}
+
+// The constructor of SingleFailureChecker remembers where to look up
+// test part results, what type of failure we expect, and what
+// substring the failure message should contain.
+SingleFailureChecker:: SingleFailureChecker(
+    const TestPartResultArray* results,
+    TestPartResult::Type type,
+    const string& substr)
+    : results_(results),
+      type_(type),
+      substr_(substr) {}
+
+// The destructor of SingleFailureChecker verifies that the given
+// TestPartResultArray contains exactly one failure that has the given
+// type and contains the given substring.  If that's not the case, a
+// non-fatal failure will be generated.
+SingleFailureChecker::~SingleFailureChecker() {
+  EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
+}
+
+DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
+    UnitTestImpl* unit_test) : unit_test_(unit_test) {}
+
+void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
+    const TestPartResult& result) {
+  unit_test_->current_test_result()->AddTestPartResult(result);
+  unit_test_->listeners()->repeater()->OnTestPartResult(result);
+}
+
+DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
+    UnitTestImpl* unit_test) : unit_test_(unit_test) {}
+
+void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
+    const TestPartResult& result) {
+  unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
+}
+
+// Returns the global test part result reporter.
+TestPartResultReporterInterface*
+UnitTestImpl::GetGlobalTestPartResultReporter() {
+  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
+  return global_test_part_result_repoter_;
+}
+
+// Sets the global test part result reporter.
+void UnitTestImpl::SetGlobalTestPartResultReporter(
+    TestPartResultReporterInterface* reporter) {
+  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
+  global_test_part_result_repoter_ = reporter;
+}
+
+// Returns the test part result reporter for the current thread.
+TestPartResultReporterInterface*
+UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
+  return per_thread_test_part_result_reporter_.get();
+}
+
+// Sets the test part result reporter for the current thread.
+void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
+    TestPartResultReporterInterface* reporter) {
+  per_thread_test_part_result_reporter_.set(reporter);
+}
+
+// Gets the number of successful test cases.
+int UnitTestImpl::successful_test_case_count() const {
+  return CountIf(test_cases_, TestCasePassed);
+}
+
+// Gets the number of failed test cases.
+int UnitTestImpl::failed_test_case_count() const {
+  return CountIf(test_cases_, TestCaseFailed);
+}
+
+// Gets the number of all test cases.
+int UnitTestImpl::total_test_case_count() const {
+  return static_cast<int>(test_cases_.size());
+}
+
+// Gets the number of all test cases that contain at least one test
+// that should run.
+int UnitTestImpl::test_case_to_run_count() const {
+  return CountIf(test_cases_, ShouldRunTestCase);
+}
+
+// Gets the number of successful tests.
+int UnitTestImpl::successful_test_count() const {
+  return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
+}
+
+// Gets the number of failed tests.
+int UnitTestImpl::failed_test_count() const {
+  return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
+}
+
+// Gets the number of disabled tests that will be reported in the XML report.
+int UnitTestImpl::reportable_disabled_test_count() const {
+  return SumOverTestCaseList(test_cases_,
+                             &TestCase::reportable_disabled_test_count);
+}
+
+// Gets the number of disabled tests.
+int UnitTestImpl::disabled_test_count() const {
+  return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
+}
+
+// Gets the number of tests to be printed in the XML report.
+int UnitTestImpl::reportable_test_count() const {
+  return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);
+}
+
+// Gets the number of all tests.
+int UnitTestImpl::total_test_count() const {
+  return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
+}
+
+// Gets the number of tests that should run.
+int UnitTestImpl::test_to_run_count() const {
+  return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
+}
+
+// Returns the current OS stack trace as an std::string.
+//
+// The maximum number of stack frames to be included is specified by
+// the gtest_stack_trace_depth flag.  The skip_count parameter
+// specifies the number of top frames to be skipped, which doesn't
+// count against the number of frames to be included.
+//
+// For example, if Foo() calls Bar(), which in turn calls
+// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
+// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
+std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
+  return os_stack_trace_getter()->CurrentStackTrace(
+      static_cast<int>(GTEST_FLAG(stack_trace_depth)),
+      skip_count + 1
+      // Skips the user-specified number of frames plus this function
+      // itself.
+      );  // NOLINT
+}
+
+// Returns the current time in milliseconds.
+TimeInMillis GetTimeInMillis() {
+#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
+  // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
+  // http://analogous.blogspot.com/2005/04/epoch.html
+  const TimeInMillis kJavaEpochToWinFileTimeDelta =
+    static_cast<TimeInMillis>(116444736UL) * 100000UL;
+  const DWORD kTenthMicrosInMilliSecond = 10000;
+
+  SYSTEMTIME now_systime;
+  FILETIME now_filetime;
+  ULARGE_INTEGER now_int64;
+  // TODO(kenton@google.com): Shouldn't this just use
+  //   GetSystemTimeAsFileTime()?
+  GetSystemTime(&now_systime);
+  if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
+    now_int64.LowPart = now_filetime.dwLowDateTime;
+    now_int64.HighPart = now_filetime.dwHighDateTime;
+    now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
+      kJavaEpochToWinFileTimeDelta;
+

<TRUNCATED>