Initial plugin version
diff --git a/.buckconfig b/.buckconfig
new file mode 100644
index 0000000..0a84b64
--- /dev/null
+++ b/.buckconfig
@@ -0,0 +1,15 @@
+[alias]
+  project-group-structure = //:project-group-structure
+  plugin = //:project-group-structure
+  src = //:project-group-structure-sources
+
+[java]
+  src_roots = java, resources
+
+[project]
+  ignore = .git
+
+[cache]
+  mode = dir
+  dir = buck-out/cache
+
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..d781c5f
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,9 @@
+/.buckd
+/.buckversion
+/.classpath
+/.project
+/.settings/
+/.watchmanconfig
+/buck-out
+/bucklets
+/eclipse-out/
diff --git a/BUCK b/BUCK
new file mode 100644
index 0000000..dfd8810
--- /dev/null
+++ b/BUCK
@@ -0,0 +1,42 @@
+include_defs('//bucklets/gerrit_plugin.bucklet')
+include_defs('//bucklets/java_sources.bucklet')
+
+SOURCES = glob(['src/main/java/**/*.java'])
+RESOURCES = glob(['src/main/resources/**/*'])
+
+TEST_DEPS = GERRIT_TESTS + GERRIT_PLUGIN_API + [
+  ':project-group-structure__plugin',
+]
+
+gerrit_plugin(
+  name = 'project-group-structure',
+  srcs = SOURCES,
+  resources = RESOURCES,
+  manifest_entries = [
+    'Gerrit-PluginName: project-group-structure',
+    'Gerrit-ApiType: plugin',
+    'Gerrit-Module: com.ericsson.gerrit.plugins.projectgroupstructure.Module',
+    'Implementation-Title: project-group-structure plugin',
+    'Implementation-URL: https://gerrit-review.googlesource.com/#/admin/projects/plugins/project-group-structure',
+    'Implementation-Vendor: Ericsson',
+  ],
+)
+
+java_test(
+  name = 'project-group-structure-tests',
+  srcs = glob(['src/test/java/**/*.java']),
+  labels = ['project-group-structure'],
+  deps = TEST_DEPS,
+)
+
+java_sources(
+  name = 'project-group-structure-sources',
+  srcs = SOURCES + RESOURCES,
+)
+
+# this is required for bucklets/tools/eclipse/project.py to work
+java_library(
+  name = 'classpath',
+  deps = TEST_DEPS,
+)
+
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..11069ed
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+                              Apache License
+                        Version 2.0, January 2004
+                     http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+   "License" shall mean the terms and conditions for use, reproduction,
+   and distribution as defined by Sections 1 through 9 of this document.
+
+   "Licensor" shall mean the copyright owner or entity authorized by
+   the copyright owner that is granting the License.
+
+   "Legal Entity" shall mean the union of the acting entity and all
+   other entities that control, are controlled by, or are under common
+   control with that entity. For the purposes of this definition,
+   "control" means (i) the power, direct or indirect, to cause the
+   direction or management of such entity, whether by contract or
+   otherwise, or (ii) ownership of fifty percent (50%) or more of the
+   outstanding shares, or (iii) beneficial ownership of such entity.
+
+   "You" (or "Your") shall mean an individual or Legal Entity
+   exercising permissions granted by this License.
+
+   "Source" form shall mean the preferred form for making modifications,
+   including but not limited to software source code, documentation
+   source, and configuration files.
+
+   "Object" form shall mean any form resulting from mechanical
+   transformation or translation of a Source form, including but
+   not limited to compiled object code, generated documentation,
+   and conversions to other media types.
+
+   "Work" shall mean the work of authorship, whether in Source or
+   Object form, made available under the License, as indicated by a
+   copyright notice that is included in or attached to the work
+   (an example is provided in the Appendix below).
+
+   "Derivative Works" shall mean any work, whether in Source or Object
+   form, that is based on (or derived from) the Work and for which the
+   editorial revisions, annotations, elaborations, or other modifications
+   represent, as a whole, an original work of authorship. For the purposes
+   of this License, Derivative Works shall not include works that remain
+   separable from, or merely link (or bind by name) to the interfaces of,
+   the Work and Derivative Works thereof.
+
+   "Contribution" shall mean any work of authorship, including
+   the original version of the Work and any modifications or additions
+   to that Work or Derivative Works thereof, that is intentionally
+   submitted to Licensor for inclusion in the Work by the copyright owner
+   or by an individual or Legal Entity authorized to submit on behalf of
+   the copyright owner. For the purposes of this definition, "submitted"
+   means any form of electronic, verbal, or written communication sent
+   to the Licensor or its representatives, including but not limited to
+   communication on electronic mailing lists, source code control systems,
+   and issue tracking systems that are managed by, or on behalf of, the
+   Licensor for the purpose of discussing and improving the Work, but
+   excluding communication that is conspicuously marked or otherwise
+   designated in writing by the copyright owner as "Not a Contribution."
+
+   "Contributor" shall mean Licensor and any individual or Legal Entity
+   on behalf of whom a Contribution has been received by Licensor and
+   subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+   this License, each Contributor hereby grants to You a perpetual,
+   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+   copyright license to reproduce, prepare Derivative Works of,
+   publicly display, publicly perform, sublicense, and distribute the
+   Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+   this License, each Contributor hereby grants to You a perpetual,
+   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+   (except as stated in this section) patent license to make, have made,
+   use, offer to sell, sell, import, and otherwise transfer the Work,
+   where such license applies only to those patent claims licensable
+   by such Contributor that are necessarily infringed by their
+   Contribution(s) alone or by combination of their Contribution(s)
+   with the Work to which such Contribution(s) was submitted. If You
+   institute patent litigation against any entity (including a
+   cross-claim or counterclaim in a lawsuit) alleging that the Work
+   or a Contribution incorporated within the Work constitutes direct
+   or contributory patent infringement, then any patent licenses
+   granted to You under this License for that Work shall terminate
+   as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+   Work or Derivative Works thereof in any medium, with or without
+   modifications, and in Source or Object form, provided that You
+   meet the following conditions:
+
+   (a) You must give any other recipients of the Work or
+       Derivative Works a copy of this License; and
+
+   (b) You must cause any modified files to carry prominent notices
+       stating that You changed the files; and
+
+   (c) You must retain, in the Source form of any Derivative Works
+       that You distribute, all copyright, patent, trademark, and
+       attribution notices from the Source form of the Work,
+       excluding those notices that do not pertain to any part of
+       the Derivative Works; and
+
+   (d) If the Work includes a "NOTICE" text file as part of its
+       distribution, then any Derivative Works that You distribute must
+       include a readable copy of the attribution notices contained
+       within such NOTICE file, excluding those notices that do not
+       pertain to any part of the Derivative Works, in at least one
+       of the following places: within a NOTICE text file distributed
+       as part of the Derivative Works; within the Source form or
+       documentation, if provided along with the Derivative Works; or,
+       within a display generated by the Derivative Works, if and
+       wherever such third-party notices normally appear. The contents
+       of the NOTICE file are for informational purposes only and
+       do not modify the License. You may add Your own attribution
+       notices within Derivative Works that You distribute, alongside
+       or as an addendum to the NOTICE text from the Work, provided
+       that such additional attribution notices cannot be construed
+       as modifying the License.
+
+   You may add Your own copyright statement to Your modifications and
+   may provide additional or different license terms and conditions
+   for use, reproduction, or distribution of Your modifications, or
+   for any such Derivative Works as a whole, provided Your use,
+   reproduction, and distribution of the Work otherwise complies with
+   the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+   any Contribution intentionally submitted for inclusion in the Work
+   by You to the Licensor shall be under the terms and conditions of
+   this License, without any additional terms or conditions.
+   Notwithstanding the above, nothing herein shall supersede or modify
+   the terms of any separate license agreement you may have executed
+   with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+   names, trademarks, service marks, or product names of the Licensor,
+   except as required for reasonable and customary use in describing the
+   origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+   agreed to in writing, Licensor provides the Work (and each
+   Contributor provides its Contributions) on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+   implied, including, without limitation, any warranties or conditions
+   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+   PARTICULAR PURPOSE. You are solely responsible for determining the
+   appropriateness of using or redistributing the Work and assume any
+   risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+   whether in tort (including negligence), contract, or otherwise,
+   unless required by applicable law (such as deliberate and grossly
+   negligent acts) or agreed to in writing, shall any Contributor be
+   liable to You for damages, including any direct, indirect, special,
+   incidental, or consequential damages of any character arising as a
+   result of this License or out of the use or inability to use the
+   Work (including but not limited to damages for loss of goodwill,
+   work stoppage, computer failure or malfunction, or any and all
+   other commercial damages or losses), even if such Contributor
+   has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+   the Work or Derivative Works thereof, You may choose to offer,
+   and charge a fee for, acceptance of support, warranty, indemnity,
+   or other liability obligations and/or rights consistent with this
+   License. However, in accepting such obligations, You may act only
+   on Your own behalf and on Your sole responsibility, not on behalf
+   of any other Contributor, and only if You agree to indemnify,
+   defend, and hold each Contributor harmless for any liability
+   incurred by, or claims asserted against, such Contributor by reason
+   of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+   To apply the Apache License to your work, attach the following
+   boilerplate notice, with the fields enclosed by brackets "[]"
+   replaced with your own identifying information. (Don't include
+   the brackets!)  The text should be enclosed in the appropriate
+   comment syntax for the file format. We also recommend that a
+   file or class name and description of purpose be included on the
+   same "printed page" as the copyright notice for easier
+   identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/lib/gerrit/BUCK b/lib/gerrit/BUCK
new file mode 100644
index 0000000..629181b
--- /dev/null
+++ b/lib/gerrit/BUCK
@@ -0,0 +1,21 @@
+include_defs('//bucklets/maven_jar.bucklet')
+
+VER = '2.12'
+REPO = MAVEN_CENTRAL
+
+maven_jar(
+  name = 'plugin-api',
+  id = 'com.google.gerrit:gerrit-plugin-api:' + VER,
+  sha1 = '8ce1f6e65078bbcf03a1758f96b3ebca19b7fe3c',
+  license = 'Apache2.0',
+  attach_source = False,
+  repository = REPO,
+)
+maven_jar(
+  name = 'acceptance-framework',
+  id = 'com.google.gerrit:gerrit-acceptance-framework:' + VER,
+  sha1 = 'f35140148294239012b1a5052181783c0c9f4ffd',
+  license = 'Apache2.0',
+  attach_source = False,
+  repository = REPO,
+)
diff --git a/src/main/java/com/ericsson/gerrit/plugins/projectgroupstructure/Module.java b/src/main/java/com/ericsson/gerrit/plugins/projectgroupstructure/Module.java
new file mode 100644
index 0000000..5e80a96
--- /dev/null
+++ b/src/main/java/com/ericsson/gerrit/plugins/projectgroupstructure/Module.java
@@ -0,0 +1,28 @@
+// Copyright (C) 2016 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.ericsson.gerrit.plugins.projectgroupstructure;
+
+import com.google.gerrit.extensions.registration.DynamicSet;
+import com.google.gerrit.server.validators.ProjectCreationValidationListener;
+import com.google.inject.AbstractModule;
+
+
+class Module extends AbstractModule {
+  @Override
+  protected void configure() {
+    DynamicSet.bind(binder(), ProjectCreationValidationListener.class)
+        .to(ProjectCreationValidator.class);
+  }
+}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/projectgroupstructure/ProjectCreationValidator.java b/src/main/java/com/ericsson/gerrit/plugins/projectgroupstructure/ProjectCreationValidator.java
new file mode 100644
index 0000000..3ea51b9
--- /dev/null
+++ b/src/main/java/com/ericsson/gerrit/plugins/projectgroupstructure/ProjectCreationValidator.java
@@ -0,0 +1,168 @@
+// Copyright (C) 2016 Ericsson
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.ericsson.gerrit.plugins.projectgroupstructure;
+
+import com.google.common.base.Charsets;
+import com.google.common.hash.Hashing;
+import com.google.gerrit.extensions.annotations.PluginCanonicalWebUrl;
+import com.google.gerrit.extensions.api.groups.GroupInput;
+import com.google.gerrit.extensions.common.GroupInfo;
+import com.google.gerrit.extensions.restapi.ResourceConflictException;
+import com.google.gerrit.extensions.restapi.RestApiException;
+import com.google.gerrit.extensions.restapi.TopLevelResource;
+import com.google.gerrit.reviewdb.client.AccountGroup;
+import com.google.gerrit.reviewdb.client.Project;
+import com.google.gerrit.server.config.AllProjectsNameProvider;
+import com.google.gerrit.server.group.CreateGroup;
+import com.google.gerrit.server.project.CreateProjectArgs;
+import com.google.gerrit.server.project.ProjectControl;
+import com.google.gerrit.server.validators.ProjectCreationValidationListener;
+import com.google.gerrit.server.validators.ValidationException;
+import com.google.gwtorm.server.OrmException;
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Singleton
+public class ProjectCreationValidator
+    implements ProjectCreationValidationListener {
+  private static final Logger log =
+      LoggerFactory.getLogger(ProjectCreationValidator.class);
+
+  private static final String AN_ERROR_OCCURRED_MSG =
+      "An error occurred while creating project, please contact Gerrit support";
+
+  private static final String MUST_BE_OWNER_TO_CREATE_PROJECT_MSG =
+      "You must be owner of the parent project \"%s\" to create a nested project."
+          + "\n\nSee documentation for more info: %s";
+
+  private static final String ROOT_PROJECT_CANNOT_CONTAINS_SLASHES_MSG =
+      "Root project name cannot contains slashes."
+          + "\n\nSee documentation for more info: %s";
+
+  private static final String REGULAR_PROJECT_NOT_ALLOWED_AS_ROOT_MSG =
+      "Regular projects are not allowed as root.\n\n"
+          + "Please create a root parent project (project with option "
+          + "\"Only serve as parent for other projects\") that will hold "
+          + "all your access rights and then create your regular project that "
+          + "inherits rights from your root project.\n\n" + "Example:\n"
+          + "\"someOrganization\"->parent project\n"
+          + "\"someOrganization/someProject\"->regular project."
+          + "\n\nSee documentation for more info: %s";
+
+  private static final String PROJECT_MUST_START_WITH_PARENT_NAME_MSG =
+      "Project name must start with parent project name, e.g. %s."
+          + "\n\nSee documentation for more info: %s";
+
+  private final CreateGroup.Factory createGroupFactory;
+  private final String documentationUrl;
+  private final AllProjectsNameProvider allProjectsName;
+
+  @Inject
+  public ProjectCreationValidator(CreateGroup.Factory createGroupFactory,
+      @PluginCanonicalWebUrl String url,
+      AllProjectsNameProvider allProjectsName) {
+    this.createGroupFactory = createGroupFactory;
+    this.documentationUrl = url + "Documentation/index.html";
+    this.allProjectsName = allProjectsName;
+
+  }
+
+  @Override
+  public void validateNewProject(CreateProjectArgs args)
+      throws ValidationException {
+    String name = args.getProjectName();
+    log.debug("validating creation of {}", name);
+    ProjectControl parentCtrl = args.newParent;
+    if (parentCtrl.getUser().getCapabilities().canAdministrateServer()) {
+      // Admins can bypass any rules to support creating projects that doesn't
+      // comply with the new naming rules. New projects structures have to
+      // comply but we need to be able to add new project to an existing non
+      // compliant structure.
+      log.debug("admin is creating project, bypassing all rules");
+      return;
+    }
+
+    Project parent = parentCtrl.getProject();
+
+    if (allProjectsName.get().equals(parent.getNameKey())) {
+      if (name.contains("/")) {
+        log.debug("rejecting creation of {}: name contains slashes", name);
+        throw new ValidationException(String.format(
+            ROOT_PROJECT_CANNOT_CONTAINS_SLASHES_MSG, documentationUrl));
+      }
+      if (!args.permissionsOnly) {
+        log.debug("rejecting creation of {}: missing permissions only option",
+            name);
+        throw new ValidationException(String
+            .format(REGULAR_PROJECT_NOT_ALLOWED_AS_ROOT_MSG, documentationUrl));
+      }
+      args.ownerIds.add(createGroup(name + "-admins"));
+      log.debug("allowing creation of root project {}", name);
+      return;
+    }
+
+    validateProjectNamePrefix(name, parent);
+
+    if (!parentCtrl.isOwner()) {
+      log.debug("rejecting creation of {}: user is not owner of {}", name,
+          parent.getName());
+      throw new ValidationException(
+          String.format(MUST_BE_OWNER_TO_CREATE_PROJECT_MSG, parent.getName(),
+              documentationUrl));
+    }
+    log.debug("allowing creation of project {}", name);
+  }
+
+  private AccountGroup.UUID createGroup(String name)
+      throws ValidationException {
+    try {
+      GroupInfo groupInfo = null;
+      try {
+        groupInfo = createGroupFactory.create(name)
+            .apply(TopLevelResource.INSTANCE, new GroupInput());
+      } catch (ResourceConflictException e) {
+        // name already exists, make sure it is unique by adding a abbreviated
+        // sha1
+        String nameWithSha1 = name + "-" + Hashing.sha1()
+            .hashString(name, Charsets.UTF_8).toString().substring(0, 7);
+        log.info(
+            "Failed to create group name {} because of a conflict: {}, trying to create {} instead",
+            name, e.getMessage(), nameWithSha1);
+        groupInfo = createGroupFactory.create(nameWithSha1)
+            .apply(TopLevelResource.INSTANCE, new GroupInput());
+      }
+      return AccountGroup.UUID.parse(groupInfo.id);
+    } catch (RestApiException | OrmException e) {
+      log.error("Failed to create project " + name + ": " + e.getMessage(), e);
+      throw new ValidationException(AN_ERROR_OCCURRED_MSG);
+    }
+  }
+
+  private void validateProjectNamePrefix(String name, Project parent)
+      throws ValidationException {
+    log.debug("validating name prefix of {}", name);
+    String prefix = parent.getName() + "/";
+    if (!name.startsWith(prefix)) {
+      log.debug("rejecting creation of {}: name is not starting with {}", name,
+          prefix);
+      throw new ValidationException(
+          String.format(PROJECT_MUST_START_WITH_PARENT_NAME_MSG, prefix + name,
+              documentationUrl));
+    }
+  }
+}
diff --git a/src/main/resources/Documentation/about.md b/src/main/resources/Documentation/about.md
new file mode 100644
index 0000000..36998dd
--- /dev/null
+++ b/src/main/resources/Documentation/about.md
@@ -0,0 +1,17 @@
+This plugin enforce a project group structure and restrict project creation
+within this structure to project group owners only.
+
+To start creating a project group structure, simply create a root project, i.e.
+a project which inherits rights from `All-Projects`. The root project name
+cannot contains slashes, e.g. `some-organization` and must be created with
+option `Only serve as parent for other projects`.
+
+Ownership of the root project is given automatically to the user who created it
+by adding him to a group named `<root-project-name>-admins`, e.g.
+`some-organization-admins` which is granted owner right on `refs/*` references.
+
+From this point on, only the root project owners can create projects within that
+structure. They can do it by creating projects that inherits rights from their
+root project and the project names must start with root project name, e.g.
+`some-organization/some-project`.
+
diff --git a/src/main/resources/Documentation/build.md b/src/main/resources/Documentation/build.md
new file mode 100644
index 0000000..bedf322
--- /dev/null
+++ b/src/main/resources/Documentation/build.md
@@ -0,0 +1,72 @@
+Build
+=====
+
+This plugin is built with Buck.
+
+Buck
+----
+
+Two build modes are supported: Standalone and in Gerrit tree.
+The standalone build mode is recommended, as this mode doesn't require
+the Gerrit tree to exist locally.
+
+Build standalone
+----------------
+
+Clone bucklets library:
+
+```
+  git clone https://gerrit.googlesource.com/bucklets
+
+```
+and link it to @PLUGIN@ plugin directory:
+
+```
+  cd @PLUGIN@ && ln -s ../bucklets .
+```
+
+Add link to the .buckversion file:
+
+```
+  cd @PLUGIN@ && ln -s bucklets/buckversion .buckversion
+```
+
+Add link to the .watchmanconfig file:
+```
+  cd @PLUGIN@ && ln -s bucklets/watchmanconfig .watchmanconfig
+```
+
+To build the plugin, issue the following command:
+
+
+```
+  buck build plugin
+```
+
+The output is created in
+
+```
+  buck-out/gen/@PLUGIN@.jar
+```
+
+Build in Gerrit tree
+--------------------
+
+Clone or link this plugin to the plugins directory of Gerrit's source
+tree, and issue the command:
+
+```
+  buck build plugins/@PLUGIN@
+```
+
+The output is created in
+
+```
+  buck-out/gen/plugins/@PLUGIN@/@PLUGIN@.jar
+```
+
+This project can be imported into the Eclipse IDE:
+
+```
+  ./tools/eclipse/project.py
+```
diff --git a/src/main/resources/Documentation/config.md b/src/main/resources/Documentation/config.md
new file mode 100644
index 0000000..a444519
--- /dev/null
+++ b/src/main/resources/Documentation/config.md
@@ -0,0 +1,2 @@
+The only configuration required is to grant "Create-group" and "Create-project"
+global permissions to "Registered Users" group.
\ No newline at end of file
diff --git a/src/test/java/com/ericsson/gerrit/plugins/projectgroupstructure/ProjectCreationValidatorTest.java b/src/test/java/com/ericsson/gerrit/plugins/projectgroupstructure/ProjectCreationValidatorTest.java
new file mode 100644
index 0000000..909fc39
--- /dev/null
+++ b/src/test/java/com/ericsson/gerrit/plugins/projectgroupstructure/ProjectCreationValidatorTest.java
@@ -0,0 +1,196 @@
+// Copyright (C) 2016 Ericsson
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.ericsson.gerrit.plugins.projectgroupstructure;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.gerrit.server.group.SystemGroupBackend.REGISTERED_USERS;
+
+import com.google.common.base.Charsets;
+import com.google.common.collect.Lists;
+import com.google.common.hash.Hashing;
+import com.google.gerrit.acceptance.PluginDaemonTest;
+import com.google.gerrit.acceptance.RestResponse;
+import com.google.gerrit.common.data.GlobalCapability;
+import com.google.gerrit.extensions.api.groups.GroupApi;
+import com.google.gerrit.extensions.api.projects.ProjectInput;
+import com.google.gerrit.extensions.restapi.Url;
+import com.google.gerrit.reviewdb.client.AccountGroup;
+import com.google.gerrit.reviewdb.client.Project;
+import com.google.gerrit.server.project.ProjectState;
+
+import org.apache.http.HttpStatus;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.IOException;
+
+public class ProjectCreationValidatorTest extends PluginDaemonTest {
+
+  @Before
+  public void setUp() throws Exception {
+    // These access rights are mandatory configuration for this plugin as
+    // documented in config.md
+    allowGlobalCapabilities(REGISTERED_USERS, GlobalCapability.CREATE_GROUP);
+    allowGlobalCapabilities(REGISTERED_USERS, GlobalCapability.CREATE_PROJECT);
+  }
+
+  @Test
+  public void shouldAllowAnyUsersToCreateUnderAllProjects() throws IOException {
+    ProjectInput in = new ProjectInput();
+    in.permissionsOnly = true;
+    assertThat(adminSession.put("/projects/" + name("someProject"), in)
+        .getStatusCode()).isEqualTo(HttpStatus.SC_CREATED);
+
+    assertThat(userSession.put("/projects/" + name("someOtherProject"), in)
+        .getStatusCode()).isEqualTo(HttpStatus.SC_CREATED);
+  }
+
+  @Test
+  public void shouldBlockRootProjectWithSlashesInTheirName() throws Exception {
+    // Root project is OK without slash
+    String parent = name("parentProject");
+    ProjectInput in = new ProjectInput();
+    in.permissionsOnly = true;
+    assertThat(userSession.put("/projects/" + parent, in).getStatusCode())
+        .isEqualTo(HttpStatus.SC_CREATED);
+
+    // Creation is rejected when root project name contains slashes
+    RestResponse r =
+        userSession.put("/projects/" + Url.encode("a/parentProject"), in);
+    assertThat(r.getStatusCode()).isEqualTo(HttpStatus.SC_CONFLICT);
+    assertThat(r.getEntityContent())
+        .contains("Root project name cannot contains slashes");
+  }
+
+  @Test
+  public void shouldBlockProjectWithParentNotPartOfProjectName()
+      throws Exception {
+    // Root project is OK without parent part of the name
+    ProjectInput in = new ProjectInput();
+    in.permissionsOnly = true;
+    String parent = name("parentProject");
+    assertThat(userSession.put("/projects/" + parent, in).getStatusCode())
+        .isEqualTo(HttpStatus.SC_CREATED);
+
+    // Creation is rejected when project name does not start with parent
+    in = new ProjectInput();
+    in.parent = parent;
+    RestResponse r = userSession.put("/projects/childProject", in);
+    assertThat(r.getStatusCode()).isEqualTo(HttpStatus.SC_CONFLICT);
+    assertThat(r.getEntityContent())
+        .contains("Project name must start with parent project name");
+
+    // Creation is OK when project name starts with parent
+    assertThat(
+        userSession.put("/projects/" + Url.encode(parent + "/childProject"), in)
+            .getStatusCode()).isEqualTo(HttpStatus.SC_CREATED);
+
+    // Creation is rejected when project name does not start with nested parent
+    String nestedParent = parent + "/childProject";
+    in.parent = nestedParent;
+    r = userSession.put("/projects/grandchild", in);
+    assertThat(r.getStatusCode()).isEqualTo(HttpStatus.SC_CONFLICT);
+    assertThat(r.getEntityContent())
+        .contains("Project name must start with parent project name");
+
+    // Creation is OK when project name starts with nested parent
+    assertThat(userSession
+        .put("/projects/" + Url.encode(nestedParent + "/grandchild"), in)
+        .getStatusCode()).isEqualTo(HttpStatus.SC_CREATED);
+  }
+
+  @Test
+  public void shouldBlockCreationToNonOwnersOfParentProject() throws Exception {
+    String ownerGroup = name("groupA");
+    GroupApi g = gApi.groups().create(ownerGroup);
+
+    String parent = name("parentProject");
+    ProjectInput in = new ProjectInput();
+    in.permissionsOnly = true;
+    in.owners = Lists.newArrayList(ownerGroup);
+    assertThat(adminSession.put("/projects/" + parent, in).getStatusCode())
+        .isEqualTo(HttpStatus.SC_CREATED);
+
+    // Creation is rejected when user is not owner of parent
+    in = new ProjectInput();
+    in.parent = parent;
+    RestResponse r = userSession
+        .put("/projects/" + Url.encode(parent + "/childProject"), in);
+    assertThat(r.getStatusCode()).isEqualTo(HttpStatus.SC_CONFLICT);
+    assertThat(r.getEntityContent())
+        .contains("You must be owner of the parent project");
+
+    // Creation is OK when user is owner of parent
+    g.addMembers(user.username);
+    assertThat(
+        userSession.put("/projects/" + Url.encode(parent + "/childProject"), in)
+            .getStatusCode()).isEqualTo(HttpStatus.SC_CREATED);
+  }
+
+  @Test
+  public void shouldAllowAdminsToByPassAnyRule() throws IOException {
+    // Root project with a slash
+    String parent = name("orgA/parentProject");
+    ProjectInput in = new ProjectInput();
+    in.permissionsOnly = true;
+    assertThat(
+        adminSession.put("/projects/" + Url.encode(parent), in).getStatusCode())
+            .isEqualTo(HttpStatus.SC_CREATED);
+
+    // Child project without name of parent as prefix
+    in = new ProjectInput();
+    in.parent = parent;
+    assertThat(
+        adminSession.put("/projects/" + Url.encode("orgA/childProject"), in)
+            .getStatusCode()).isEqualTo(HttpStatus.SC_CREATED);
+  }
+
+  @Test
+  public void shouldMakeUserOwnerOnRootProjectCreation() throws Exception {
+    // normal case, when <project-name>-admins group does not exist
+    String rootProject = name("rootProject");
+    ProjectInput in = new ProjectInput();
+    in.permissionsOnly = true;
+    assertThat(userSession.put("/projects/" + rootProject, in).getStatusCode())
+        .isEqualTo(HttpStatus.SC_CREATED);
+    ProjectState projectState =
+        projectCache.get(new Project.NameKey(rootProject));
+    assertThat(projectState.getOwners().size()).isEqualTo(1);
+    assertThat(projectState.getOwners()).contains(groupCache
+        .get(new AccountGroup.NameKey(rootProject + "-admins")).getGroupUUID());
+
+    // case when <project-name>-admins group already exists
+    rootProject = name("rootProject2");
+    String existingGroupName = rootProject + "-admins";
+    gApi.groups().create(existingGroupName);
+    assertThat(userSession.put("/projects/" + rootProject, in).getStatusCode())
+        .isEqualTo(HttpStatus.SC_CREATED);
+    projectState = projectCache.get(new Project.NameKey(rootProject));
+    assertThat(projectState.getOwners().size()).isEqualTo(1);
+    String expectedOwnerGroup = existingGroupName + "-"
+        + Hashing.sha1().hashString(existingGroupName, Charsets.UTF_8)
+            .toString().substring(0, 7);
+    assertThat(projectState.getOwners()).contains(groupCache
+        .get(new AccountGroup.NameKey(expectedOwnerGroup)).getGroupUUID());
+  }
+
+  @Test
+  public void shouldBlockRootCodeProject() throws Exception {
+    RestResponse r = userSession.put("/projects/" + Url.encode("project1"));
+    assertThat(r.getStatusCode()).isEqualTo(HttpStatus.SC_CONFLICT);
+    assertThat(r.getEntityContent())
+        .contains("Regular projects are not allowed as root");
+  }
+}