diff --git a/Jenkinsfile b/Jenkinsfile index 64c881183a..4d11767e67 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -1,47 +1,117 @@ #!groovy -@Library('github.com/cloudogu/ces-build-lib@ac17d45') + +// Keep the version in sync with the one used in pom.xml in order to get correct syntax completion. +@Library('github.com/cloudogu/ces-build-lib@9aadeeb') import com.cloudogu.ces.cesbuildlib.* node() { // No specific label - properties([ - // Keep only the last 10 build to preserve space - buildDiscarder(logRotator(numToKeepStr: '10')), - // Don't run concurrent builds for a branch, because they use the same workspace directory - disableConcurrentBuilds() - ]) + // Change this as when we go back to default - necessary for proper SonarQube analysis + mainBranch = "2.0.0-m3" - String defaultEmailRecipients = env.EMAIL_SCM_RECIPIENTS + properties([ + // Keep only the last 10 build to preserve space + buildDiscarder(logRotator(numToKeepStr: '10')), + ]) - catchError { + catchError { - Maven mvn = new MavenWrapper(this) + Maven mvn = setupMavenBuild() + // Maven build specified it must be 1.8.0-101 or newer + def javaHome = tool 'JDK-1.8.0-101+' - stage('Checkout') { - checkout scm - } - - stage('Build') { - mvn 'clean install -DskipTests -DperformRelease' - archive '**/target/*.jar,**/target/*.zip' - } - - stage('Unit Test') { - mvn 'test -Dsonia.scm.test.skip.hg=true' - } - - stage('SonarQube') { - def sonarQube = new SonarQube(this, 'ces-sonar') - - sonarQube.analyzeWith(mvn) + withEnv(["JAVA_HOME=${javaHome}", "PATH=${env.JAVA_HOME}/bin:${env.PATH}"]) { + + stage('Checkout') { + checkout scm + } + + stage('Build') { + mvn 'clean install -DskipTests' + } + + stage('Unit Test') { + mvn 'test -Dsonia.scm.test.skip.hg=true' + } + + stage('SonarQube') { + + analyzeWith(mvn) + + if (!waitForQualityGateWebhookToBeCalled()) { + currentBuild.result = 'UNSTABLE' } + } } + } - // Archive Unit and integration test results, if any - junit allowEmptyResults: true, testResults: '**/target/failsafe-reports/TEST-*.xml,**/target/surefire-reports/TEST-*.xml,**/target/jest-reports/TEST-*.xml' + // Archive Unit and integration test results, if any + junit allowEmptyResults: true, testResults: '**/target/failsafe-reports/TEST-*.xml,**/target/surefire-reports/TEST-*.xml,**/target/jest-reports/TEST-*.xml' - // Find maven warnings and visualize in job - warnings consoleParsers: [[parserName: 'Maven']], canRunOnFailed: true + // Find maven warnings and visualize in job + warnings consoleParsers: [[parserName: 'Maven']], canRunOnFailed: true - mailIfStatusChanged(defaultEmailRecipients) + mailIfStatusChanged(commitAuthorEmail) +} + +String mainBranch + +Maven setupMavenBuild() { + Maven mvn = new MavenWrapper(this) + + if (mainBranch.equals(env.BRANCH_NAME)) { + // Release starts javadoc, which takes very long, so do only for certain branches + mvn.additionalArgs += ' -DperformRelease' + // JDK8 is more strict, we should fix this before the next release. Right now, this is just not the focus, yet. + mvn.additionalArgs += ' -Dmaven.javadoc.failOnError=false' + } + return mvn +} + +void analyzeWith(Maven mvn) { + + withSonarQubeEnv('sonarcloud.io') { + + String mvnArgs = "${env.SONAR_MAVEN_GOAL} " + + "-Dsonar.host.url=${env.SONAR_HOST_URL} " + + "-Dsonar.login=${env.SONAR_AUTH_TOKEN} " + + if (isPullRequest()) { + echo "Analysing SQ in PR mode" + mvnArgs += "-Dsonar.pullrequest.base=${env.CHANGE_TARGET} " + + "-Dsonar.pullrequest.branch=${env.CHANGE_BRANCH} " + + "-Dsonar.pullrequest.key=${env.CHANGE_ID} " + + "-Dsonar.pullrequest.provider=bitbucketcloud " + + "-Dsonar.pullrequest.bitbucketcloud.owner=sdorra " + + "-Dsonar.pullrequest.bitbucketcloud.repository=scm-manager " + } else { + mvnArgs += " -Dsonar.branch.name=${env.BRANCH_NAME} " + if (!mainBranch.equals(env.BRANCH_NAME)) { + // Avoid exception "The main branch must not have a target" on main branch + mvnArgs += " -Dsonar.branch.target=${mainBranch} " + } + } + mvn "${mvnArgs}" + } +} + +boolean waitForQualityGateWebhookToBeCalled() { + boolean isQualityGateSucceeded = true + timeout(time: 2, unit: 'MINUTES') { // Needed when there is no webhook for example + def qGate = waitForQualityGate() + echo "SonarQube Quality Gate status: ${qGate.status}" + if (qGate.status != 'OK') { + isQualityGateSucceeded = false + } + } + return isQualityGateSucceeded +} + +String getCommitAuthorComplete() { + new Sh(this).returnStdOut 'hg log --branch . --limit 1 --template "{author}"' +} + +String getCommitAuthorEmail() { + def matcher = getCommitAuthorComplete() =~ "<(.*?)>" + matcher ? matcher[0][1] : "" } diff --git a/pom.xml b/pom.xml index 7ed637f0d7..1f33be2b6c 100644 --- a/pom.xml +++ b/pom.xml @@ -73,7 +73,6 @@ scm-ui scm-webapp scm-server - scm-clients @@ -146,10 +145,31 @@ ${mokito.version} test + + + + com.github.cloudogu + ces-build-lib + + 9aadeeb + + true + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.0.1 + + + + @@ -205,6 +225,23 @@ + + com.github.legman + legman-maven-plugin + ${legman.version} + + true + + + + process-classes + + guava-migration-check + + + + + org.apache.maven.plugins maven-compiler-plugin @@ -255,7 +292,6 @@ org.apache.maven.plugins maven-javadoc-plugin - 2.9 true ${project.build.sourceEncoding} @@ -440,7 +476,6 @@ org.apache.maven.plugins maven-javadoc-plugin - 2.8.1 org.jboss.apiviz.APIviz @@ -495,7 +530,7 @@ 4.0 - 1.2.0 + 1.3.0 9.2.10.v20150310 diff --git a/scm-annotation-processor/src/main/java/sonia/scm/annotation/ScmAnnotationProcessor.java b/scm-annotation-processor/src/main/java/sonia/scm/annotation/ScmAnnotationProcessor.java index b49713d61a..c548f30d45 100644 --- a/scm-annotation-processor/src/main/java/sonia/scm/annotation/ScmAnnotationProcessor.java +++ b/scm-annotation-processor/src/main/java/sonia/scm/annotation/ScmAnnotationProcessor.java @@ -1,9 +1,9 @@ /** * Copyright (c) 2010, Sebastian Sdorra All rights reserved. - * + *

* Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + *

* 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. 2. Redistributions in * binary form must reproduce the above copyright notice, this list of @@ -11,7 +11,7 @@ * materials provided with the distribution. 3. Neither the name of SCM-Manager; * 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 @@ -22,13 +22,11 @@ * 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. - * + *

* http://bitbucket.org/sdorra/scm-manager - * */ - package sonia.scm.annotation; //~--- non-JDK imports -------------------------------------------------------- @@ -107,84 +105,51 @@ import javax.xml.transform.stream.StreamResult; */ @SupportedAnnotationTypes("*") @MetaInfServices(Processor.class) -@SuppressWarnings({ "Since16", "Since15" }) +@SuppressWarnings({"Since16", "Since15"}) @SupportedSourceVersion(SourceVersion.RELEASE_8) -public final class ScmAnnotationProcessor extends AbstractProcessor -{ +public final class ScmAnnotationProcessor extends AbstractProcessor { - /** Field description */ private static final String DESCRIPTOR_MODULE = "META-INF/scm/module.xml"; - - /** Field description */ private static final String DESCRIPTOR_PLUGIN = "META-INF/scm/plugin.xml"; - - /** Field description */ private static final String EL_MODULE = "module"; - - /** Field description */ private static final String EMPTY = ""; - - /** Field description */ private static final String PROPERTY_VALUE = "yes"; - - /** Field description */ private static final Set SUBSCRIBE_ANNOTATIONS = ImmutableSet.of(Subscribe.class.getName()); - - /** Field description */ private static final Set CLASS_ANNOTATIONS = ImmutableSet.of(new ClassAnnotation("rest-resource", Path.class), new ClassAnnotation("rest-provider", Provider.class)); - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param annotations - * @param roundEnv - * - * @return - */ @Override public boolean process(Set annotations, - RoundEnvironment roundEnv) - { - if (!roundEnv.processingOver()) - { + RoundEnvironment roundEnv) { + if (!roundEnv.processingOver()) { Set descriptorElements = Sets.newHashSet(); Set subscriberAnnotations = Sets.newHashSet(); - for (TypeElement e : annotations) - { + for (TypeElement e : annotations) { PluginAnnotation pa = e.getAnnotation(PluginAnnotation.class); - if (pa != null) - { + if (pa != null) { scanForClassAnnotations(descriptorElements, roundEnv, e, pa.value()); } - if (SUBSCRIBE_ANNOTATIONS.contains(e.getQualifiedName().toString())) - { + if (SUBSCRIBE_ANNOTATIONS.contains(e.getQualifiedName().toString())) { subscriberAnnotations.add(e); } } - for (ClassAnnotation ca : CLASS_ANNOTATIONS) - { + for (ClassAnnotation ca : CLASS_ANNOTATIONS) { TypeElement annotation = findAnnotation(annotations, - ca.annotationClass); + ca.annotationClass); - if (annotation != null) - { + if (annotation != null) { scanForClassAnnotations(descriptorElements, roundEnv, annotation, ca.elementName); } } - for (TypeElement annotation : subscriberAnnotations) - { + for (TypeElement annotation : subscriberAnnotations) { scanForSubscriberAnnotations(descriptorElements, roundEnv, annotation); } @@ -194,46 +159,25 @@ public final class ScmAnnotationProcessor extends AbstractProcessor return false; } - /** - * Method description - * - * - * @param closeable - */ - private void close(Closeable closeable) - { - if (closeable != null) - { - try - { + + private void close(Closeable closeable) { + if (closeable != null) { + try { closeable.close(); - } - catch (IOException ex) - { + } catch (IOException ex) { printException("could not close closeable", ex); } } } - /** - * Method description - * - * - * @param annotations - * @param annotationClass - * - * @return - */ + private TypeElement findAnnotation(Set annotations, - Class annotationClass) - { + Class annotationClass) { TypeElement annotation = null; - for (TypeElement te : annotations) - { - if (te.getQualifiedName().toString().equals(annotationClass.getName())) - { - annotation = te; + for (TypeElement typeElement : annotations) { + if (typeElement.getQualifiedName().toString().equals(annotationClass.getName())) { + annotation = typeElement; break; } @@ -242,24 +186,13 @@ public final class ScmAnnotationProcessor extends AbstractProcessor return annotation; } - /** - * Method description - * - * - * @param filer - * - * @return - * - * @throws IOException - */ - private File findDescriptor(Filer filer) throws IOException - { + + private File findDescriptor(Filer filer) throws IOException { FileObject f = filer.getResource(StandardLocation.CLASS_OUTPUT, EMPTY, - DESCRIPTOR_PLUGIN); + DESCRIPTOR_PLUGIN); File file = new File(f.toUri()); - if (!file.exists()) - { + if (!file.exists()) { f = filer.getResource(StandardLocation.CLASS_OUTPUT, EMPTY, DESCRIPTOR_MODULE); file = new File(f.toUri()); @@ -268,68 +201,40 @@ public final class ScmAnnotationProcessor extends AbstractProcessor return file; } - /** - * Method description - * - * - * @param f - * - * @param file - * - * @return - */ - private Document parseDocument(File file) - { + + private Document parseDocument(File file) { Document doc = null; InputStream input = null; - try - { + try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - if (file.exists()) - { + if (file.exists()) { input = new FileInputStream(file); doc = builder.parse(input); - } - else - { + } else { doc = builder.newDocument(); doc.appendChild(doc.createElement(EL_MODULE)); } - } - catch (ParserConfigurationException | SAXException | IOException - | DOMException ex) - { + } catch (ParserConfigurationException | SAXException | IOException + | DOMException ex) { printException("could not parse document", ex); - } - finally - { + } finally { close(input); } return doc; } - /** - * Method description - * - * - * @param obj - * - * @return - */ - private String prepareArrayElement(Object obj) - { + + private String prepareArrayElement(Object obj) { String v = obj.toString(); - if (v.startsWith("\"")) - { + if (v.startsWith("\"")) { v = v.substring(1); - if (v.endsWith("")) - { + if (v.endsWith("")) { v = v.substring(0, v.length() - 1); } } @@ -337,15 +242,8 @@ public final class ScmAnnotationProcessor extends AbstractProcessor return v; } - /** - * Method description - * - * - * @param msg - * @param throwable - */ - private void printException(String msg, Throwable throwable) - { + + private void printException(String msg, Throwable throwable) { processingEnv.getMessager().printMessage(Kind.ERROR, msg); String stack = Throwables.getStackTraceAsString(throwable); @@ -353,144 +251,98 @@ public final class ScmAnnotationProcessor extends AbstractProcessor processingEnv.getMessager().printMessage(Kind.ERROR, stack); } - /** - * Method description - * - * - * @param descriptorElements - * @param roundEnv - * @param annotation - * @param elementName - * @param elements - * - * @return - */ + private void scanForClassAnnotations( Set descriptorElements, RoundEnvironment roundEnv, - TypeElement annotation, String elementName) - { + TypeElement annotation, String elementName) { + Set classes = Sets.newHashSet(); - for (Element e : roundEnv.getElementsAnnotatedWith(annotation)) - { - if (e.getKind().isClass() || e.getKind().isInterface()) - { + for (Element e : roundEnv.getElementsAnnotatedWith(annotation)) { + + if (isClassOrInterface(e)) { TypeElement type = (TypeElement) e; String desc = processingEnv.getElementUtils().getDocComment(type); - if (desc != null) - { + if (desc != null) { desc = desc.trim(); } - //J- classes.add( new ClassWithAttributes( - type.getQualifiedName().toString(), - desc, - getAttributesFromAnnotation(e, annotation) + type.getQualifiedName().toString(), desc, getAttributesFromAnnotation(e, annotation) ) ); - //J+ } } descriptorElements.add(new ClassSetElement(elementName, classes)); } - /** - * Method description - * - * - * @param descriptorElements - * @param roundEnv - * @param annotation - */ + + private boolean isClassOrInterface(Element e) { + return e.getKind().isClass() || e.getKind().isInterface(); + } + + private void scanForSubscriberAnnotations( Set descriptorElements, RoundEnvironment roundEnv, - TypeElement annotation) - { - for (Element el : roundEnv.getElementsAnnotatedWith(annotation)) - { - if (el.getKind() == ElementKind.METHOD) - { + TypeElement annotation) { + for (Element el : roundEnv.getElementsAnnotatedWith(annotation)) { + if (el.getKind() == ElementKind.METHOD) { ExecutableElement ee = (ExecutableElement) el; List params = ee.getParameters(); - if ((params != null) && (params.size() == 1)) - { + if ((params != null) && (params.size() == 1)) { VariableElement param = params.get(0); Element clazz = el.getEnclosingElement(); String desc = processingEnv.getElementUtils().getDocComment(clazz); - if (desc != null) - { + if (desc != null) { desc = desc.trim(); } - //J- descriptorElements.add( new SubscriberElement( - clazz.toString(), + clazz.toString(), param.asType().toString(), desc ) ); - //J+ } } } } - /** - * Method description - * - * - * @param descriptorElements - */ - private void write(Set descriptorElements) - { + + private void write(Set descriptorElements) { Filer filer = processingEnv.getFiler(); - try - { + try { File file = findDescriptor(filer); Document doc = parseDocument(file); - if (doc != null) - { + if (doc != null) { org.w3c.dom.Element root = doc.getDocumentElement(); - for (DescriptorElement el : descriptorElements) - { + for (DescriptorElement el : descriptorElements) { el.append(doc, root); } writeDocument(doc, file); } - } - catch (IOException ex) - { + } catch (IOException ex) { printException("could not open plugin descriptor", ex); } } - /** - * Method description - * - * - * @param doc - * @param f - * @param file - */ - private void writeDocument(Document doc, File file) - { + + private void writeDocument(Document doc, File file) { Writer writer = null; - try - { + try { file.getParentFile().mkdirs(); writer = new FileWriter(file); @@ -499,42 +351,24 @@ public final class ScmAnnotationProcessor extends AbstractProcessor transformer.setOutputProperty(OutputKeys.INDENT, PROPERTY_VALUE); transformer.transform(new DOMSource(doc), new StreamResult(writer)); - } - catch (IOException | IllegalArgumentException | TransformerException ex) - { + } catch (IOException | IllegalArgumentException | TransformerException ex) { printException("could not write document", ex); - } - finally - { + } finally { close(writer); } } - //~--- get methods ---------------------------------------------------------- - /** - * Method description - * - * - * @param el - * @param annotation - * - * @return - */ private Map getAttributesFromAnnotation(Element el, - TypeElement annotation) - { + TypeElement annotation) { Map attributes = Maps.newHashMap(); - for (AnnotationMirror am : el.getAnnotationMirrors()) - { - String qn = am.getAnnotationType().asElement().toString(); + for (AnnotationMirror annotationMirror : el.getAnnotationMirrors()) { + String qn = annotationMirror.getAnnotationType().asElement().toString(); - if (qn.equals(annotation.toString())) - { + if (qn.equals(annotation.toString())) { for (Entry entry : am.getElementValues().entrySet()) - { + ? extends AnnotationValue> entry : annotationMirror.getElementValues().entrySet()) { attributes.put(entry.getKey().getSimpleName().toString(), getValue(entry.getValue())); } @@ -544,77 +378,42 @@ public final class ScmAnnotationProcessor extends AbstractProcessor return attributes; } - /** - * Method description - * - * - * @param v - * - * @return - */ - private String getValue(AnnotationValue v) - { + + private String getValue(AnnotationValue v) { String value; Object object = v.getValue(); - if (object instanceof Iterable) - { + if (object instanceof Iterable) { Iterator it = ((Iterable) object).iterator(); StringBuilder buffer = new StringBuilder(); - while (it.hasNext()) - { + while (it.hasNext()) { buffer.append(prepareArrayElement(it.next())); - if (it.hasNext()) - { + if (it.hasNext()) { buffer.append(","); } - } value = buffer.toString(); - } - else - { + } else { value = object.toString(); } return value; } - //~--- inner classes -------------------------------------------------------- - /** - * Class description - * - * - * @version Enter version here..., 14/03/18 - * @author Enter your name here... - */ - private static final class ClassAnnotation - { + private static final class ClassAnnotation { - /** - * Constructs ... - * - * - * @param elementName - * @param annotationClass - */ public ClassAnnotation(String elementName, - Class annotationClass) - { + Class annotationClass) { + this.elementName = elementName; this.annotationClass = annotationClass; } - //~--- fields ------------------------------------------------------------- - - /** Field description */ private final Class annotationClass; - - /** Field description */ private final String elementName; } } diff --git a/scm-annotations/src/main/java/sonia/scm/plugin/ExtensionPoint.java b/scm-annotations/src/main/java/sonia/scm/plugin/ExtensionPoint.java index 5417317627..b36a28f993 100644 --- a/scm-annotations/src/main/java/sonia/scm/plugin/ExtensionPoint.java +++ b/scm-annotations/src/main/java/sonia/scm/plugin/ExtensionPoint.java @@ -33,8 +33,6 @@ package sonia.scm.plugin; -//~--- JDK imports ------------------------------------------------------------ - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/scm-clients/pom.xml b/scm-clients/pom.xml deleted file mode 100644 index e78be6afa5..0000000000 --- a/scm-clients/pom.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - - 4.0.0 - - - sonia.scm - scm - 2.0.0-SNAPSHOT - - - sonia.scm.clients - scm-clients - pom - 2.0.0-SNAPSHOT - scm-clients - - - scm-client-api - scm-client-impl - scm-cli-client - - - - - - - - scm-core - sonia.scm - jar - 2.0.0-SNAPSHOT - - - shiro-core - org.apache.shiro - - - aopalliance - aopalliance - - - guice - com.google.inject - - - guice-multibindings - com.google.inject.extensions - - - guice-servlet - com.google.inject.extensions - - - jersey-core - com.sun.jersey - - - guice-throwingproviders - com.google.inject.extensions - - - commons-lang - commons-lang - - - - - - - diff --git a/scm-clients/scm-cli-client/pom.xml b/scm-clients/scm-cli-client/pom.xml deleted file mode 100644 index e5605878f8..0000000000 --- a/scm-clients/scm-cli-client/pom.xml +++ /dev/null @@ -1,219 +0,0 @@ - - - - 4.0.0 - - - scm-clients - sonia.scm.clients - 2.0.0-SNAPSHOT - - - sonia.scm.clients - scm-cli-client - 2.0.0-SNAPSHOT - scm-cli-client - - - - - - - javax.servlet - javax.servlet-api - ${servlet.version} - - - - javax.transaction - jta - 1.1 - provided - - - - sonia.scm.clients - scm-client-impl - 2.0.0-SNAPSHOT - - - - args4j - args4j - 2.0.29 - - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.freemarker - freemarker - 2.3.21 - - - - - - - - - com.mycila.maven-license-plugin - maven-license-plugin - 1.9.0 - -

http://download.scm-manager.org/licenses/mvn-license.txt
- - src/** - **/test/** - - - target/** - .hg/** - **/*.ftl - - true -
-
- - - org.apache.maven.plugins - maven-assembly-plugin - 2.3 - - - - sonia.scm.cli.App - - - - jar-with-dependencies - - - - - package - - single - - - - - -
-
- - - - - it - - - - - - org.apache.maven.plugins - maven-dependency-plugin - 2.4 - - - package - - copy - - - - - sonia.scm - scm-webapp - ${project.version} - war - ${project.build.directory}/webapp - scm-webapp.war - - - - - - - - - org.apache.maven.plugins - maven-failsafe-plugin - 2.12 - - - ${project.version} - - - - - integration-test - - integration-test - - - - verify - - verify - - - - - - - org.eclipse.jetty - jetty-maven-plugin - ${jetty.maven.version} - - 8085 - STOP - - - scm.home - target/scm-it - - - file.encoding - UTF-8 - - - - 8081 - - - /scm - - ${project.build.directory}/webapp/scm-webapp.war - 0 - true - - - - start-jetty - pre-integration-test - - deploy-war - - - - stop-jetty - post-integration-test - - stop - - - - - - - - - - - - diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/App.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/App.java deleted file mode 100644 index ca8737101c..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/App.java +++ /dev/null @@ -1,339 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli; - -//~--- non-JDK imports -------------------------------------------------------- - -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.LoggerContext; - -import org.kohsuke.args4j.Argument; -import org.kohsuke.args4j.CmdLineException; -import org.kohsuke.args4j.CmdLineParser; -import org.kohsuke.args4j.Option; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import sonia.scm.cli.cmd.CommandDescriptor; -import sonia.scm.cli.cmd.SubCommand; -import sonia.scm.cli.cmd.SubCommandHandler; -import sonia.scm.cli.cmd.SubCommandOptionHandler; -import sonia.scm.cli.config.ConfigOptionHandler; -import sonia.scm.cli.config.ScmClientConfig; -import sonia.scm.cli.config.ServerConfig; -import sonia.scm.util.IOUtil; -import sonia.scm.util.Util; - -//~--- JDK imports ------------------------------------------------------------ - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.PrintWriter; - -import java.util.ArrayList; -import java.util.List; - -/** - * - * @author Sebastian Sdorra - */ -public class App -{ - - /** the logger for App */ - private static final Logger logger = LoggerFactory.getLogger(App.class); - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - */ - public App() - { - this(System.in, System.out); - } - - /** - * Constructs ... - * - * - * @param input - * @param output - */ - public App(BufferedReader input, PrintWriter output) - { - this.input = input; - this.output = output; - } - - /** - * Constructs ... - * - * - * @param input - * @param output - */ - public App(InputStream input, OutputStream output) - { - this.input = new BufferedReader(new InputStreamReader(input)); - this.output = new PrintWriter(output); - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param args - */ - public static void main(String[] args) - { - new App().run(args); - } - - /** - * Method description - * - * - * @param args - */ - protected void run(String[] args) - { - CmdLineParser parser = new CmdLineParser(this); - - try - { - parser.parseArgument(args); - } - catch (CmdLineException ex) - { - - // todo error handling - logger.warn("could not parse commandline", ex); - System.exit(1); - } - - configureLogger(); - loadConfig(); - - I18n i18n = new I18n(); - - if ((args.length == 0) || (subcommand == null) || help) - { - printHelp(parser, i18n); - } - else - { - subcommand.init(input, output, i18n, config); - subcommand.run(arguments); - } - - IOUtil.close(input); - IOUtil.close(output); - } - - /** - * Method description - * - */ - private void configureLogger() - { - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - - lc.getLogger(Logger.ROOT_LOGGER_NAME).setLevel(loggingLevel); - } - - /** - * Method description - * - */ - private void loadConfig() - { - if (config == null) - { - config = ScmClientConfig.getInstance().getDefaultConfig(); - } - - if (Util.isNotEmpty(serverUrl)) - { - config.setServerUrl(serverUrl); - } - - if (Util.isNotEmpty(username)) - { - config.setUsername(username); - } - - if (Util.isNotEmpty(password)) - { - config.setPassword(password); - } - } - - /** - * Method description - * - * - * @param parser - * @param i18n - */ - private void printHelp(CmdLineParser parser, I18n i18n) - { - output.println(i18n.getMessage(I18n.USAGE)); - output.println(); - output.append(i18n.getMessage(I18n.OPTIONS)).println(":"); - output.println(); - parser.printUsage(output, i18n.getBundle()); - output.println(); - output.append(i18n.getMessage(I18n.SUBCOMMANDS_TITLE)).println(":"); - output.println(); - - String group = null; - List descList = - SubCommandHandler.getInstance().getDescriptors(); - int length = 0; - - for (CommandDescriptor desc : descList) - { - int l = desc.getName().length(); - - if (l > length) - { - length = l; - } - } - - length += 5; - - for (CommandDescriptor desc : - SubCommandHandler.getInstance().getDescriptors()) - { - if ((group == null) ||!group.equals(desc.getGroup())) - { - output.println(); - group = desc.getGroup(); - output.append(i18n.getMessage(group)).println(":"); - output.println(); - } - - int l = desc.getName().length(); - - output.append(" ").append(desc.getName()); - l = length - l; - - for (int i = 0; i < l; i++) - { - output.append(" "); - } - - output.println(i18n.getMessage(desc.getUsage())); - } - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Option( - name = "--config", - usage = "optionConfig", - metaVar = "config", - handler = ConfigOptionHandler.class, - aliases = { "-c" } - ) - private ServerConfig config; - - /** Field description */ - @Option( - name = "--help", - usage = "optionHelpText", - aliases = { "-h" } - ) - private boolean help = false; - - /** Field description */ - @Argument(index = 1, metaVar = "arg") - private List arguments = new ArrayList(); - - /** Field description */ - private BufferedReader input; - - /** Field description */ - @Option( - name = "--logging-level", - usage = "optionLoggingLevel", - handler = LoggingLevelOptionHandler.class, - aliases = { "-l" } - ) - private Level loggingLevel = Level.ERROR; - - /** Field description */ - private PrintWriter output; - - /** Field description */ - @Option( - name = "--password", - usage = "optionPassword", - aliases = { "-p" } - ) - private String password; - - /** Field description */ - @Option( - name = "--server", - usage = "optionServerUrl", - aliases = { "-s" } - ) - private String serverUrl; - - /** Field description */ - @Argument( - index = 0, - metaVar = "metaVar_command", - handler = SubCommandOptionHandler.class - ) - private SubCommand subcommand; - - /** Field description */ - @Option( - name = "--user", - usage = "optionUsername", - aliases = { "-u" } - ) - private String username; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/BooleanModifyOptionHandler.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/BooleanModifyOptionHandler.java deleted file mode 100644 index 46d18badb6..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/BooleanModifyOptionHandler.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - -package sonia.scm.cli; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.CmdLineException; -import org.kohsuke.args4j.CmdLineParser; -import org.kohsuke.args4j.OptionDef; -import org.kohsuke.args4j.spi.OptionHandler; -import org.kohsuke.args4j.spi.Parameters; -import org.kohsuke.args4j.spi.Setter; - -/** - * - * @author Sebastian Sdorra - */ -public class BooleanModifyOptionHandler extends OptionHandler -{ - - /** - * Constructs ... - * - * - * @param parser - * @param option - * @param setter - */ - public BooleanModifyOptionHandler(CmdLineParser parser, OptionDef option, - Setter setter) - { - super(parser, option, setter); - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param params - * - * @return - * - * @throws CmdLineException - */ - @Override - public int parseArguments(Parameters params) throws CmdLineException - { - Boolean bool = Boolean.valueOf(params.getParameter(0)); - - setter.addValue(bool); - - return 1; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - @Override - public String getDefaultMetaVariable() - { - return I18n.BOOLEAN; - } -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/I18n.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/I18n.java deleted file mode 100644 index 8147c59b44..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/I18n.java +++ /dev/null @@ -1,138 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -/** - * - * @author Sebastian Sdorra - */ -public class I18n -{ - - /** Field description */ - public static final String ERROR = "error"; - - /** Field description */ - public static final String GROUP_NOT_FOUND = "groupNotFound"; - - /** Field description */ - public static final String LEVEL = "level"; - - - public static final String BOOLEAN = "boolean"; - - /** Field description */ - public static final String OPTIONS = "options"; - - /** Field description */ - public static final String REPOSITORY_NOT_FOUND = "repositoryNotFound"; - - /** Field description */ - public static final String RESOURCE_BUNDLE = "sonia.resources.i18n"; - - /** Field description */ - public static final String SUBCOMMANDS_TITLE = "subCommandsTitle"; - - /** Field description */ - public static final String USAGE = "usage"; - - /** Field description */ - public static final String USER_NOT_FOUND = "userNotFound"; - - /** the logger for I18n */ - private static final Logger logger = LoggerFactory.getLogger(I18n.class); - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - */ - public I18n() - { - bundle = ResourceBundle.getBundle(RESOURCE_BUNDLE); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public ResourceBundle getBundle() - { - return bundle; - } - - /** - * Method description - * - * - * @param key - * - * @return - */ - public String getMessage(String key) - { - String value = key; - - try - { - value = bundle.getString(key); - } - catch (MissingResourceException ex) - { - logger.warn("could not find resource for key {}", key); - } - - return value; - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private ResourceBundle bundle; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/LoggingLevelOptionHandler.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/LoggingLevelOptionHandler.java deleted file mode 100644 index 2622abecfb..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/LoggingLevelOptionHandler.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli; - -//~--- non-JDK imports -------------------------------------------------------- - -import ch.qos.logback.classic.Level; - -import org.kohsuke.args4j.CmdLineException; -import org.kohsuke.args4j.CmdLineParser; -import org.kohsuke.args4j.OptionDef; -import org.kohsuke.args4j.spi.OptionHandler; -import org.kohsuke.args4j.spi.Parameters; -import org.kohsuke.args4j.spi.Setter; - -/** - * - * @author Sebastian Sdorra - */ -public class LoggingLevelOptionHandler extends OptionHandler -{ - - /** - * Constructs ... - * - * - * @param parser - * @param option - * @param setter - */ - public LoggingLevelOptionHandler(CmdLineParser parser, OptionDef option, - Setter setter) - { - super(parser, option, setter); - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param params - * - * @return - * - * @throws CmdLineException - */ - @Override - public int parseArguments(Parameters params) throws CmdLineException - { - String value = params.getParameter(0); - Level l = Level.toLevel(value); - - setter.addValue(l); - - return 1; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - @Override - public String getDefaultMetaVariable() - { - return I18n.LEVEL; - } -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/SimpleLocalizable.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/SimpleLocalizable.java deleted file mode 100644 index 33fc3ef0b5..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/SimpleLocalizable.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Copyright (c) 2014, Sebastian Sdorra All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of SCM-Manager; - * 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.Localizable; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.Locale; - -/** - * TODO create real implementation - * - * @author Sebastian Sdorra - */ -public class SimpleLocalizable implements Localizable -{ - - /** - * Constructs ... - * - * - * @param message - */ - public SimpleLocalizable(String message) - { - this.message = message; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param args - * - * @return - */ - @Override - public String format(Object... args) - { - return message; - } - - /** - * Method description - * - * - * @param locale - * @param args - * - * @return - */ - @Override - public String formatWithLocale(Locale locale, Object... args) - { - return message; - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private final String message; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/AddMembersSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/AddMembersSubCommand.java deleted file mode 100644 index 2538367fb0..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/AddMembersSubCommand.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.group.Group; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.List; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "add-members", - usage = "usageAddMember", - group = "group" -) -public class AddMembersSubCommand extends MembersSubCommand -{ - - /** - * Method description - * - * - * @param group - * @param members - */ - @Override - protected void modifyMembers(Group group, List members) - { - group.getMembers().addAll(members); - } -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/AddPermissionSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/AddPermissionSubCommand.java deleted file mode 100644 index 621ebe54de..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/AddPermissionSubCommand.java +++ /dev/null @@ -1,147 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.Option; - -import sonia.scm.repository.Permission; -import sonia.scm.repository.PermissionType; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.List; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "add-permission", - usage = "usageAddPermission", - group = "repository" -) -public class AddPermissionSubCommand extends PermissionSubCommand -{ - - /** - * Method description - * - * - * @return - */ - public PermissionType getType() - { - return type; - } - - /** - * Method description - * - * - * @return - */ - public boolean isGroup() - { - return group; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param group - */ - public void setGroup(boolean group) - { - this.group = group; - } - - /** - * Method description - * - * - * @param type - */ - public void setType(PermissionType type) - { - this.type = type; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param permissions - */ - @Override - protected void modifyPermissions(List permissions) - { - permissions.add(new Permission(name, type, group)); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Option( - name = "--group", - usage = "optionPermissionGroup", - aliases = { "-g" } - ) - private boolean group = false; - - /** Field description */ - @Option( - name = "--name", - usage = "optionPermissionName", - required = true, - aliases = { "-n" } - ) - private String name; - - /** Field description */ - @Option( - name = "--type", - usage = "optionPermissionType", - required = true, - metaVar = "permissiontype", - aliases = { "-t" } - ) - private PermissionType type; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/Command.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/Command.java deleted file mode 100644 index ea6e988dae..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/Command.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- JDK imports ------------------------------------------------------------ - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * - * @author Sebastian Sdorra - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -public @interface Command -{ - String name() default ""; - String usage() default ""; - String group() default "misc"; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/CommandDescriptor.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/CommandDescriptor.java deleted file mode 100644 index ce51657ea9..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/CommandDescriptor.java +++ /dev/null @@ -1,204 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import sonia.scm.util.AssertUtil; -import sonia.scm.util.Util; - -/** - * - * @author Sebastian Sdorra - */ -public class CommandDescriptor implements Comparable -{ - - /** the logger for CommandDescriptor */ - private static final Logger logger = - LoggerFactory.getLogger(CommandDescriptor.class); - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - * - * @param commandClass - */ - public CommandDescriptor(Class commandClass) - { - AssertUtil.assertIsNotNull(commandClass); - this.commandClass = commandClass; - - Command cmd = commandClass.getAnnotation(Command.class); - - if (cmd != null) - { - this.name = cmd.name(); - this.group = cmd.group(); - this.usage = cmd.usage(); - } - - if (Util.isEmpty(name)) - { - name = commandClass.getSimpleName(); - } - } - - /** - * Constructs ... - * - * - * @param name - * @param usage - * @param commandClass - */ - public CommandDescriptor(String name, String usage, - Class commandClass) - { - this.name = name; - this.usage = usage; - this.commandClass = commandClass; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param desc - * - * @return - */ - @Override - public int compareTo(CommandDescriptor desc) - { - int result = group.compareTo(desc.group); - - if (result == 0) - { - result = name.compareTo(desc.name); - } - - return result; - } - - /** - * Method description - * - * - * @return - */ - public SubCommand createSubCommand() - { - SubCommand command = null; - - try - { - command = commandClass.newInstance(); - command.setCommandName(name); - } - catch (Exception ex) - { - logger.error("could not create SubCommand {}", commandClass.getName()); - } - - return command; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public Class getCommandClass() - { - return commandClass; - } - - /** - * Method description - * - * - * @return - */ - public String getGroup() - { - return group; - } - - /** - * Method description - * - * - * @return - */ - public String getName() - { - return name; - } - - /** - * Method description - * - * - * @return - */ - public String getUsage() - { - return usage; - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private Class commandClass; - - /** Field description */ - private String group = "misc"; - - /** Field description */ - private String name; - - /** Field description */ - private String usage = ""; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/CreateGroupSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/CreateGroupSubCommand.java deleted file mode 100644 index a64a273253..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/CreateGroupSubCommand.java +++ /dev/null @@ -1,212 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.Option; - -import sonia.scm.cli.wrapper.GroupWrapper; -import sonia.scm.client.ScmClientSession; -import sonia.scm.group.Group; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "create-group", - usage = "usageCreateGroup", - group = "group" -) -public class CreateGroupSubCommand extends TemplateSubCommand -{ - - /** - * Method description - * - * - * @return - */ - public String getDescription() - { - return description; - } - - /** - * Method description - * - * - * @return - */ - public List getMembers() - { - return members; - } - - /** - * Method description - * - * - * @return - */ - public String getName() - { - return name; - } - - /** - * Method description - * - * - * @return - */ - public String getType() - { - return type; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param description - */ - public void setDescription(String description) - { - this.description = description; - } - - /** - * Method description - * - * - * @param members - */ - public void setMembers(List members) - { - this.members = members; - } - - /** - * Method description - * - * - * @param name - */ - public void setName(String name) - { - this.name = name; - } - - /** - * Method description - * - * - * @param type - */ - public void setType(String type) - { - this.type = type; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - Group group = new Group(); - - group.setName(name); - group.setDescription(description); - group.setType(type); - group.setMembers(members); - - ScmClientSession session = createSession(); - - session.getGroupHandler().create(group); - - Map env = new HashMap(); - - env.put("group", new GroupWrapper(group)); - renderTemplate(env, GetGroupSubCommand.TEMPLATE); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Option( - name = "--description", - usage = "optionGroupDescription", - aliases = { "-d" } - ) - private String description; - - /** Field description */ - @Option( - name = "--member", - usage = "optionGroupMember", - aliases = { "-m" } - ) - private List members; - - /** Field description */ - @Option( - name = "--name", - usage = "optionGroupName", - required = true, - aliases = { "-n" } - ) - private String name; - - /** Field description */ - @Option( - name = "--type", - usage = "optionGroupType", - aliases = { "-t" } - ) - private String type = "xml"; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/CreateRepositorySubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/CreateRepositorySubCommand.java deleted file mode 100644 index 52828eba25..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/CreateRepositorySubCommand.java +++ /dev/null @@ -1,220 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.Option; - -import sonia.scm.cli.wrapper.RepositoryWrapper; -import sonia.scm.client.ScmClientSession; -import sonia.scm.repository.Repository; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.HashMap; -import java.util.Map; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "create-repository", - usage = "usageCreateRepository", - group = "repository" -) -public class CreateRepositorySubCommand extends TemplateSubCommand -{ - - /** - * Method description - * - * - * @return - */ - public String getContact() - { - return contact; - } - - /** - * Method description - * - * - * @return - */ - public String getDescription() - { - return description; - } - - /** - * Method description - * - * - * @return - */ - public String getType() - { - return type; - } - - /** - * Method description - * - * - * @return - */ - public boolean isPublicReadable() - { - return publicReadable; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param contact - */ - public void setContact(String contact) - { - this.contact = contact; - } - - /** - * Method description - * - * - * @param description - */ - public void setDescription(String description) - { - this.description = description; - } - - /** - * Method description - * - * - * @param publicReadable - */ - public void setPublicReadable(boolean publicReadable) - { - this.publicReadable = publicReadable; - } - - /** - * Method description - * - * - * @param type - */ - public void setType(String type) - { - this.type = type; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - Repository repository = new Repository(); - - repository.setName(name); - repository.setType(type); - repository.setContact(contact); - repository.setDescription(description); - - ScmClientSession session = createSession(); - - session.getRepositoryHandler().create(repository); - - Map env = new HashMap(); - - env.put("repository", new RepositoryWrapper(config, repository)); - renderTemplate(env, GetRepositorySubCommand.TEMPLATE); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Option( - name = "--contact", - usage = "optionRepositoryContact", - aliases = { "-c" } - ) - private String contact; - - /** Field description */ - @Option( - name = "--description", - usage = "optionRepositoryDescription", - aliases = { "-d" } - ) - private String description; - - /** Field description */ - @Option( - name = "--name", - required = true, - usage = "optionRepositoryName", - aliases = { "-n" } - ) - private String name; - - /** Field description */ - @Option( - name = "--public", - usage = "optionRepositoryPublic", - aliases = { "-p" } - ) - private boolean publicReadable; - - /** Field description */ - @Option( - name = "--type", - required = true, - usage = "optionRepositoryType", - aliases = { "-t" } - ) - private String type; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/CreateUserSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/CreateUserSubCommand.java deleted file mode 100644 index c6a72d4ce8..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/CreateUserSubCommand.java +++ /dev/null @@ -1,274 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.Option; - -import sonia.scm.cli.wrapper.UserWrapper; -import sonia.scm.client.ScmClientSession; -import sonia.scm.user.User; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.HashMap; -import java.util.Map; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "create-user", - usage = "usageCreateUser", - group = "user" -) -public class CreateUserSubCommand extends TemplateSubCommand -{ - - /** - * Method description - * - * - * @return - */ - public String getDisplayName() - { - return displayName; - } - - /** - * Method description - * - * - * @return - */ - public String getMail() - { - return mail; - } - - /** - * Method description - * - * - * @return - */ - public String getName() - { - return name; - } - - /** - * Method description - * - * - * @return - */ - public String getPassword() - { - return password; - } - - /** - * Method description - * - * - * @return - */ - public String getType() - { - return type; - } - - /** - * Method description - * - * - * @return - */ - public boolean isAdmin() - { - return admin; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param admin - */ - public void setAdmin(boolean admin) - { - this.admin = admin; - } - - /** - * Method description - * - * - * @param displayName - */ - public void setDisplayName(String displayName) - { - this.displayName = displayName; - } - - /** - * Method description - * - * - * @param mail - */ - public void setMail(String mail) - { - this.mail = mail; - } - - /** - * Method description - * - * - * @param name - */ - public void setName(String name) - { - this.name = name; - } - - /** - * Method description - * - * - * @param password - */ - public void setPassword(String password) - { - this.password = password; - } - - /** - * Method description - * - * - * @param type - */ - public void setType(String type) - { - this.type = type; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - User user = new User(); - - user.setName(name); - user.setAdmin(admin); - user.setDisplayName(displayName); - user.setPassword(password); - user.setMail(mail); - user.setType(type); - - ScmClientSession session = createSession(); - - session.getUserHandler().create(user); - - Map env = new HashMap(); - - env.put("user", new UserWrapper(user)); - renderTemplate(env, GetUserSubCommand.TEMPLATE); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Option( - name = "--admin", - usage = "optionUserAdmin", - aliases = { "-a" } - ) - private boolean admin = false; - - /** Field description */ - @Option( - name = "--display-name", - usage = "optionUserDisplayName", - required = true, - aliases = { "-d" } - ) - private String displayName; - - /** Field description */ - @Option( - name = "--mail", - usage = "optionUserMail", - aliases = { "-m" } - ) - private String mail; - - /** Field description */ - @Option( - name = "--name", - usage = "optionUserName", - required = true, - aliases = { "-n" } - ) - private String name; - - /** Field description */ - @Option( - name = "--password", - usage = "optionUserPassword", - aliases = { "-p" } - ) - private String password; - - /** Field description */ - @Option( - name = "--type", - usage = "optionUserType", - aliases = { "-t" } - ) - private String type = "xml"; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/DeleteConfigSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/DeleteConfigSubCommand.java deleted file mode 100644 index 93c2ad253e..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/DeleteConfigSubCommand.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.cli.config.ScmClientConfig; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "delete-config", - usage = "usageDeleteConfig", - group = "config" -) -public class DeleteConfigSubCommand extends SubCommand -{ - - /** - * Method description - * - */ - @Override - protected void run() - { - ScmClientConfig.getInstance().delete(); - } -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/DeleteGroupSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/DeleteGroupSubCommand.java deleted file mode 100644 index 345cf5baec..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/DeleteGroupSubCommand.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.Argument; - -import sonia.scm.client.ScmClientSession; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "delete-group", - usage = "usageDeleteGroup", - group = "group" -) -public class DeleteGroupSubCommand extends SubCommand -{ - - /** - * Method description - * - * - * @return - */ - public String getName() - { - return name; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param name - */ - public void setName(String name) - { - this.name = name; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - ScmClientSession session = createSession(); - - session.getGroupHandler().delete(name); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Argument( - usage = "optionGroupName", - metaVar = "groupname", - required = true - ) - private String name; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/DeleteMembersSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/DeleteMembersSubCommand.java deleted file mode 100644 index 449fab5181..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/DeleteMembersSubCommand.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.group.Group; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.List; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "delete-members", - usage = "usageDeleteMembers", - group = "group" -) -public class DeleteMembersSubCommand extends MembersSubCommand -{ - - /** - * Method description - * - * - * @param group - * @param members - */ - @Override - protected void modifyMembers(Group group, List members) - { - group.getMembers().removeAll(members); - } -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/DeletePermissionSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/DeletePermissionSubCommand.java deleted file mode 100644 index fe01b3ff24..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/DeletePermissionSubCommand.java +++ /dev/null @@ -1,117 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.Option; - -import sonia.scm.repository.Permission; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.Iterator; -import java.util.List; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "delete-permission", - usage = "usageDeletePermission", - group = "repository" -) -public class DeletePermissionSubCommand extends PermissionSubCommand -{ - - /** - * Method description - * - * - * @return - */ - public String getName() - { - return name; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param name - */ - public void setName(String name) - { - this.name = name; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param permissions - */ - @Override - protected void modifyPermissions(List permissions) - { - Iterator it = permissions.iterator(); - - while (it.hasNext()) - { - Permission p = it.next(); - - if (name.equals(p.getName())) - { - it.remove(); - } - } - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Option( - name = "--name", - usage = "optionPermissionName", - required = true, - aliases = { "-n" } - ) - private String name; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/DeleteRepositorySubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/DeleteRepositorySubCommand.java deleted file mode 100644 index 742eb72f80..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/DeleteRepositorySubCommand.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.Argument; - -import sonia.scm.client.ScmClientSession; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "delete-repository", - usage = "usageDeleteRepository", - group = "repository" -) -public class DeleteRepositorySubCommand extends SubCommand -{ - - /** - * Method description - * - * - * @return - */ - public String getId() - { - return id; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param id - */ - public void setId(String id) - { - this.id = id; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - ScmClientSession session = createSession(); - - session.getRepositoryHandler().delete(id); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Argument( - usage = "optionRepositoryId", - metaVar = "repositoryid", - required = true - ) - private String id; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/DeleteUserSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/DeleteUserSubCommand.java deleted file mode 100644 index c254a2e7e3..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/DeleteUserSubCommand.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.Argument; - -import sonia.scm.client.ScmClientSession; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "delete-user", - usage = "usageDeleteUser", - group = "user" -) -public class DeleteUserSubCommand extends SubCommand -{ - - /** - * Method description - * - * - * @return - */ - public String getName() - { - return name; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param name - */ - public void setName(String name) - { - this.name = name; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - ScmClientSession session = createSession(); - - session.getUserHandler().delete(name); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Argument( - usage = "optionUserName", - metaVar = "username", - required = true - ) - private String name; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/EncryptSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/EncryptSubCommand.java deleted file mode 100644 index af76698062..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/EncryptSubCommand.java +++ /dev/null @@ -1,98 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of SCM-Manager; - * 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.Argument; - -/** - * - * @author Sebastian Sdorra - * @since 1.41 - */ -@Command( - name = "encrypt", - usage = "usageEncrypt", - group = "security" -) -public class EncryptSubCommand extends SubCommand -{ - - /** - * Method description - * - * - * @return - */ - public String getValue() - { - return value; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param value - */ - public void setValue(String value) - { - this.value = value; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - String enc = createSession().getSecurityHandler().encrypt(value); - - output.println(enc); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Argument( - usage = "optionEncryptValue", - metaVar = "value", - required = true - ) - private String value; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/GenerateKeySubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/GenerateKeySubCommand.java deleted file mode 100644 index b8658391b0..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/GenerateKeySubCommand.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of SCM-Manager; - * 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "generate-key", - usage = "usageGenerateKey", - group = "security" -) -public class GenerateKeySubCommand extends SubCommand -{ - - /** - * Method description - * - */ - @Override - protected void run() - { - output.println(createSession().getSecurityHandler().generateKey()); - } -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/GetGroupSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/GetGroupSubCommand.java deleted file mode 100644 index 5d823217e1..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/GetGroupSubCommand.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.Argument; - -import sonia.scm.cli.I18n; -import sonia.scm.cli.wrapper.GroupWrapper; -import sonia.scm.client.ScmClientSession; -import sonia.scm.group.Group; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.HashMap; -import java.util.Map; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "get-group", - usage = "usageGetGroup", - group = "group" -) -public class GetGroupSubCommand extends TemplateSubCommand -{ - - /** Field description */ - public static final String TEMPLATE = "/sonia/resources/get-group.ftl"; - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public String getName() - { - return name; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param name - */ - public void setName(String name) - { - this.name = name; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - ScmClientSession session = createSession(); - Group group = session.getGroupHandler().get(name); - - if (group != null) - { - Map env = new HashMap(); - - env.put("group", new GroupWrapper(group)); - renderTemplate(env, TEMPLATE); - } - else - { - output.println(i18n.getMessage(I18n.GROUP_NOT_FOUND)); - } - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Argument( - usage = "optionGroupName", - metaVar = "groupname", - required = true - ) - private String name; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/GetRepositorySubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/GetRepositorySubCommand.java deleted file mode 100644 index 2e8227fa60..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/GetRepositorySubCommand.java +++ /dev/null @@ -1,140 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.Argument; - -import sonia.scm.cli.I18n; -import sonia.scm.cli.wrapper.RepositoryWrapper; -import sonia.scm.client.ScmClientSession; -import sonia.scm.repository.Repository; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.HashMap; -import java.util.Map; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "get-repository", - usage = "usageGetRepository", - group = "repository" -) -public class GetRepositorySubCommand extends TemplateSubCommand -{ - - /** Field description */ - public static final String TEMPLATE = "/sonia/resources/get-repository.ftl"; - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public String getId() - { - return id; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param id - */ - public void setId(String id) - { - this.id = id; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - ScmClientSession session = createSession(); - - Repository repository; - - int index = id.indexOf("/"); - - if (index > 0) - { - String type = id.substring(0, index); - String name = id.substring(index + 1); - - repository = session.getRepositoryHandler().get(type, name); - } - else - { - repository = session.getRepositoryHandler().get(id); - } - - if (repository != null) - { - Map env = new HashMap(); - - env.put("repository", new RepositoryWrapper(config, repository)); - renderTemplate(env, TEMPLATE); - } - else - { - output.println(i18n.getMessage(I18n.REPOSITORY_NOT_FOUND)); - } - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Argument( - usage = "optionRepositoryIdOrTypeAndName", - metaVar = "repositoryid", - required = true - ) - private String id; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/GetUserSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/GetUserSubCommand.java deleted file mode 100644 index 60d70349cb..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/GetUserSubCommand.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.Argument; - -import sonia.scm.cli.I18n; -import sonia.scm.cli.wrapper.UserWrapper; -import sonia.scm.client.ScmClientSession; -import sonia.scm.user.User; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.HashMap; -import java.util.Map; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "get-user", - usage = "usageGetUser", - group = "user" -) -public class GetUserSubCommand extends TemplateSubCommand -{ - - /** Field description */ - public static final String TEMPLATE = "/sonia/resources/get-user.ftl"; - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public String getName() - { - return name; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param name - */ - public void setName(String name) - { - this.name = name; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - ScmClientSession session = createSession(); - User user = session.getUserHandler().get(name); - - if (user != null) - { - Map env = new HashMap(); - - env.put("user", new UserWrapper(user)); - renderTemplate(env, TEMPLATE); - } - else - { - output.println(i18n.getMessage(I18n.USER_NOT_FOUND)); - } - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Argument( - usage = "optionUserName", - metaVar = "username", - required = true - ) - private String name; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ImportBundleSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ImportBundleSubCommand.java deleted file mode 100644 index d746df0828..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ImportBundleSubCommand.java +++ /dev/null @@ -1,186 +0,0 @@ -/** -* Copyright (c) 2014, Sebastian Sdorra All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* -* 1. Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of SCM-Manager; -* 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 REGENTS 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. -* -* http://bitbucket.org/sdorra/scm-manager -* -*/ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import com.google.common.io.Files; - -import org.kohsuke.args4j.Option; - -import sonia.scm.ConfigurationException; -import sonia.scm.client.ImportBundleRequest; -import sonia.scm.client.ScmClientSession; -import sonia.scm.repository.Repository; - -//~--- JDK imports ------------------------------------------------------------ - -import java.io.File; - -/** - * - * @author Sebastian Sdorra - * @since 1.43 - */ -@Command( - name = "import-from-bundle", - usage = "usageImportBundle", - group = "repository" -) -public class ImportBundleSubCommand extends ImportSubCommand -{ - - /** - * Method description - * - * - * @return - */ - public File getBundle() - { - return bundle; - } - - /** - * Method description - * - * - * @return - */ - public String getName() - { - return name; - } - - /** - * Method description - * - * - * @return - */ - public boolean isCompressed() - { - return compressed; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param bundle - */ - public void setBundle(File bundle) - { - this.bundle = bundle; - } - - /** - * Method description - * - * - * @param compressed - */ - public void setCompressed(boolean compressed) - { - this.compressed = compressed; - } - - /** - * Method description - * - * - * @param name - */ - public void setName(String name) - { - this.name = name; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - if (!bundle.exists()) - { - throw new ConfigurationException("could not find bundle"); - } - else - { - ScmClientSession session = createSession(); - - ImportBundleRequest req = new ImportBundleRequest(getType(), name, - Files.asByteSource(bundle)); - - req.setCompressed(compressed); - - Repository repository = - session.getRepositoryHandler().importFromBundle(req); - - printImportedRepository(repository); - } - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Option( - name = "--bundle", - required = true, - usage = "optionRepositoryBundle", - aliases = { "-b" } - ) - private File bundle; - - /** Field description */ - @Option( - name = "--compressed", - usage = "optionRepositoryBundleCompressed", - aliases = { "-c" } - ) - private boolean compressed = false; - - /** Field description */ - @Option( - name = "--name", - required = true, - usage = "optionRepositoryName", - aliases = { "-n" } - ) - private String name; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ImportDirectorySubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ImportDirectorySubCommand.java deleted file mode 100644 index 788eef4fae..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ImportDirectorySubCommand.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import com.google.common.collect.Maps; - -import sonia.scm.client.ImportResultWrapper; -import sonia.scm.client.ScmClientSession; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.Map; - -/** - * - * @author Sebastian Sdorra - * @since 1.43 - */ -@Command( - name = "import-from-directory", - usage = "usageImportDirectory", - group = "repository" -) -public class ImportDirectorySubCommand extends ImportSubCommand -{ - - /** Field description */ - public static final String TEMPLATE = - "/sonia/resources/import-from-directory.ftl"; - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - ScmClientSession session = createSession(); - ImportResultWrapper wrapper = - session.getRepositoryHandler().importFromDirectory(getType()); - Map env = Maps.newHashMap(); - - env.put("importedDirectories", wrapper.getImportedDirectories()); - env.put("failedDirectories", wrapper.getFailedDirectories()); - renderTemplate(env, TEMPLATE); - } -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ImportSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ImportSubCommand.java deleted file mode 100644 index 7c8efe704d..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ImportSubCommand.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * Copyright (c) 2014, Sebastian Sdorra All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of SCM-Manager; - * 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import com.google.common.collect.Maps; - -import org.kohsuke.args4j.Argument; - -import sonia.scm.cli.wrapper.RepositoryWrapper; -import sonia.scm.repository.Repository; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.Map; - -/** - * - * @author Sebastian Sdorra - * @since 1.43 - */ -public abstract class ImportSubCommand extends TemplateSubCommand -{ - - /** - * Method description - * - * - * @return - */ - public String getType() - { - return type; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param type - */ - public void setType(String type) - { - this.type = type; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param repository - */ - protected void printImportedRepository(Repository repository) - { - Map env = Maps.newHashMap(); - - env.put("repository", new RepositoryWrapper(config, repository)); - renderTemplate(env, GetRepositorySubCommand.TEMPLATE); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Argument( - usage = "optionRepositoryType", - metaVar = "repositorytype", - required = true - ) - private String type; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ImportUrlSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ImportUrlSubCommand.java deleted file mode 100644 index 912a9a5fbc..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ImportUrlSubCommand.java +++ /dev/null @@ -1,146 +0,0 @@ -/** - * Copyright (c) 2014, Sebastian Sdorra All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of SCM-Manager; - * 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import com.google.common.collect.Maps; - -import org.kohsuke.args4j.Option; - -import sonia.scm.client.ImportUrlRequest; -import sonia.scm.client.ScmClientSession; -import sonia.scm.repository.Repository; - -//~--- JDK imports ------------------------------------------------------------ - -import java.net.URL; - -import java.util.Map; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "import-from-url", - usage = "usageImportUrl", - group = "repository" -) -public class ImportUrlSubCommand extends ImportSubCommand -{ - - /** - * Method description - * - * - * @return - */ - public String getName() - { - return name; - } - - /** - * Method description - * - * - * @return - */ - public URL getUrl() - { - return url; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param name - */ - public void setName(String name) - { - this.name = name; - } - - /** - * Method description - * - * - * @param url - */ - public void setUrl(URL url) - { - this.url = url; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - ScmClientSession session = createSession(); - - ImportUrlRequest request = new ImportUrlRequest(getType(), name, - url.toExternalForm()); - Repository repository = - session.getRepositoryHandler().importFromUrl(request); - - printImportedRepository(repository); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Option( - name = "--name", - required = true, - usage = "optionRepositoryName", - aliases = { "-n" } - ) - private String name; - - /** Field description */ - @Option( - name = "--url", - required = true, - usage = "optionRemoteRepositoryUrl", - aliases = { "-r" } - ) - private URL url; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ListGroupsSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ListGroupsSubCommand.java deleted file mode 100644 index 968e574ca6..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ListGroupsSubCommand.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.cli.wrapper.WrapperUtil; -import sonia.scm.client.ScmClientSession; -import sonia.scm.group.Group; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "list-groups", - usage = "usageListGroups", - group = "group" -) -public class ListGroupsSubCommand extends TemplateSubCommand -{ - - /** Field description */ - public static final String TEMPLATE = "/sonia/resources/list-groups.ftl"; - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - ScmClientSession session = createSession(); - List groups = session.getGroupHandler().getAll(); - Map env = new HashMap(); - - env.put("groups", WrapperUtil.wrapGroups(groups)); - renderTemplate(env, TEMPLATE); - } -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ListRepositoriesSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ListRepositoriesSubCommand.java deleted file mode 100644 index 2235781791..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ListRepositoriesSubCommand.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.cli.wrapper.WrapperUtil; -import sonia.scm.client.ScmClientSession; -import sonia.scm.repository.Repository; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "list-repositories", - usage = "usageListRepositories", - group = "repository" -) -public class ListRepositoriesSubCommand extends TemplateSubCommand -{ - - /** Field description */ - public static final String TEMPLATE = - "/sonia/resources/list-repositories.ftl"; - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - ScmClientSession session = createSession(); - List repositories = session.getRepositoryHandler().getAll(); - Map env = new HashMap(); - - env.put("repositories", WrapperUtil.wrapRepositories(config, repositories)); - renderTemplate(env, TEMPLATE); - } -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ListUsersSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ListUsersSubCommand.java deleted file mode 100644 index 58da1fc2f3..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ListUsersSubCommand.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.cli.wrapper.WrapperUtil; -import sonia.scm.client.ScmClientSession; -import sonia.scm.user.User; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "list-users", - usage = "usageListUsers", - group = "user" -) -public class ListUsersSubCommand extends TemplateSubCommand -{ - - /** Field description */ - public static final String TEMPLATE = "/sonia/resources/list-users.ftl"; - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - ScmClientSession session = createSession(); - List users = session.getUserHandler().getAll(); - Map env = new HashMap(); - - env.put("users", WrapperUtil.wrapUsers(users)); - renderTemplate(env, TEMPLATE); - } -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/MembersSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/MembersSubCommand.java deleted file mode 100644 index 279b0602ec..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/MembersSubCommand.java +++ /dev/null @@ -1,164 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.Argument; -import org.kohsuke.args4j.Option; - -import sonia.scm.cli.I18n; -import sonia.scm.cli.wrapper.GroupWrapper; -import sonia.scm.client.GroupClientHandler; -import sonia.scm.client.ScmClientSession; -import sonia.scm.group.Group; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * - * @author Sebastian Sdorra - */ -public abstract class MembersSubCommand extends TemplateSubCommand -{ - - /** - * Method description - * - * - * @param group - * @param members - */ - protected abstract void modifyMembers(Group group, List members); - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public List getMembers() - { - return members; - } - - /** - * Method description - * - * - * @return - */ - public String getName() - { - return name; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param members - */ - public void setMembers(List members) - { - this.members = members; - } - - /** - * Method description - * - * - * @param name - */ - public void setName(String name) - { - this.name = name; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - ScmClientSession session = createSession(); - GroupClientHandler handler = session.getGroupHandler(); - Group group = handler.get(name); - - if (group != null) - { - modifyMembers(group, members); - handler.modify(group); - - Map env = new HashMap(); - - env.put("group", new GroupWrapper(group)); - renderTemplate(env, GetGroupSubCommand.TEMPLATE); - } - else - { - output.println(i18n.getMessage(I18n.GROUP_NOT_FOUND)); - } - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Option( - name = "--member", - usage = "optionGroupMember", - required = true, - aliases = { "-m" } - ) - private List members; - - /** Field description */ - @Argument( - usage = "optionGroupName", - metaVar = "groupname", - required = true - ) - private String name; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ModifyGroupSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ModifyGroupSubCommand.java deleted file mode 100644 index 244f40f114..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ModifyGroupSubCommand.java +++ /dev/null @@ -1,139 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.Argument; -import org.kohsuke.args4j.Option; - -import sonia.scm.cli.I18n; -import sonia.scm.cli.wrapper.GroupWrapper; -import sonia.scm.client.GroupClientHandler; -import sonia.scm.client.ScmClientSession; -import sonia.scm.group.Group; -import sonia.scm.util.Util; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.HashMap; -import java.util.Map; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "modify-group", - usage = "usageModifyGroup", - group = "group" -) -public class ModifyGroupSubCommand extends TemplateSubCommand -{ - - /** - * Method description - * - * - * @return - */ - public String getDescription() - { - return description; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param description - */ - public void setDescription(String description) - { - this.description = description; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - ScmClientSession session = createSession(); - GroupClientHandler handler = session.getGroupHandler(); - Group group = handler.get(name); - - if (group != null) - { - if (Util.isNotEmpty(description)) - { - group.setDescription(description); - } - - handler.modify(group); - - Map env = new HashMap(); - - env.put("group", new GroupWrapper(group)); - renderTemplate(env, GetGroupSubCommand.TEMPLATE); - } - else - { - output.println(i18n.getMessage(I18n.GROUP_NOT_FOUND)); - } - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Option( - name = "--description", - usage = "optionGroupDescription", - aliases = { "-d" } - ) - private String description; - - /** Field description */ - @Argument( - usage = "optionGroupName", - metaVar = "groupname", - required = true - ) - private String name; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ModifyRepositorySubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ModifyRepositorySubCommand.java deleted file mode 100644 index 5ec4c59519..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ModifyRepositorySubCommand.java +++ /dev/null @@ -1,269 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.Argument; -import org.kohsuke.args4j.Option; - -import sonia.scm.cli.BooleanModifyOptionHandler; -import sonia.scm.cli.I18n; -import sonia.scm.cli.wrapper.RepositoryWrapper; -import sonia.scm.client.RepositoryClientHandler; -import sonia.scm.client.ScmClientSession; -import sonia.scm.repository.Repository; -import sonia.scm.util.Util; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.HashMap; -import java.util.Map; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "modify-repository", - usage = "usageModifyRepository", - group = "repository" -) -public class ModifyRepositorySubCommand extends TemplateSubCommand -{ - - /** - * Method description - * - * - * @return - */ - public Boolean getArchvied() - { - return archvied; - } - - /** - * Method description - * - * - * @return - */ - public String getContact() - { - return contact; - } - - /** - * Method description - * - * - * @return - */ - public String getDescription() - { - return description; - } - - /** - * Method description - * - * - * @return - */ - public String getId() - { - return id; - } - - /** - * Method description - * - * - * @return - */ - public Boolean getPublicReadable() - { - return publicReadable; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param archvied - */ - public void setArchvied(Boolean archvied) - { - this.archvied = archvied; - } - - /** - * Method description - * - * - * @param contact - */ - public void setContact(String contact) - { - this.contact = contact; - } - - /** - * Method description - * - * - * @param description - */ - public void setDescription(String description) - { - this.description = description; - } - - /** - * Method description - * - * - * @param id - */ - public void setId(String id) - { - this.id = id; - } - - /** - * Method description - * - * - * @param publicReadable - */ - public void setPublicReadable(Boolean publicReadable) - { - this.publicReadable = publicReadable; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - ScmClientSession session = createSession(); - RepositoryClientHandler handler = session.getRepositoryHandler(); - Repository repository = handler.get(id); - - if (repository != null) - { - if (Util.isNotEmpty(contact)) - { - repository.setContact(contact); - } - - if (Util.isNotEmpty(description)) - { - repository.setDescription(description); - } - - if (archvied != null) - { - repository.setArchived(archvied); - } - - if (publicReadable != null) - { - repository.setPublicReadable(publicReadable); - } - - handler.modify(repository); - - Map env = new HashMap(); - - env.put("repository", new RepositoryWrapper(config, repository)); - renderTemplate(env, GetRepositorySubCommand.TEMPLATE); - } - else - { - output.println(i18n.getMessage(I18n.REPOSITORY_NOT_FOUND)); - } - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Option( - name = "--archived", - usage = "optionRepositoryArchive", - aliases = { "-a" }, - handler = BooleanModifyOptionHandler.class - ) - private Boolean archvied; - - /** Field description */ - @Option( - name = "--contact", - usage = "optionRepositoryContact", - aliases = { "-c" } - ) - private String contact; - - /** Field description */ - @Option( - name = "--description", - usage = "optionRepositoryDescription", - aliases = { "-d" } - ) - private String description; - - /** Field description */ - @Argument( - usage = "optionRepositoryId", - metaVar = "repositoryid", - required = true - ) - private String id; - - /** Field description */ - @Option( - name = "--public", - usage = "optionRepositoryPublic", - aliases = { "-p" }, - handler = BooleanModifyOptionHandler.class - ) - private Boolean publicReadable; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ModifyUserSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ModifyUserSubCommand.java deleted file mode 100644 index 613b07d552..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ModifyUserSubCommand.java +++ /dev/null @@ -1,231 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.Argument; -import org.kohsuke.args4j.Option; - -import sonia.scm.cli.I18n; -import sonia.scm.cli.wrapper.UserWrapper; -import sonia.scm.client.ScmClientSession; -import sonia.scm.client.UserClientHandler; -import sonia.scm.user.User; -import sonia.scm.util.Util; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.HashMap; -import java.util.Map; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "modify-user", - usage = "usageModifyUser", - group = "user" -) -public class ModifyUserSubCommand extends TemplateSubCommand -{ - - /** - * Method description - * - * - * @return - */ - public String getDisplayName() - { - return displayName; - } - - /** - * Method description - * - * - * @return - */ - public String getMail() - { - return mail; - } - - /** - * Method description - * - * - * @return - */ - public String getName() - { - return name; - } - - /** - * Method description - * - * - * @return - */ - public String getPassword() - { - return password; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param displayName - */ - public void setDisplayName(String displayName) - { - this.displayName = displayName; - } - - /** - * Method description - * - * - * @param mail - */ - public void setMail(String mail) - { - this.mail = mail; - } - - /** - * Method description - * - * - * @param name - */ - public void setName(String name) - { - this.name = name; - } - - /** - * Method description - * - * - * @param password - */ - public void setPassword(String password) - { - this.password = password; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - ScmClientSession session = createSession(); - UserClientHandler handler = session.getUserHandler(); - User user = handler.get(name); - - if (user != null) - { - if (Util.isNotEmpty(displayName)) - { - user.setDisplayName(displayName); - } - - if (Util.isNotEmpty(mail)) - { - user.setMail(mail); - } - - if (Util.isNotEmpty(password)) - { - user.setPassword(password); - } - - handler.modify(user); - - Map env = new HashMap(); - - env.put("user", new UserWrapper(user)); - renderTemplate(env, GetUserSubCommand.TEMPLATE); - } - else - { - output.println(i18n.getMessage(I18n.USER_NOT_FOUND)); - } - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Option( - name = "--display-name", - usage = "optionUserDisplayName", - aliases = { "-d" } - ) - private String displayName; - - /** Field description */ - @Option( - name = "--mail", - usage = "optionUserMail", - aliases = { "-m" } - ) - private String mail; - - /** Field description */ - @Argument( - usage = "optionUserName", - metaVar = "username", - required = true - ) - private String name; - - /** Field description */ - @Option( - name = "--password", - usage = "optionUserPassword", - aliases = { "-p" } - ) - private String password; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/PermissionSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/PermissionSubCommand.java deleted file mode 100644 index a6b5eba2f5..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/PermissionSubCommand.java +++ /dev/null @@ -1,141 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.Argument; - -import sonia.scm.cli.I18n; -import sonia.scm.cli.wrapper.RepositoryWrapper; -import sonia.scm.client.RepositoryClientHandler; -import sonia.scm.client.ScmClientSession; -import sonia.scm.repository.Permission; -import sonia.scm.repository.Repository; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * - * @author Sebastian Sdorra - */ -public abstract class PermissionSubCommand extends TemplateSubCommand -{ - - /** - * Method description - * - * - * @param permissions - */ - protected abstract void modifyPermissions(List permissions); - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public String getId() - { - return id; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param id - */ - public void setId(String id) - { - this.id = id; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - ScmClientSession session = createSession(); - RepositoryClientHandler handler = session.getRepositoryHandler(); - Repository repository = handler.get(id); - - if (repository != null) - { - List permissions = repository.getPermissions(); - - if (permissions == null) - { - permissions = new ArrayList(); - } - - modifyPermissions(permissions); - repository.setPermissions(permissions); - handler.modify(repository); - - Map env = new HashMap(); - - env.put("repository", new RepositoryWrapper(config, repository)); - renderTemplate(env, GetRepositorySubCommand.TEMPLATE); - } - else - { - output.println(i18n.getMessage(I18n.REPOSITORY_NOT_FOUND)); - } - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Argument( - usage = "optionRepositoryId", - metaVar = "repositoryid", - required = true - ) - private String id; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ServerVersionSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ServerVersionSubCommand.java deleted file mode 100644 index e5c60f0779..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/ServerVersionSubCommand.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ -package sonia.scm.cli.cmd; - -import sonia.scm.ScmState; -import sonia.scm.client.ScmClientSession; -import sonia.scm.util.Util; - -/** - * - * @author Sebastian Sdorra - * @version 1.9 - */ -@Command( - name = "server-version", - usage = "usageServerVersion", - group = "misc" -) -public class ServerVersionSubCommand extends SubCommand -{ - - @Override - protected void run() - { - ScmClientSession session = createSession(); - ScmState state = session.getState(); - String version = null; - if ( state != null ){ - version = state.getVersion(); - - } - if ( Util.isEmpty(version) ){ - version = VersionSubCommand.DEFAULT_VERSION; - } - - output.append("scm-manager version: ").println( version ); - } - -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/StoreConfigSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/StoreConfigSubCommand.java deleted file mode 100644 index 3fcd06e479..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/StoreConfigSubCommand.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.cli.config.ScmClientConfig; - -/** - * - * @author Sebastian Sdorra - */ -@Command( - name = "store-config", - usage = "usageStoreConfig", - group = "config" -) -public class StoreConfigSubCommand extends SubCommand -{ - - /** - * Method description - * - */ - @Override - protected void run() - { - output.println("store config"); - ScmClientConfig.getInstance().store(); - } -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/SubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/SubCommand.java deleted file mode 100644 index 09dcf344ef..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/SubCommand.java +++ /dev/null @@ -1,235 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.CmdLineException; -import org.kohsuke.args4j.CmdLineParser; -import org.kohsuke.args4j.Option; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import sonia.scm.cli.I18n; -import sonia.scm.cli.config.ServerConfig; -import sonia.scm.client.ScmClient; -import sonia.scm.client.ScmClientSession; -import sonia.scm.util.IOUtil; -import sonia.scm.util.Util; - -//~--- JDK imports ------------------------------------------------------------ - -import java.io.BufferedReader; -import java.io.PrintWriter; - -import java.util.Collection; - -/** - * - * @author Sebastian Sdorra - */ -public abstract class SubCommand -{ - - /** the logger for SubCommand */ - private static final Logger logger = - LoggerFactory.getLogger(SubCommand.class); - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - protected abstract void run(); - - /** - * Method description - * - * - * @param input - * @param output - * @param i18n - * @param config - */ - public void init(BufferedReader input, PrintWriter output, I18n i18n, - ServerConfig config) - { - this.input = input; - this.output = output; - this.i18n = i18n; - this.config = config; - } - - /** - * Method description - * - * - * @param args - */ - public void run(Collection args) - { - CmdLineParser parser = new CmdLineParser(this); - - try - { - parser.parseArgument(args); - - if (help) - { - parser.printUsage(output, i18n.getBundle()); - System.exit(1); - } - else - { - try - { - run(); - } - finally - { - IOUtil.close(session); - } - } - } - catch (CmdLineException ex) - { - if (logger.isWarnEnabled()) - { - logger.warn("could not parse comannd line", ex); - } - - if (!help) - { - output.append(i18n.getMessage(I18n.ERROR)).append(": "); - output.println(ex.getMessage()); - output.println(); - } - - printHelp(parser); - } - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public String getCommandName() - { - return commandName; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param name - */ - public void setCommandName(String name) - { - this.commandName = name; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - protected ScmClientSession createSession() - { - if (Util.isNotEmpty(config.getUsername()) - && Util.isNotEmpty(config.getPassword())) - { - session = ScmClient.createSession(config.getServerUrl(), - config.getUsername(), - config.getPassword()); - } - else - { - session = ScmClient.createSession(config.getServerUrl()); - } - - return session; - } - - /** - * Method description - * - * - * @param parser - */ - protected void printHelp(CmdLineParser parser) - { - parser.printUsage(output, i18n.getBundle()); - System.exit(1); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - protected ServerConfig config; - - /** Field description */ - protected I18n i18n; - - /** Field description */ - protected BufferedReader input; - - /** Field description */ - protected PrintWriter output; - - /** Field description */ - private String commandName; - - /** Field description */ - @Option( - name = "--help", - usage = "optionHelpText", - aliases = { "-h" } - ) - private boolean help = false; - - /** Field description */ - private ScmClientSession session; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/SubCommandHandler.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/SubCommandHandler.java deleted file mode 100644 index 3f8e1f74fb..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/SubCommandHandler.java +++ /dev/null @@ -1,234 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import sonia.scm.ConfigurationException; -import sonia.scm.util.IOUtil; -import sonia.scm.util.Util; - -//~--- JDK imports ------------------------------------------------------------ - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -import java.net.URL; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * - * @author Sebastian Sdorra - */ -public class SubCommandHandler -{ - - /** Field description */ - public static final String RESOURCE_SERVICES = - "META-INF/services/".concat(SubCommand.class.getName()); - - /** Field description */ - private static volatile SubCommandHandler instance; - - /** the logger for SubCommandOptionHandler */ - private static final Logger logger = - LoggerFactory.getLogger(SubCommandOptionHandler.class); - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - */ - private SubCommandHandler() - { - subCommands = new HashMap(); - loadSubCommands(); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public static SubCommandHandler getInstance() - { - if (instance == null) - { - synchronized (SubCommandHandler.class) - { - if (instance == null) - { - instance = new SubCommandHandler(); - } - } - } - - return instance; - } - - /** - * Method description - * - * - * @param name - * - * @return - */ - public CommandDescriptor getDescriptor(String name) - { - return subCommands.get(name); - } - - /** - * Method description - * - * - * @return - */ - public List getDescriptors() - { - List descs = - new ArrayList(subCommands.values()); - - Collections.sort(descs); - - return descs; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param url - */ - private void loadSubCommand(URL url) - { - BufferedReader reader = null; - - try - { - reader = new BufferedReader(new InputStreamReader(url.openStream())); - - String line = reader.readLine(); - - while (line != null) - { - parseLine(line); - line = reader.readLine(); - } - } - catch (IOException ex) - { - logger.error("could not load commands"); - } - finally - { - IOUtil.close(reader); - } - } - - /** - * Method description - * - */ - private void loadSubCommands() - { - try - { - Enumeration enm = - SubCommandHandler.class.getClassLoader().getResources( - RESOURCE_SERVICES); - - while (enm.hasMoreElements()) - { - URL url = enm.nextElement(); - - loadSubCommand(url); - } - } - catch (IOException ex) - { - throw new ConfigurationException("could not load SubComamnds", ex); - } - } - - /** - * Method description - * - * - * @param line - */ - @SuppressWarnings("unchecked") - private void parseLine(String line) - { - line = line.trim(); - - if (Util.isNotEmpty(line) &&!line.startsWith("#")) - { - try - { - Class clazz = - (Class) Class.forName(line); - CommandDescriptor desc = new CommandDescriptor(clazz); - - subCommands.put(desc.getName(), desc); - } - catch (ClassNotFoundException ex) - { - logger.warn("could not found command class {}", line); - } - } - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private Map subCommands; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/SubCommandOptionHandler.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/SubCommandOptionHandler.java deleted file mode 100644 index dd219e557c..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/SubCommandOptionHandler.java +++ /dev/null @@ -1,118 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.CmdLineException; -import org.kohsuke.args4j.CmdLineParser; -import org.kohsuke.args4j.Localizable; -import org.kohsuke.args4j.OptionDef; -import org.kohsuke.args4j.spi.Messages; -import org.kohsuke.args4j.spi.OptionHandler; -import org.kohsuke.args4j.spi.Parameters; -import org.kohsuke.args4j.spi.Setter; - -import sonia.scm.cli.SimpleLocalizable; - -/** - * - * @author Sebastian Sdorra - */ -public class SubCommandOptionHandler extends OptionHandler -{ - - /** - * Constructs ... - * - * - * @param parser - * @param option - * @param setter - */ - public SubCommandOptionHandler(CmdLineParser parser, OptionDef option, - Setter setter) - { - super(parser, option, setter); - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * - * @param parameters - * - * @return - * - * @throws CmdLineException - */ - @Override - public int parseArguments(Parameters parameters) throws CmdLineException - { - String name = parameters.getParameter(0); - CommandDescriptor desc = - SubCommandHandler.getInstance().getDescriptor(name); - - if (desc != null) - { - owner.stopOptionParsing(); - setter.addValue(desc.createSubCommand()); - } - else - { - String msg = "command ".concat(name).concat(" not found"); - - throw new CmdLineException(owner, new SimpleLocalizable(msg)); - } - - return 1; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - @Override - public String getDefaultMetaVariable() - { - return "command"; - } -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/TemplateSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/TemplateSubCommand.java deleted file mode 100644 index b9d985b3b9..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/TemplateSubCommand.java +++ /dev/null @@ -1,165 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import freemarker.template.Configuration; -import freemarker.template.Template; -import freemarker.template.TemplateException; - -import org.kohsuke.args4j.Option; - -import sonia.scm.ConfigurationException; -import sonia.scm.util.IOUtil; -import sonia.scm.util.Util; - -//~--- JDK imports ------------------------------------------------------------ - -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; - -import java.util.Map; - -/** - * - * @author Sebastian Sdorra - */ -public abstract class TemplateSubCommand extends SubCommand -{ - - /** - * Method description - * - * - * @return - */ - public String getTemplate() - { - return template; - } - - /** - * Method description - * - * - * @return - */ - public File getTemplateFile() - { - return templateFile; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param template - */ - public void setTemplate(String template) - { - this.template = template; - } - - /** - * Method description - * - * - * @param templateFile - */ - public void setTemplateFile(File templateFile) - { - this.templateFile = templateFile; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param env - * @param defaultTemplate - */ - protected void renderTemplate(Map env, String defaultTemplate) - { - Configuration configuration = new Configuration(Configuration.VERSION_2_3_20); - Reader reader = null; - - try - { - if ((templateFile != null) && templateFile.exists()) - { - reader = new FileReader(templateFile); - } - else if (Util.isNotEmpty(template)) - { - reader = new StringReader(template); - } - else - { - reader = new InputStreamReader( - TemplateSubCommand.class.getResourceAsStream(defaultTemplate)); - } - - Template tpl = new Template("default-template", reader, configuration); - - tpl.process(env, output); - } - catch (TemplateException | IOException ex) - { - throw new ConfigurationException("could not render template", ex); - } - finally - { - IOUtil.close(reader); - } - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @Option(name = "--template", usage = "optionTemplate") - private String template; - - /** Field description */ - @Option(name = "--template-file", usage = "optionTemplateFile") - private File templateFile; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/VersionSubCommand.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/VersionSubCommand.java deleted file mode 100644 index 285739f2c2..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/cmd/VersionSubCommand.java +++ /dev/null @@ -1,133 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.cmd; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import sonia.scm.util.IOUtil; -import sonia.scm.util.Util; - -//~--- JDK imports ------------------------------------------------------------ - -import java.io.IOException; -import java.io.InputStream; - -import java.util.Properties; - -/** - * - * @author Sebastian Sdorra - * @since 1.9 - */ -@Command( - name = "version", - usage = "usageVersion", - group = "misc" -) -public class VersionSubCommand extends SubCommand -{ - - /** Default version {@link String} */ - public static final String DEFAULT_VERSION = "unknown"; - - /** Path to the maven properties file of the scm-core artifact */ - public static final String MAVEN_PROPERTIES = - "/META-INF/maven/sonia.scm.clients/scm-cli-client/pom.properties"; - - /** Maven property for the version of the artifact */ - public static final String MAVEN_PROPERTY_VERSION = "version"; - - /** the logger for VersionSubCommand */ - private static final Logger logger = - LoggerFactory.getLogger(VersionSubCommand.class); - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Override - protected void run() - { - String version = getVersion(); - - output.append("scm-cli-client version: ").println(version); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - private String getVersion() - { - String version = null; - InputStream stream = null; - - try - { - stream = VersionSubCommand.class.getResourceAsStream(MAVEN_PROPERTIES); - - if (stream != null) - { - Properties properties = new Properties(); - - properties.load(stream); - version = properties.getProperty(MAVEN_PROPERTY_VERSION); - } - } - catch (IOException ex) - { - logger.warn("could not parse maven.properties", ex); - } - finally - { - IOUtil.close(stream); - } - - if (Util.isEmpty(version)) - { - version = DEFAULT_VERSION; - } - - return version; - } -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/ConfigOptionHandler.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/ConfigOptionHandler.java deleted file mode 100644 index 15e030b8bc..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/ConfigOptionHandler.java +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.config; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.kohsuke.args4j.CmdLineException; -import org.kohsuke.args4j.CmdLineParser; -import org.kohsuke.args4j.OptionDef; -import org.kohsuke.args4j.spi.OptionHandler; -import org.kohsuke.args4j.spi.Parameters; -import org.kohsuke.args4j.spi.Setter; - -/** - * - * @author Sebastian Sdorra - */ -public class ConfigOptionHandler extends OptionHandler -{ - - /** - * Constructs ... - * - * - * @param parser - * @param option - * @param setter - */ - public ConfigOptionHandler(CmdLineParser parser, OptionDef option, - Setter setter) - { - super(parser, option, setter); - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param parameters - * - * @return - * - * @throws CmdLineException - */ - @Override - public int parseArguments(Parameters parameters) throws CmdLineException - { - String name = parameters.getParameter(0); - ServerConfig config = ScmClientConfig.getInstance().getConfig(name); - - setter.addValue(config); - - return 1; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - @Override - public String getDefaultMetaVariable() - { - return "metaVar_config"; - } -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/ScmClientConfig.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/ScmClientConfig.java deleted file mode 100644 index 9edb2b382a..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/ScmClientConfig.java +++ /dev/null @@ -1,196 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.config; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.HashMap; -import java.util.Map; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlTransient; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - -/** - * - * @author Sebastian Sdorra - */ -@XmlRootElement(name = "client-config") -@XmlAccessorType(XmlAccessType.FIELD) -public class ScmClientConfig -{ - - /** Field description */ - public static final String DEFAULT_NAME = "default"; - - /** Field description */ - private static volatile ScmClientConfig instance; - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - */ - private ScmClientConfig() - { - this.serverConfigMap = new HashMap(); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public static ScmClientConfig getInstance() - { - if (instance == null) - { - synchronized (ScmClientConfig.class) - { - if (instance == null) - { - instance = load(); - } - } - } - - return instance; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - private static ScmClientConfig load() - { - ScmClientConfigFileHandler fileHandler = new ScmClientConfigFileHandler(); - ScmClientConfig config = fileHandler.read(); - - if (config == null) - { - config = new ScmClientConfig(); - } - - config.setFileHandler(fileHandler); - - return config; - } - - /** - * Method description - * - */ - public void delete() - { - fileHandler.delete(); - } - - /** - * Method description - * - */ - public void store() - { - fileHandler.write(this); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param name - * - * @return - */ - public ServerConfig getConfig(String name) - { - ServerConfig config = serverConfigMap.get(name); - - if (config == null) - { - config = new ServerConfig(); - serverConfigMap.put(name, config); - } - - return config; - } - - /** - * Method description - * - * - * @return - */ - public ServerConfig getDefaultConfig() - { - return getConfig(DEFAULT_NAME); - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param fileHandler - */ - private void setFileHandler(ScmClientConfigFileHandler fileHandler) - { - this.fileHandler = fileHandler; - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @XmlTransient - private ScmClientConfigFileHandler fileHandler; - - /** Field description */ - @XmlElement(name = "server-config") - @XmlJavaTypeAdapter(XmlConfigAdapter.class) - private Map serverConfigMap; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/ScmClientConfigFileHandler.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/ScmClientConfigFileHandler.java deleted file mode 100644 index 5cc2c46978..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/ScmClientConfigFileHandler.java +++ /dev/null @@ -1,306 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.config; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.util.IOUtil; -import sonia.scm.util.Util; - -//~--- JDK imports ------------------------------------------------------------ - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.OutputStream; - -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.spec.InvalidKeySpecException; - -import java.util.UUID; -import java.util.prefs.Preferences; - -import javax.crypto.Cipher; -import javax.crypto.CipherInputStream; -import javax.crypto.CipherOutputStream; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.PBEKeySpec; -import javax.crypto.spec.PBEParameterSpec; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; - -/** - * - * @author Sebastian Sdorra - */ -public class ScmClientConfigFileHandler -{ - - /** Field description */ - public static final String DEFAULT_CONFIG_NAME = ".scm-cli-config.enc.xml"; - - /** Field description */ - public static final String ENV_CONFIG_FILE = "SCM_CLI_CONFIG"; - - /** Field description */ - public static final String PREF_SECRET_KEY = "scm.client.key"; - - /** Field description */ - public static final String SALT = "AE16347F"; - - /** Field description */ - public static final int SPEC_ITERATION = 12; - - /** Field description */ - private static final String CIPHER_NAME = "PBEWithMD5AndDES"; - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - */ - public ScmClientConfigFileHandler() - { - prefs = Preferences.userNodeForPackage(ScmClientConfigFileHandler.class); - key = prefs.get(PREF_SECRET_KEY, null); - - if (Util.isEmpty(key)) - { - key = createNewKey(); - prefs.put(PREF_SECRET_KEY, key); - } - - try - { - context = JAXBContext.newInstance(ScmClientConfig.class); - } - catch (JAXBException ex) - { - throw new ScmConfigException( - "could not create JAXBContext for ScmClientConfig", ex); - } - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - public void delete() - { - File configFile = getConfigFile(); - - if (configFile.exists() &&!configFile.delete()) - { - throw new ScmConfigException("could not delete config file"); - } - - prefs.remove(PREF_SECRET_KEY); - } - - /** - * Method description - * - * - * @return - */ - public ScmClientConfig read() - { - ScmClientConfig config = null; - File configFile = getConfigFile(); - - if (configFile.exists()) - { - InputStream input = null; - - try - { - Cipher c = createCipher(Cipher.DECRYPT_MODE); - - input = new CipherInputStream(new FileInputStream(configFile), c); - - Unmarshaller um = context.createUnmarshaller(); - - config = (ScmClientConfig) um.unmarshal(input); - } - catch (Exception ex) - { - throw new ScmConfigException("could not read config file", ex); - } - finally - { - IOUtil.close(input); - } - } - - return config; - } - - /** - * Method description - * - * - * @param config - */ - public void write(ScmClientConfig config) - { - File configFile = getConfigFile(); - OutputStream output = null; - - try - { - Cipher c = createCipher(Cipher.ENCRYPT_MODE); - - output = new CipherOutputStream(new FileOutputStream(configFile), c); - - Marshaller m = context.createMarshaller(); - - m.marshal(config, output); - } - catch (Exception ex) - { - throw new ScmConfigException("could not write config file", ex); - } - finally - { - IOUtil.close(output); - } - } - - /** - * Method description - * - * - * @param mode - * - * @return - * - * - * @throws InvalidAlgorithmParameterException - * @throws InvalidKeyException - * @throws InvalidKeySpecException - * @throws NoSuchAlgorithmException - * @throws NoSuchPaddingException - */ - private Cipher createCipher(int mode) - throws NoSuchAlgorithmException, NoSuchPaddingException, - InvalidKeySpecException, InvalidKeyException, - InvalidAlgorithmParameterException - { - SecretKey sk = createSecretKey(); - Cipher cipher = Cipher.getInstance(CIPHER_NAME); - PBEParameterSpec spec = new PBEParameterSpec(SALT.getBytes(), - SPEC_ITERATION); - - cipher.init(mode, sk, spec); - - return cipher; - } - - /** - * Method description - * - * - * @return - */ - private String createNewKey() - { - return UUID.randomUUID().toString(); - } - - /** - * Method description - * - * - * @return - * - * @throws InvalidKeySpecException - * @throws NoSuchAlgorithmException - */ - private SecretKey createSecretKey() - throws NoSuchAlgorithmException, InvalidKeySpecException - { - PBEKeySpec keySpec = new PBEKeySpec(key.toCharArray()); - SecretKeyFactory factory = SecretKeyFactory.getInstance(CIPHER_NAME); - - return factory.generateSecret(keySpec); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - private File getConfigFile() - { - File configFile = null; - String configPath = System.getenv(ENV_CONFIG_FILE); - - if (Util.isEmpty(configPath)) - { - configFile = new File(System.getProperty("user.home"), - DEFAULT_CONFIG_NAME); - } - else - { - configFile = new File(configPath); - } - - return configFile; - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private JAXBContext context; - - /** Field description */ - private String key; - - /** Field description */ - private Preferences prefs; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/ScmConfigException.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/ScmConfigException.java deleted file mode 100644 index 33fbef093e..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/ScmConfigException.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.config; - -/** - * - * @author Sebastian Sdorra - */ -public class ScmConfigException extends RuntimeException -{ - - /** Field description */ - private static final long serialVersionUID = -4226165375815233654L; - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - */ - public ScmConfigException() - { - super(); - } - - /** - * Constructs ... - * - * - * @param message - */ - public ScmConfigException(String message) - { - super(message); - } - - /** - * Constructs ... - * - * - * @param cause - */ - public ScmConfigException(Throwable cause) - { - super(cause); - } - - /** - * Constructs ... - * - * - * @param message - * @param cause - */ - public ScmConfigException(String message, Throwable cause) - { - super(message, cause); - } -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/ServerConfig.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/ServerConfig.java deleted file mode 100644 index c7fb4108c5..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/ServerConfig.java +++ /dev/null @@ -1,162 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.config; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.Validateable; - -/** - * - * @author Sebastian Sdorra - */ -public class ServerConfig implements Validateable -{ - - /** - * Constructs ... - * - */ - public ServerConfig() {} - - /** - * Constructs ... - * - * - * @param serverUrl - * @param username - * @param password - */ - public ServerConfig(String serverUrl, String username, String password) - { - this.serverUrl = serverUrl; - this.username = username; - this.password = password; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public String getPassword() - { - return password; - } - - /** - * Method description - * - * - * @return - */ - public String getServerUrl() - { - return serverUrl; - } - - /** - * Method description - * - * - * @return - */ - public String getUsername() - { - return username; - } - - /** - * Method description - * - * - * @return - */ - @Override - public boolean isValid() - { - - // TODO - return true; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param password - */ - public void setPassword(String password) - { - this.password = password; - } - - /** - * Method description - * - * - * @param serverUrl - */ - public void setServerUrl(String serverUrl) - { - this.serverUrl = serverUrl; - } - - /** - * Method description - * - * - * @param username - */ - public void setUsername(String username) - { - this.username = username; - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private String password; - - /** Field description */ - private String serverUrl; - - /** Field description */ - private String username; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/XmlConfigAdapter.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/XmlConfigAdapter.java deleted file mode 100644 index fcf109d879..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/XmlConfigAdapter.java +++ /dev/null @@ -1,98 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.config; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import javax.xml.bind.annotation.adapters.XmlAdapter; - -/** - * - * @author Sebastian Sdorra - */ -public class XmlConfigAdapter - extends XmlAdapter> -{ - - /** - * Method description - * - * - * @param map - * - * @return - * - * @throws Exception - */ - @Override - public XmlConfigSet marshal(Map map) throws Exception - { - Set set = new HashSet(); - - for (Map.Entry e : map.entrySet()) - { - set.add(new XmlConfigElement(e.getKey(), e.getValue())); - } - - return new XmlConfigSet(set); - } - - /** - * Method description - * - * - * @param set - * - * @return - * - * @throws Exception - */ - @Override - public Map unmarshal(XmlConfigSet set) throws Exception - { - Map map = new HashMap(); - - for (XmlConfigElement e : set) - { - map.put(e.getName(), e.getConfig()); - } - - return map; - } -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/XmlConfigElement.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/XmlConfigElement.java deleted file mode 100644 index f4e3eb2c04..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/XmlConfigElement.java +++ /dev/null @@ -1,127 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.config; - -//~--- JDK imports ------------------------------------------------------------ - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * - * @author Sebastian Sdorra - */ -@XmlRootElement(name = "server") -@XmlAccessorType(XmlAccessType.FIELD) -public class XmlConfigElement -{ - - /** - * Constructs ... - * - */ - public XmlConfigElement() {} - - /** - * Constructs ... - * - * - * @param name - * @param config - */ - public XmlConfigElement(String name, ServerConfig config) - { - this.name = name; - this.config = config; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public ServerConfig getConfig() - { - return config; - } - - /** - * Method description - * - * - * @return - */ - public String getName() - { - return name; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param config - */ - public void setConfig(ServerConfig config) - { - this.config = config; - } - - /** - * Method description - * - * - * @param name - */ - public void setName(String name) - { - this.name = name; - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @XmlElement(name = "server-config") - private ServerConfig config; - - /** Field description */ - private String name; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/XmlConfigSet.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/XmlConfigSet.java deleted file mode 100644 index 9bd3370775..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/config/XmlConfigSet.java +++ /dev/null @@ -1,117 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.config; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.Iterator; -import java.util.Set; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * - * @author Sebastian Sdorra - */ -@XmlRootElement(name = "server-config") -@XmlAccessorType(XmlAccessType.FIELD) -public class XmlConfigSet implements Iterable -{ - - /** - * Constructs ... - * - */ - public XmlConfigSet() {} - - /** - * Constructs ... - * - * - * @param configSet - */ - public XmlConfigSet(Set configSet) - { - this.configSet = configSet; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - @Override - public Iterator iterator() - { - return configSet.iterator(); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public Set getConfigSet() - { - return configSet; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param configSet - */ - public void setConfigSet(Set configSet) - { - this.configSet = configSet; - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @XmlElement(name = "server") - private Set configSet; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/wrapper/AbstractWrapper.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/wrapper/AbstractWrapper.java deleted file mode 100644 index 0e72aec28e..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/wrapper/AbstractWrapper.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.wrapper; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.Date; - -/** - * - * @author Sebastian Sdorra - */ -public class AbstractWrapper -{ - - /** - * Method description - * - * - * @param value - * - * @return - */ - protected Date getDate(Long value) - { - Date date = null; - - if (value != null) - { - date = new Date(value); - } - - return date; - } -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/wrapper/GroupWrapper.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/wrapper/GroupWrapper.java deleted file mode 100644 index d26225b5f7..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/wrapper/GroupWrapper.java +++ /dev/null @@ -1,146 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.wrapper; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.group.Group; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.Date; -import java.util.List; - -/** - * - * @author Sebastian Sdorra - */ -public class GroupWrapper extends AbstractWrapper -{ - - /** - * Constructs ... - * - * - * @param group - */ - public GroupWrapper(Group group) - { - this.group = group; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public Date getCreationDate() - { - return getDate(group.getCreationDate()); - } - - /** - * Method description - * - * - * @return - */ - public String getDescription() - { - return group.getDescription(); - } - - /** - * Method description - * - * - * @return - */ - public String getId() - { - return group.getId(); - } - - /** - * Method description - * - * - * @return - */ - public Date getLastModified() - { - return getDate(group.getLastModified()); - } - - /** - * Method description - * - * - * @return - */ - public List getMembers() - { - return group.getMembers(); - } - - /** - * Method description - * - * - * @return - */ - public String getName() - { - return group.getName(); - } - - /** - * Method description - * - * - * @return - */ - public String getType() - { - return group.getType(); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private Group group; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/wrapper/RepositoryWrapper.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/wrapper/RepositoryWrapper.java deleted file mode 100644 index 216afde624..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/wrapper/RepositoryWrapper.java +++ /dev/null @@ -1,210 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.wrapper; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.cli.config.ServerConfig; -import sonia.scm.repository.Permission; -import sonia.scm.repository.Repository; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.Date; -import java.util.List; - -/** - * - * @author Sebastian Sdorra - */ -public class RepositoryWrapper extends AbstractWrapper -{ - - /** - * Constructs ... - * - * - * @param config - * @param repository - */ - public RepositoryWrapper(ServerConfig config, Repository repository) - { - this(config.getServerUrl(), repository); - } - - /** - * Constructs ... - * - * - * - * @param baseUrl - * @param repository - */ - public RepositoryWrapper(String baseUrl, Repository repository) - { - this.baseUrl = baseUrl; - this.repository = repository; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public String getContact() - { - return repository.getContact(); - } - - /** - * Method description - * - * - * @return - */ - public Date getCreationDate() - { - return getDate(repository.getCreationDate()); - } - - /** - * Method description - * - * - * @return - */ - public String getDescription() - { - return repository.getDescription(); - } - - /** - * Method description - * - * - * @return - */ - public String getId() - { - return repository.getId(); - } - - /** - * Method description - * - * - * @return - */ - public Date getLastModified() - { - return getDate(repository.getLastModified()); - } - - /** - * Method description - * - * - * @return - */ - public String getName() - { - return repository.getName(); - } - - /** - * Method description - * - * - * @return - */ - public List getPermissions() - { - return repository.getPermissions(); - } - - /** - * Method description - * - * - * @return - */ - public String getType() - { - return repository.getType(); - } - - /** - * Method description - * - * - * @return - */ - public String getUrl() - { - return repository.createUrl(baseUrl); - } - - /** - * Method description - * - * - * @return - */ - public boolean isArchived() - { - return repository.isArchived(); - } - - /** - * Method description - * - * - * @return - */ - public boolean isPublicReadable() - { - return repository.isPublicReadable(); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private String baseUrl; - - /** Field description */ - private Repository repository; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/wrapper/UserWrapper.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/wrapper/UserWrapper.java deleted file mode 100644 index 55ccc6681c..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/wrapper/UserWrapper.java +++ /dev/null @@ -1,156 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.wrapper; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.user.User; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.Date; - -/** - * - * @author Sebastian Sdorra - */ -public class UserWrapper extends AbstractWrapper -{ - - /** - * Constructs ... - * - * - * @param user - */ - public UserWrapper(User user) - { - this.user = user; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public Date getCreationDate() - { - return getDate(user.getCreationDate()); - } - - /** - * Method description - * - * - * @return - */ - public String getDisplayName() - { - return user.getDisplayName(); - } - - /** - * Method description - * - * - * @return - */ - public String getId() - { - return user.getId(); - } - - /** - * Method description - * - * - * @return - */ - public Date getLastModified() - { - return getDate(user.getLastModified()); - } - - /** - * Method description - * - * - * @return - */ - public String getMail() - { - return user.getMail(); - } - - /** - * Method description - * - * - * @return - */ - public String getName() - { - return user.getName(); - } - - /** - * Method description - * - * - * @return - */ - public String getType() - { - return user.getType(); - } - - /** - * Method description - * - * - * @return - */ - public boolean isAdmin() - { - return user.isAdmin(); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private User user; -} diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/wrapper/WrapperUtil.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/wrapper/WrapperUtil.java deleted file mode 100644 index 0c87424fe6..0000000000 --- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/wrapper/WrapperUtil.java +++ /dev/null @@ -1,127 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli.wrapper; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.cli.config.ServerConfig; -import sonia.scm.group.Group; -import sonia.scm.repository.Repository; -import sonia.scm.user.User; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * - * @author Sebastian Sdorra - */ -public final class WrapperUtil -{ - - /** - * Constructs ... - * - */ - private WrapperUtil() {} - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param groups - * - * @return - */ - public static List wrapGroups(Collection groups) - { - List wrappers = new ArrayList(); - - for (Group g : groups) - { - wrappers.add(new GroupWrapper(g)); - } - - return wrappers; - } - - /** - * Method description - * - * - * - * - * @param config - * @param repositories - * - * @return - */ - public static List wrapRepositories(ServerConfig config, - Collection repositories) - { - List wrappers = new ArrayList(); - - for (Repository r : repositories) - { - wrappers.add(new RepositoryWrapper(config.getServerUrl(), r)); - } - - return wrappers; - } - - /** - * Method description - * - * - * @param users - * - * @return - */ - public static List wrapUsers(Collection users) - { - List wrappers = new ArrayList(); - - for (User u : users) - { - wrappers.add(new UserWrapper(u)); - } - - return wrappers; - } -} diff --git a/scm-clients/scm-cli-client/src/main/resources/META-INF/services/sonia.scm.cli.cmd.SubCommand b/scm-clients/scm-cli-client/src/main/resources/META-INF/services/sonia.scm.cli.cmd.SubCommand deleted file mode 100644 index 91f2345948..0000000000 --- a/scm-clients/scm-cli-client/src/main/resources/META-INF/services/sonia.scm.cli.cmd.SubCommand +++ /dev/null @@ -1,72 +0,0 @@ -# Copyright (c) 2010, Sebastian Sdorra -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. 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. -# 3. Neither the name of SCM-Manager; 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 REGENTS 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. -# -# http://bitbucket.org/sdorra/scm-manager -# - -# config -sonia.scm.cli.cmd.StoreConfigSubCommand -sonia.scm.cli.cmd.DeleteConfigSubCommand - -# repository -sonia.scm.cli.cmd.CreateRepositorySubCommand -sonia.scm.cli.cmd.ModifyRepositorySubCommand -sonia.scm.cli.cmd.GetRepositorySubCommand -sonia.scm.cli.cmd.ListRepositoriesSubCommand -sonia.scm.cli.cmd.DeleteRepositorySubCommand -sonia.scm.cli.cmd.ImportDirectorySubCommand -sonia.scm.cli.cmd.ImportUrlSubCommand -sonia.scm.cli.cmd.ImportBundleSubCommand - -# permission -sonia.scm.cli.cmd.AddPermissionSubCommand -sonia.scm.cli.cmd.DeletePermissionSubCommand - -# user -sonia.scm.cli.cmd.ListUsersSubCommand -sonia.scm.cli.cmd.GetUserSubCommand -sonia.scm.cli.cmd.CreateUserSubCommand -sonia.scm.cli.cmd.DeleteUserSubCommand -sonia.scm.cli.cmd.ModifyUserSubCommand - -# group -sonia.scm.cli.cmd.ListGroupsSubCommand -sonia.scm.cli.cmd.GetGroupSubCommand -sonia.scm.cli.cmd.CreateGroupSubCommand -sonia.scm.cli.cmd.DeleteGroupSubCommand -sonia.scm.cli.cmd.ModifyGroupSubCommand - -# member -sonia.scm.cli.cmd.AddMembersSubCommand -sonia.scm.cli.cmd.DeleteMembersSubCommand - -# security -sonia.scm.cli.cmd.EncryptSubCommand -sonia.scm.cli.cmd.GenerateKeySubCommand - -# misc -sonia.scm.cli.cmd.VersionSubCommand -sonia.scm.cli.cmd.ServerVersionSubCommand diff --git a/scm-clients/scm-cli-client/src/main/resources/sonia/resources/get-group.ftl b/scm-clients/scm-cli-client/src/main/resources/sonia/resources/get-group.ftl deleted file mode 100644 index 6126b6d81f..0000000000 --- a/scm-clients/scm-cli-client/src/main/resources/sonia/resources/get-group.ftl +++ /dev/null @@ -1,11 +0,0 @@ -Name: ${group.name} -Type: ${group.type} -Description: ${group.description!""} -Creation-Date: <#if group.creationDate??>${group.creationDate?string("yyyy-MM-dd HH:mm:ss")} -Last-Modified: <#if group.lastModified??>${group.lastModified?string("yyyy-MM-dd HH:mm:ss")} -Members: -<#if group.members??> -<#list group.members as member> - ${member} - - diff --git a/scm-clients/scm-cli-client/src/main/resources/sonia/resources/get-repository.ftl b/scm-clients/scm-cli-client/src/main/resources/sonia/resources/get-repository.ftl deleted file mode 100644 index 7ac5d4c38f..0000000000 --- a/scm-clients/scm-cli-client/src/main/resources/sonia/resources/get-repository.ftl +++ /dev/null @@ -1,16 +0,0 @@ -ID: ${repository.id} -Name: ${repository.name} -Type: ${repository.type} -E-Mail: ${repository.contact!""} -Description: ${repository.description!""} -Public: ${repository.publicReadable?string} -Archived: ${repository.archived?string} -Creation-Date: <#if repository.creationDate??>${repository.creationDate?string("yyyy-MM-dd HH:mm:ss")} -Last-Modified: <#if repository.lastModified??>${repository.lastModified?string("yyyy-MM-dd HH:mm:ss")} -URL: ${repository.url} -Permissions: -<#if repository.permissions??> -<#list repository.permissions as permission> - ${permission.type} - ${permission.name} (Group: ${permission.groupPermission?string}) - - diff --git a/scm-clients/scm-cli-client/src/main/resources/sonia/resources/get-user.ftl b/scm-clients/scm-cli-client/src/main/resources/sonia/resources/get-user.ftl deleted file mode 100644 index 45f08e56d1..0000000000 --- a/scm-clients/scm-cli-client/src/main/resources/sonia/resources/get-user.ftl +++ /dev/null @@ -1,8 +0,0 @@ -Name: ${user.name} -Display Name: ${user.displayName} -Type: ${user.type} -E-Mail: ${user.mail!""} -Active: ${user.admin?string} -Administrator: ${user.admin?string} -Creation-Date: <#if user.creationDate??>${user.creationDate?string("yyyy-MM-dd HH:mm:ss")} -Last-Modified: <#if user.lastModified??>${user.lastModified?string("yyyy-MM-dd HH:mm:ss")} diff --git a/scm-clients/scm-cli-client/src/main/resources/sonia/resources/i18n.properties b/scm-clients/scm-cli-client/src/main/resources/sonia/resources/i18n.properties deleted file mode 100644 index 9d6afd3dda..0000000000 --- a/scm-clients/scm-cli-client/src/main/resources/sonia/resources/i18n.properties +++ /dev/null @@ -1,131 +0,0 @@ -# -# Copyright (c) 2010, Sebastian Sdorra -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. 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. -# 3. Neither the name of SCM-Manager; 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 REGENTS 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. -# -# http://bitbucket.org/sdorra/scm-manager -# -# - -VAL = value -FILE = file -error = Error - -subCommandsTitle = list of commands - -optionConfig = Configuration name -optionServerUrl = SCM-Manager URL -optionUsername = Username -optionPassword = Password -optionHelpText = Shows this help -optionLoggingLevel = Logging level (DEBUG, INFO, WARN, ERROR) -optionTemplate = Template -optionTemplateFile = Template file -optionRepositoryId = Repository Id -optionRepositoryIdOrTypeAndName = Repository Id or type/name -optionRepositoryName = Repository name -optionRepositoryType = Repository type -optionRepositoryContact = Repository contact -optionRepositoryDescription = Repository description -optionRepositoryPublic = Repository public readable -optionRepositoryArchive = Repository archived -optionRemoteRepositoryUrl = Remote repository url -optionRepositoryBundle = Import repository from a bundle file (e.g. svn dump) -optionRepositoryBundleCompressed = Indicates that the bundle is gzip compressed - -optionPermissionGroup = Group -optionPermissionName = Group or user name -optionPermissionType = Permission type (READ,WRITE or OWNER) - -optionUserName = Username -optionUserDisplayName = Display name -optionUserMail = E-Mail address -optionUserPassword = Password -optionUserType = Type -optionUserAdmin = Administrator - -optionGroupName = Name of the group -optionGroupDescription = Description -optionGroupType = Type -optionGroupMember = Member - -optionEncryptValue = value to encrypt - -repositoryNotFound = The repository is not available -userNotFound = The user could not be found -groupNotFoun = The group could not be found - -config = configname -arg = subcommand arguments -command = subcommand -permissiontype = value -groupname = groupname -repositoryid = repositoryid -username = username -repositorytype = type - -config = Configuration -misc = Miscellaneous -repository = Repository -group = Group -user = User -security = Security -level = Logging-Level -boolean = true or false -URL = url -bundle = file - -options = Options -usage = scm-cli-client [options] command [command options] - -# usages -usageAddMember = Add members to a existing group -usageAddPermission = Add permission to a existing repository -usageCreateGroup = Create a new group -usageCreateRepository = Create a new repository -usageCreateUser = Create a new user -usageDeleteConfig = Delete all stored configurations -usageDeleteGroup = Delete a group -usageDeleteMembers = Delete members of a group -usageDeletePermission = Delete a permission of a repository -usageDeleteRepository = Delete a repository -usageDeleteUser = Delete a user -usageGetGroup = Print a group -usageGetRepository = Print a repository -usageGetUser = Print a user -usageListGroups= Print a list of all groups -usageListUsers= Print a list of all users -usageListRepositories= Print a list of all repositories -usageModifyGroup = Modify a group -usageModifyUser = Modify a user -usageModifyRepository = Modify a repository -usageStoreConfig = Stores the current configuration -usageVersion = Show the version of scm-cli-client -usageServerVersion = Show the version of the scm-manager -usageImportDirectory = Import repositories from repository directory -usageImportUrl = Import repository from remote url - -usageEncrypt = Encrypts the given value -usageGenerateKey = Generates a unique key \ No newline at end of file diff --git a/scm-clients/scm-cli-client/src/main/resources/sonia/resources/import-from-directory.ftl b/scm-clients/scm-cli-client/src/main/resources/sonia/resources/import-from-directory.ftl deleted file mode 100644 index 33cf9e083e..0000000000 --- a/scm-clients/scm-cli-client/src/main/resources/sonia/resources/import-from-directory.ftl +++ /dev/null @@ -1,9 +0,0 @@ -Imported repositories: -<#list importedDirectories as imported> -- ${imported} - - -Repositories failed to import: -<#list failedDirectories as failed> -- ${failed} - \ No newline at end of file diff --git a/scm-clients/scm-cli-client/src/main/resources/sonia/resources/list-groups.ftl b/scm-clients/scm-cli-client/src/main/resources/sonia/resources/list-groups.ftl deleted file mode 100644 index b25340f8f1..0000000000 --- a/scm-clients/scm-cli-client/src/main/resources/sonia/resources/list-groups.ftl +++ /dev/null @@ -1,14 +0,0 @@ -<#list groups as group> -Name: ${group.name} -Type: ${group.type} -Description: ${group.description!""} -Creation-Date: <#if group.creationDate??>${group.creationDate?string("yyyy-MM-dd HH:mm:ss")} -Last-Modified: <#if group.lastModified??>${group.lastModified?string("yyyy-MM-dd HH:mm:ss")} -Members: -<#if group.members??> -<#list group.members as member> - ${member} - - - - \ No newline at end of file diff --git a/scm-clients/scm-cli-client/src/main/resources/sonia/resources/list-repositories.ftl b/scm-clients/scm-cli-client/src/main/resources/sonia/resources/list-repositories.ftl deleted file mode 100644 index c78c51b505..0000000000 --- a/scm-clients/scm-cli-client/src/main/resources/sonia/resources/list-repositories.ftl +++ /dev/null @@ -1,19 +0,0 @@ -<#list repositories as repository> -ID: ${repository.id} -Name: ${repository.name} -Type: ${repository.type} -E-Mail: ${repository.contact!""} -Description: ${repository.description!""} -Public: ${repository.publicReadable?string} -Archived: ${repository.archived?string} -Creation-Date: <#if repository.creationDate??>${repository.creationDate?string("yyyy-MM-dd HH:mm:ss")} -Last-Modified: <#if repository.lastModified??>${repository.lastModified?string("yyyy-MM-dd HH:mm:ss")} -URL: ${repository.url} -Permissions: -<#if repository.permissions??> -<#list repository.permissions as permission> - ${permission.type} - ${permission.name} (Group: ${permission.groupPermission?string}) - - - - diff --git a/scm-clients/scm-cli-client/src/main/resources/sonia/resources/list-users.ftl b/scm-clients/scm-cli-client/src/main/resources/sonia/resources/list-users.ftl deleted file mode 100644 index eab8106c3c..0000000000 --- a/scm-clients/scm-cli-client/src/main/resources/sonia/resources/list-users.ftl +++ /dev/null @@ -1,11 +0,0 @@ -<#list users as user> -Name: ${user.name} -Display Name: ${user.displayName} -Type: ${user.type} -E-Mail: ${user.mail!""} -Active: ${user.admin?string} -Administrator: ${user.admin?string} -Creation-Date: <#if user.creationDate??>${user.creationDate?string("yyyy-MM-dd HH:mm:ss")} -Last-Modified: <#if user.lastModified??>${user.lastModified?string("yyyy-MM-dd HH:mm:ss")} - - diff --git a/scm-clients/scm-cli-client/src/test/java/sonia/scm/cli/AbstractITCaseBase.java b/scm-clients/scm-cli-client/src/test/java/sonia/scm/cli/AbstractITCaseBase.java deleted file mode 100644 index 5184ea37ed..0000000000 --- a/scm-clients/scm-cli-client/src/test/java/sonia/scm/cli/AbstractITCaseBase.java +++ /dev/null @@ -1,129 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of SCM-Manager; - * 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli; - -//~--- non-JDK imports -------------------------------------------------------- - -import com.google.common.collect.Lists; -import com.google.common.io.Closeables; - -//~--- JDK imports ------------------------------------------------------------ - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import java.util.Arrays; -import java.util.List; - -/** - * - * @author Sebastian Sdorra - */ -public abstract class AbstractITCaseBase -{ - - /** - * Method description - * - * - * @param cmd - * - * @return - * - * @throws IOException - */ - protected String execute(String... cmd) throws IOException - { - String result = null; - ByteArrayInputStream inputStream = null; - ByteArrayOutputStream outputStream = null; - - try - { - inputStream = new ByteArrayInputStream(new byte[0]); - outputStream = new ByteArrayOutputStream(); - - App app = new App(inputStream, outputStream); - - app.run(cmd); - - outputStream.flush(); - result = outputStream.toString().trim(); - } - finally - { - Closeables.close(inputStream, true); - Closeables.close(outputStream, true); - } - - return result; - } - - /** - * Method description - * - * - * @param cmd - * - * @return - * - * @throws IOException - */ - protected String executeServer(String... cmd) throws IOException - { - List cmdList = Lists.newArrayList(); - - cmdList.add("--server"); - cmdList.add("http://localhost:8081/scm"); - cmdList.add("--user"); - cmdList.add("scmadmin"); - cmdList.add("--password"); - cmdList.add("scmadmin"); - cmdList.addAll(Arrays.asList(cmd)); - - return execute(cmdList.toArray(new String[cmdList.size()])); - } - - /** - * Method description - * - * - * @param values - * - * @return - */ - protected String prepareForTest(String values) - { - return values.replaceAll("\\n", ";").replaceAll("\\s+", ""); - } -} diff --git a/scm-clients/scm-cli-client/src/test/java/sonia/scm/cli/RepositoriesITCase.java b/scm-clients/scm-cli-client/src/test/java/sonia/scm/cli/RepositoriesITCase.java deleted file mode 100644 index d09e912157..0000000000 --- a/scm-clients/scm-cli-client/src/test/java/sonia/scm/cli/RepositoriesITCase.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of SCM-Manager; - * 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.junit.Test; - -import static org.hamcrest.Matchers.*; - -import static org.junit.Assert.*; - -//~--- JDK imports ------------------------------------------------------------ - -import java.io.IOException; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * - * @author Sebastian Sdorra - */ -public class RepositoriesITCase extends AbstractITCaseBase -{ - - /** - * Method description - * - * - * @throws IOException - */ - @Test - public void listRepositoriesTest() throws IOException - { - executeServer("create-repository", "--type", "git", "--name", "hobbo", - "--description", "Test Repo"); - - String repositories = prepareForTest(executeServer("list-repositories")); - - assertThat(repositories, containsString("Name:hobbo;")); - assertThat(repositories, containsString("Description:TestRepo;")); - assertThat(repositories, containsString("Type:git;")); - - Pattern pattern = Pattern.compile("ID:([^;]+);"); - Matcher matcher = pattern.matcher(repositories); - - if (!matcher.find()) - { - fail("could not extract id of repository"); - } - - String id = matcher.group(1); - - executeServer("delete-repository", id); - } -} diff --git a/scm-clients/scm-cli-client/src/test/java/sonia/scm/cli/ServerVersionITCase.java b/scm-clients/scm-cli-client/src/test/java/sonia/scm/cli/ServerVersionITCase.java deleted file mode 100644 index 7e424587fb..0000000000 --- a/scm-clients/scm-cli-client/src/test/java/sonia/scm/cli/ServerVersionITCase.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of SCM-Manager; - * 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assume.assumeTrue; - -//~--- JDK imports ------------------------------------------------------------ - -import java.io.IOException; - -/** - * - * @author Sebastian Sdorra - */ -public class ServerVersionITCase extends AbstractITCaseBase -{ - - /** - * Method description - * - * - * @throws IOException - */ - @Test - public void testServerVersion() throws IOException - { - String systemVersion = System.getProperty("scm.version"); - - assumeTrue("skip test, because system property scm.version is not set", - systemVersion != null); - - String version = executeServer("server-version"); - - assertEquals("scm-manager version: ".concat(systemVersion), version); - } -} diff --git a/scm-clients/scm-cli-client/src/test/java/sonia/scm/cli/UsersITCase.java b/scm-clients/scm-cli-client/src/test/java/sonia/scm/cli/UsersITCase.java deleted file mode 100644 index e5b29457a9..0000000000 --- a/scm-clients/scm-cli-client/src/test/java/sonia/scm/cli/UsersITCase.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of SCM-Manager; - * 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.junit.Test; - -import static org.hamcrest.Matchers.*; - -import static org.junit.Assert.*; - -//~--- JDK imports ------------------------------------------------------------ - -import java.io.IOException; - -/** - * - * @author Sebastian Sdorra - */ -public class UsersITCase extends AbstractITCaseBase -{ - - /** - * Method description - * - * - * @throws IOException - */ - @Test - public void listUsersTest() throws IOException - { - String users = prepareForTest(executeServer("list-users")); - - assertThat(users, containsString("Name:scmadmin;")); - assertThat(users, containsString("DisplayName:SCMAdministrator;")); - assertThat(users, containsString("Type:xml;")); - assertThat(users, containsString("E-Mail:scm-admin@scm-manager.org;")); - assertThat(users, containsString("Active:true;")); - assertThat(users, containsString("Administrator:true;")); - System.out.println(users); - } -} diff --git a/scm-clients/scm-cli-client/src/test/java/sonia/scm/cli/VersionITCase.java b/scm-clients/scm-cli-client/src/test/java/sonia/scm/cli/VersionITCase.java deleted file mode 100644 index 3d9563c34e..0000000000 --- a/scm-clients/scm-cli-client/src/test/java/sonia/scm/cli/VersionITCase.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of SCM-Manager; - * 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.cli; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.junit.Test; - -import static org.junit.Assert.*; - -//~--- JDK imports ------------------------------------------------------------ - -import java.io.IOException; - -/** - * - * @author Sebastian Sdorra - */ -public class VersionITCase extends AbstractITCaseBase -{ - - /** - * Method description - * - * - * @throws IOException - */ - @Test - public void testVersion() throws IOException - { - // maven properties are not available during it tests - String version = execute("version"); - - assertEquals("scm-cli-client version: unknown", version); - } -} diff --git a/scm-clients/scm-client-api/pom.xml b/scm-clients/scm-client-api/pom.xml deleted file mode 100644 index d2f8692ca7..0000000000 --- a/scm-clients/scm-client-api/pom.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - 4.0.0 - - - sonia.scm.clients - scm-clients - 2.0.0-SNAPSHOT - - - sonia.scm.clients - scm-client-api - jar - 2.0.0-SNAPSHOT - scm-client-api - - - - - - - javax.servlet - javax.servlet-api - ${servlet.version} - provided - - - - javax.transaction - jta - 1.1 - provided - - - - - diff --git a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ClientChangesetHandler.java b/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ClientChangesetHandler.java deleted file mode 100644 index 2207d2c6b9..0000000000 --- a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ClientChangesetHandler.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.repository.Changeset; -import sonia.scm.repository.ChangesetPagingResult; - -/** - * - * @author Sebastian Sdorra - * @since 1.8 - */ -public interface ClientChangesetHandler -{ - - /** - * Method description - * - * - * @param revision - * - * @return - * - * @since 1.12 - */ - public Changeset getChangeset(String revision); - - /** - * Method description - * - * - * @param start - * @param limit - * - * @return - */ - public ChangesetPagingResult getChangesets(int start, int limit); - - /** - * @param path - * @param revision - * @param start - * @param limit - * @return - */ - public ChangesetPagingResult getChangesets(String path, String revision, - int start, int limit); -} diff --git a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ClientHandler.java b/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ClientHandler.java deleted file mode 100644 index b178ab3680..0000000000 --- a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ClientHandler.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.List; - -/** - * - * @author Sebastian Sdorra - * - * @param - */ -public interface ClientHandler -{ - - /** - * Method description - * - * - * - * @param item - */ - public void create(T item); - - /** - * Method description - * - * - * @param id - */ - public void delete(String id); - - /** - * Method description - * - * - * - * @param item - */ - public void delete(T item); - - /** - * Method description - * - * - * - * @param item - */ - public void modify(T item); - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param id - * - * @return - */ - public T get(String id); - - /** - * Method description - * - * - * @return - */ - public List getAll(); -} diff --git a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ClientRepositoryBrowser.java b/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ClientRepositoryBrowser.java deleted file mode 100644 index 5c1f753e63..0000000000 --- a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ClientRepositoryBrowser.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.repository.BlameLine; - -//~--- JDK imports ------------------------------------------------------------ - -import java.io.IOException; -import java.io.InputStream; - -import java.util.List; - -/** - * - * @author Sebastian Sdorra - * @since 1.8 - */ -public interface ClientRepositoryBrowser -{ - - /** - * Method description - * - * - * @param revision - * @param path - * - * @return - */ - public List getBlameLines(String revision, String path); - - /** - * Method description - * - * - * @param revision - * @param path - * - * @return - * - * @throws IOException - */ - public InputStream getContent(String revision, String path) - throws IOException; - - /** - * Method description - * - * - * @param revision - * @param path - * - * @return - */ - public List getFiles(String revision, String path); - - /** - * Method description - * - * - * @param revision - * - * @return - */ - public List getFiles(String revision); -} diff --git a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/FileObjectWrapper.java b/scm-clients/scm-client-api/src/main/java/sonia/scm/client/FileObjectWrapper.java deleted file mode 100644 index ddbeef69a3..0000000000 --- a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/FileObjectWrapper.java +++ /dev/null @@ -1,193 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.repository.BlameLine; -import sonia.scm.repository.FileObject; - -//~--- JDK imports ------------------------------------------------------------ - -import java.io.IOException; -import java.io.InputStream; - -import java.util.List; - -/** - * - * @author Sebastian Sdorra - * @since 1.8 - */ -public class FileObjectWrapper -{ - - /** - * Constructs ... - * - * - * - * @param repositoryBrowser - * @param revision - * @param file - */ - public FileObjectWrapper(ClientRepositoryBrowser repositoryBrowser, - String revision, FileObject file) - { - this.repositoryBrowser = repositoryBrowser; - this.revision = revision; - this.file = file; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public List getBlameLines() - { - return repositoryBrowser.getBlameLines(revision, getPath()); - } - - /** - * Method description - * - * - * @return - */ - public List getChildren() - { - List children = null; - - if (isDirectory()) - { - children = repositoryBrowser.getFiles(revision, getPath()); - } - - return children; - } - - /** - * Method description - * - * - * @return - * - * @throws IOException - */ - public InputStream getContent() throws IOException - { - return repositoryBrowser.getContent(revision, getPath()); - } - - /** - * Method description - * - * - * @return - */ - public String getDescription() - { - return file.getDescription(); - } - - /** - * Method description - * - * - * @return - */ - public Long getLastModified() - { - return file.getLastModified(); - } - - /** - * Method description - * - * - * @return - */ - public long getLength() - { - return file.getLength(); - } - - /** - * Method description - * - * - * @return - */ - public String getName() - { - return file.getName(); - } - - /** - * Method description - * - * - * @return - */ - public String getPath() - { - return file.getPath(); - } - - /** - * Method description - * - * - * @return - */ - public boolean isDirectory() - { - return file.isDirectory(); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private FileObject file; - - /** Field description */ - private ClientRepositoryBrowser repositoryBrowser; - - /** Field description */ - private String revision; -} diff --git a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/GroupClientHandler.java b/scm-clients/scm-client-api/src/main/java/sonia/scm/client/GroupClientHandler.java deleted file mode 100644 index 93fe52cc8d..0000000000 --- a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/GroupClientHandler.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.group.Group; - -/** - * - * @author Sebastian Sdorra - */ -public interface GroupClientHandler extends ClientHandler {} diff --git a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ImportBundleRequest.java b/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ImportBundleRequest.java deleted file mode 100644 index c6c9e71016..0000000000 --- a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ImportBundleRequest.java +++ /dev/null @@ -1,139 +0,0 @@ -/** - * Copyright (c) 2014, Sebastian Sdorra All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of SCM-Manager; - * 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -//~--- non-JDK imports -------------------------------------------------------- - -import com.google.common.io.ByteSource; - -/** - * - * @author Sebastian Sdorra - * @since 1.43 - */ -public class ImportBundleRequest -{ - - /** - * Constructs ... - * - */ - ImportBundleRequest() {} - - /** - * Constructs ... - * - * - * @param type - * @param name - * @param bundle - */ - public ImportBundleRequest(String type, String name, ByteSource bundle) - { - this.type = type; - this.name = name; - this.bundle = bundle; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public ByteSource getBundle() - { - return bundle; - } - - /** - * Method description - * - * - * @return - */ - public String getName() - { - return name; - } - - /** - * Method description - * - * - * @return - */ - public String getType() - { - return type; - } - - /** - * Method description - * - * - * @return - */ - public boolean isCompressed() - { - return compressed; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param compressed - */ - public void setCompressed(boolean compressed) - { - this.compressed = compressed; - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private ByteSource bundle; - - /** Field description */ - private boolean compressed = false; - - /** Field description */ - private String name; - - /** Field description */ - private String type; -} diff --git a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ImportResultWrapper.java b/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ImportResultWrapper.java deleted file mode 100644 index 1417e3b888..0000000000 --- a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ImportResultWrapper.java +++ /dev/null @@ -1,184 +0,0 @@ -/** - * Copyright (c) 2014, Sebastian Sdorra All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of SCM-Manager; - * 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -//~--- non-JDK imports -------------------------------------------------------- - -import com.google.common.base.Function; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; - -import sonia.scm.repository.ImportResult; -import sonia.scm.repository.Repository; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.List; - -/** - * - * @author Sebastian Sdorra - * @since 1.43 - */ -public class ImportResultWrapper -{ - - /** - * Constructs ... - * - * - * @param client - * @param type - * @param result - */ - public ImportResultWrapper(RepositoryClientHandler client, String type, - ImportResult result) - { - this.client = client; - this.type = type; - this.result = result; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public List getFailedDirectories() - { - List directories = result.getFailedDirectories(); - - if (directories == null) - { - directories = ImmutableList.of(); - } - - return directories; - } - - /** - * Method description - * - * - * @return - */ - public List getImportedDirectories() - { - List directories = result.getImportedDirectories(); - - if (directories == null) - { - directories = ImmutableList.of(); - } - - return directories; - } - - /** - * Method description - * - * - * @return - */ - public Iterable getImportedRepositories() - { - return Iterables.transform(getImportedDirectories(), - new RepositoryResolver(client, type)); - } - - //~--- inner classes -------------------------------------------------------- - - /** - * Class description - * - * - * @version Enter version here..., 14/11/29 - * @author Enter your name here... - */ - private static class RepositoryResolver - implements Function - { - - /** - * Constructs ... - * - * - * @param clientHandler - * @param type - */ - public RepositoryResolver(RepositoryClientHandler clientHandler, - String type) - { - this.clientHandler = clientHandler; - this.type = type; - } - - //~--- methods ------------------------------------------------------------ - - /** - * Method description - * - * - * @param name - * - * @return - */ - @Override - public Repository apply(String name) - { - return clientHandler.get(type, type); - } - - //~--- fields ------------------------------------------------------------- - - /** Field description */ - private final RepositoryClientHandler clientHandler; - - /** Field description */ - private final String type; - } - - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private final RepositoryClientHandler client; - - /** Field description */ - private final ImportResult result; - - /** Field description */ - private final String type; -} diff --git a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ImportUrlRequest.java b/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ImportUrlRequest.java deleted file mode 100644 index 66969f4a86..0000000000 --- a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ImportUrlRequest.java +++ /dev/null @@ -1,118 +0,0 @@ -/** - * Copyright (c) 2014, Sebastian Sdorra All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of SCM-Manager; - * 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -//~--- JDK imports ------------------------------------------------------------ - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlTransient; - -/** - * - * @author Sebastian Sdorra - * @since 1.43 - */ -@XmlRootElement(name = "import") -@XmlAccessorType(XmlAccessType.FIELD) -public class ImportUrlRequest -{ - - /** - * Constructs ... - * - */ - ImportUrlRequest() {} - - /** - * Constructs ... - * - * - * @param type - * @param name - * @param url - */ - public ImportUrlRequest(String type, String name, String url) - { - this.type = type; - this.name = name; - this.url = url; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public String getName() - { - return name; - } - - /** - * Method description - * - * - * @return - */ - public String getType() - { - return type; - } - - /** - * Method description - * - * - * @return - */ - public String getUrl() - { - return url; - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private String name; - - /** Field description */ - @XmlTransient - private String type; - - /** Field description */ - private String url; -} diff --git a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/RepositoryClientHandler.java b/scm-clients/scm-client-api/src/main/java/sonia/scm/client/RepositoryClientHandler.java deleted file mode 100644 index 9c0060aaff..0000000000 --- a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/RepositoryClientHandler.java +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.NotSupportedFeatuerException; -import sonia.scm.Type; -import sonia.scm.repository.Repository; -import sonia.scm.repository.Tags; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.Collection; - -/** - * - * @author Sebastian Sdorra - */ -public interface RepositoryClientHandler extends ClientHandler -{ - - /** - * Method description - * - * - * @param type - * - * @return - * - * @since 1.43 - */ - public ImportResultWrapper importFromDirectory(String type); - - /** - * Method description - * - * - * @param request - * - * @return - * - * @since 1.43 - */ - public Repository importFromBundle(ImportBundleRequest request); - - /** - * Method description - * - * - * @param request - * @return - * - * @since 1.43 - */ - public Repository importFromUrl(ImportUrlRequest request); - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param type - * @param name - * - * @return - * @since 1.11 - */ - public Repository get(String type, String name); - - /** - * Method description - * - * - * @param repository - * - * @return - * @since 1.8 - * - * @throws NotSupportedFeatuerException - */ - public ClientChangesetHandler getChangesetHandler(Repository repository) - throws NotSupportedFeatuerException; - - /** - * Method description - * - * - * @param repository - * - * @return - * @since 1.8 - * - * @throws NotSupportedFeatuerException - */ - public ClientRepositoryBrowser getRepositoryBrowser(Repository repository) - throws NotSupportedFeatuerException; - - /** - * Method description - * - * - * @return - */ - public Collection getRepositoryTypes(); - - /** - * Returns all tags of the given repository. - * - * - * @param repository repository - * - * @return all tags of the given repository - * @since 1.18 - */ - public Tags getTags(Repository repository); -} diff --git a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ScmClient.java b/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ScmClient.java deleted file mode 100644 index c57e4992bb..0000000000 --- a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ScmClient.java +++ /dev/null @@ -1,135 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import sonia.scm.util.ServiceUtil; - -/** - * - * @author Sebastian Sdorra - */ -public final class ScmClient -{ - - /** Field description */ - private static volatile ScmClientProvider provider = null; - - /** the logger for ScmClient */ - private static final Logger logger = LoggerFactory.getLogger(ScmClient.class); - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - */ - private ScmClient() {} - - //~--- methods -------------------------------------------------------------- - - /** - * Creates an ScmClientSession for the given user - * - * - * @param url - * @param username - * @param password - * - * @return - * - * @throws ScmClientException - */ - public static ScmClientSession createSession(String url, String username, - String password) - throws ScmClientException - { - return getProvider().createSession(url, username, password); - } - - /** - * Creates an anonymous ScmClientSession - * - * - * @param url - * - * @return - * - * @throws ScmClientException - */ - public static ScmClientSession createSession(String url) - throws ScmClientException - { - return getProvider().createSession(url, null, null); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - * - */ - private static ScmClientProvider getProvider() - { - if (provider == null) - { - synchronized (ScmClientProvider.class) - { - if (provider == null) - { - provider = ServiceUtil.getService(ScmClientProvider.class); - } - } - } - - if (provider == null) - { - throw new ScmClientException("could not find a ScmClientProvider"); - } - else if (logger.isInfoEnabled()) - { - logger.info("create ScmClient with provider {}", - provider.getClass().getName()); - } - - return provider; - } -} diff --git a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ScmClientException.java b/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ScmClientException.java deleted file mode 100644 index 2a15a277f7..0000000000 --- a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ScmClientException.java +++ /dev/null @@ -1,174 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -/** - * - * @author Sebastian Sdorra - */ -public class ScmClientException extends RuntimeException -{ - - /** Field description */ - public static final int SC_FORBIDDEN = 403; - - /** Field description */ - public static final int SC_NOTFOUND = 404; - - /** Field description */ - public static final int SC_UNAUTHORIZED = 401; - - /** Field description */ - public static final int SC_UNKNOWN = -1; - - /** Field description */ - private static final long serialVersionUID = -2302107106896701393L; - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - * - * @param statusCode - */ - public ScmClientException(int statusCode) - { - this.statusCode = statusCode; - } - - /** - * Constructs ... - * - * - * @param message - */ - public ScmClientException(String message) - { - super(message); - } - - /** - * Constructs ... - * - * - * @param cause - */ - public ScmClientException(Throwable cause) - { - super(cause); - } - - /** - * Constructs ... - * - * - * - * @param statusCode - * @param message - */ - public ScmClientException(int statusCode, String message) - { - super(message); - this.statusCode = statusCode; - } - - /** - * Constructs ... - * - * - * @param message - * @param cause - */ - public ScmClientException(String message, Throwable cause) - { - super(message, cause); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public String getContent() - { - return content; - } - - /** - * Method description - * - * - * @return - */ - public int getStatusCode() - { - return statusCode; - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param content - */ - public void setContent(String content) - { - this.content = content; - } - - /** - * Method description - * - * - * @param statusCode - */ - public void setStatusCode(int statusCode) - { - this.statusCode = statusCode; - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private String content; - - /** Field description */ - private int statusCode = SC_UNKNOWN; -} diff --git a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ScmClientProvider.java b/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ScmClientProvider.java deleted file mode 100644 index 1a03696400..0000000000 --- a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ScmClientProvider.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -/** - * - * @author Sebastian Sdorra - */ -public interface ScmClientProvider -{ - - /** - * Method description - * - * - * @param url - * @param username - * @param password - * - * @return - * - */ - public ScmClientSession createSession(String url, String username, - String password); -} diff --git a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ScmClientSession.java b/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ScmClientSession.java deleted file mode 100644 index 7f58a94852..0000000000 --- a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ScmClientSession.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.ScmState; - -//~--- JDK imports ------------------------------------------------------------ - -import java.io.Closeable; - -/** - * - * @author Sebastian Sdorra - */ -public interface ScmClientSession extends Closeable -{ - - /** - * Method description - * - */ - @Override - public void close(); - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public GroupClientHandler getGroupHandler(); - - /** - * Method description - * - * - * @return - */ - public RepositoryClientHandler getRepositoryHandler(); - - /** - * Method description - * - * - * @return - */ - public SecurityClientHandler getSecurityHandler(); - - /** - * Method description - * - * - * @return - */ - public ScmState getState(); - - /** - * Method description - * - * - * @return - */ - public UserClientHandler getUserHandler(); -} diff --git a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ScmForbiddenException.java b/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ScmForbiddenException.java deleted file mode 100644 index d029d654a8..0000000000 --- a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ScmForbiddenException.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -/** - * - * @author Sebastian Sdorra - */ -public class ScmForbiddenException extends ScmClientException -{ - - /** Field description */ - private static final long serialVersionUID = 3937346624508458660L; - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - */ - public ScmForbiddenException() - { - super(SC_FORBIDDEN); - } - - /** - * Constructs ... - * - * - * @param message - */ - public ScmForbiddenException(String message) - { - super(SC_FORBIDDEN, message); - } -} diff --git a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ScmNotFoundException.java b/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ScmNotFoundException.java deleted file mode 100644 index ae0835e8cb..0000000000 --- a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ScmNotFoundException.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -/** - * - * @author Sebastian Sdorra - */ -public class ScmNotFoundException extends ScmClientException -{ - - /** Field description */ - private static final long serialVersionUID = -7015126639998723954L; - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - */ - public ScmNotFoundException() - { - super(SC_NOTFOUND); - } - - /** - * Constructs ... - * - * - * @param message - */ - public ScmNotFoundException(String message) - { - super(SC_NOTFOUND, message); - } -} diff --git a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ScmUnauthorizedException.java b/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ScmUnauthorizedException.java deleted file mode 100644 index fc561117e1..0000000000 --- a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/ScmUnauthorizedException.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -/** - * - * @author Sebastian Sdorra - */ -public class ScmUnauthorizedException extends ScmClientException -{ - - /** Field description */ - private static final long serialVersionUID = 4398907424134588809L; - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - */ - public ScmUnauthorizedException() - { - super(SC_UNAUTHORIZED); - } - - /** - * Constructs ... - * - * - * @param message - */ - public ScmUnauthorizedException(String message) - { - super(SC_UNAUTHORIZED, message); - } -} diff --git a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/SecurityClientHandler.java b/scm-clients/scm-client-api/src/main/java/sonia/scm/client/SecurityClientHandler.java deleted file mode 100644 index a0131a7f1c..0000000000 --- a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/SecurityClientHandler.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of SCM-Manager; - * 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -/** - * - * @author Sebastian Sdorra - * @since 1.41 - */ -public interface SecurityClientHandler -{ - - /** - * Method description - * - * - * @param value - * - * @return - */ - public String encrypt(String value); - - /** - * Method description - * - * - * @return - */ - public String generateKey(); -} diff --git a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/UserClientHandler.java b/scm-clients/scm-client-api/src/main/java/sonia/scm/client/UserClientHandler.java deleted file mode 100644 index 59192ba5a7..0000000000 --- a/scm-clients/scm-client-api/src/main/java/sonia/scm/client/UserClientHandler.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.user.User; - -/** - * - * @author Sebastian Sdorra - */ -public interface UserClientHandler extends ClientHandler {} diff --git a/scm-clients/scm-client-impl/pom.xml b/scm-clients/scm-client-impl/pom.xml deleted file mode 100644 index ecf2939706..0000000000 --- a/scm-clients/scm-client-impl/pom.xml +++ /dev/null @@ -1,227 +0,0 @@ - - - - 4.0.0 - - - sonia.scm.clients - scm-clients - 2.0.0-SNAPSHOT - - - sonia.scm.clients - scm-client-impl - jar - 2.0.0-SNAPSHOT - scm-client-impl - - - - - - - javax.servlet - javax.servlet-api - ${servlet.version} - provided - - - - javax.transaction - jta - 1.1 - provided - - - - sonia.scm.clients - scm-client-api - 2.0.0-SNAPSHOT - - - - com.sun.jersey - jersey-client - ${jersey-client.version} - - - - com.sun.jersey.contribs - jersey-multipart - ${jersey-client.version} - - - - - - org.slf4j - jul-to-slf4j - ${slf4j.version} - test - - - - ch.qos.logback - logback-classic - ${logback.version} - test - - - - sonia.scm - scm-test - 2.0.0-SNAPSHOT - test - - - - - - - - - - Sonatype - Sonatype Release - http://oss.sonatype.org/content/repositories/releases - - - - maven.scm-manager.org - scm-manager release repository - http://maven.scm-manager.org/nexus/content/groups/public - - - - - - - - - org.apache.maven.plugins - maven-assembly-plugin - 2.3 - - - jar-with-dependencies - - - - - package - - single - - - - - - - - - - - - it - - - - - - org.apache.maven.plugins - maven-dependency-plugin - 2.4 - - - package - - copy - - - - - sonia.scm - scm-webapp - ${project.version} - war - ${project.build.directory}/webapp - scm-webapp.war - - - - - - - - - org.apache.maven.plugins - maven-failsafe-plugin - 2.12 - - - integration-test - - integration-test - - - - verify - - verify - - - - - - - org.eclipse.jetty - jetty-maven-plugin - ${jetty.maven.version} - - 8085 - STOP - - - scm.home - target/scm-it - - - file.encoding - UTF-8 - - - - 8081 - - - /scm - - ${project.build.directory}/webapp/scm-webapp.war - 0 - true - - - - start-jetty - pre-integration-test - - deploy-war - - - - stop-jetty - post-integration-test - - stop - - - - - - - - - - - - diff --git a/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/AbstractClientHandler.java b/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/AbstractClientHandler.java deleted file mode 100644 index 0e29456adc..0000000000 --- a/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/AbstractClientHandler.java +++ /dev/null @@ -1,346 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import sonia.scm.ModelObject; -import sonia.scm.url.UrlProvider; -import sonia.scm.util.AssertUtil; - -//~--- JDK imports ------------------------------------------------------------ - -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.GenericType; -import com.sun.jersey.api.client.WebResource; - -import java.util.List; - -/** - * - * @author Sebastian Sdorra - * - * @param - */ -public abstract class AbstractClientHandler - implements ClientHandler -{ - - /** the logger for AbstractClientHandler */ - private static final Logger logger = - LoggerFactory.getLogger(AbstractClientHandler.class); - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - * - * @param session - * @param itemClass - */ - public AbstractClientHandler(JerseyClientSession session, Class itemClass) - { - this.session = session; - this.itemClass = itemClass; - this.client = session.getClient(); - this.urlProvider = session.getUrlProvider(); - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * - * @return - */ - protected abstract GenericType> createGenericListType(); - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param itemId - * - * @return - */ - protected abstract String getItemUrl(String itemId); - - /** - * Method description - * - * - * @return - */ - protected abstract String getItemsUrl(); - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param item - */ - @Override - public void create(T item) - { - AssertUtil.assertIsNotNull(item); - - WebResource resource = client.resource(getItemsUrl()); - ClientResponse response = null; - - try - { - response = resource.post(ClientResponse.class, item); - ClientUtil.checkResponse(response, 201); - - String url = response.getHeaders().get("Location").get(0); - - AssertUtil.assertIsNotEmpty(url); - - T newItem = getItemByUrl(url); - - AssertUtil.assertIsNotNull(newItem); - postCreate(response, item, newItem); - } - finally - { - ClientUtil.close(response); - } - } - - /** - * Method description - * - * - * @param id - */ - @Override - public void delete(String id) - { - AssertUtil.assertIsNotEmpty(id); - - WebResource resource = client.resource(getItemUrl(id)); - ClientResponse response = null; - - try - { - response = resource.delete(ClientResponse.class); - ClientUtil.checkResponse(response, 204); - } - finally - { - ClientUtil.close(response); - } - } - - /** - * Method description - * - * - * @param item - */ - @Override - public void delete(T item) - { - AssertUtil.assertIsNotNull(item); - delete(item.getId()); - } - - /** - * Method description - * - * - * @param item - */ - @Override - public void modify(T item) - { - AssertUtil.assertIsNotNull(item); - - String id = item.getId(); - - AssertUtil.assertIsNotEmpty(id); - - WebResource resource = client.resource(getItemUrl(id)); - ClientResponse response = null; - - try - { - response = resource.put(ClientResponse.class, item); - ClientUtil.checkResponse(response, 204); - postModify(response, item); - } - finally - { - ClientUtil.close(response); - } - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param id - * - * @return - */ - @Override - public T get(String id) - { - return getItemByUrl(getItemUrl(id)); - } - - /** - * Method description - * - * - * @return - */ - @Override - public List getAll() - { - List items = null; - String url = getItemsUrl(); - - if (logger.isDebugEnabled()) - { - logger.debug("fetch all items of {} from url", itemClass.getSimpleName(), - url); - } - - WebResource resource = client.resource(url); - ClientResponse response = null; - - try - { - response = resource.get(ClientResponse.class); - ClientUtil.checkResponse(response, 200); - items = response.getEntity(createGenericListType()); - } - finally - { - ClientUtil.close(response); - } - - return items; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param response - * @param item - * @param newItem - */ - protected void postCreate(ClientResponse response, T item, T newItem) {} - - /** - * Method description - * - * - * @param response - * @param item - */ - protected void postModify(ClientResponse response, T item) {} - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param url - * - * @return - */ - protected T getItemByUrl(String url) - { - if (logger.isDebugEnabled()) - { - logger.debug("fetch item {} from url {}", itemClass.getSimpleName(), url); - } - - T item = null; - WebResource resource = client.resource(url); - ClientResponse response = null; - - try - { - response = resource.get(ClientResponse.class); - - int sc = response.getStatus(); - - if (sc != ScmClientException.SC_NOTFOUND) - { - ClientUtil.checkResponse(response, 200); - item = response.getEntity(itemClass); - } - } - finally - { - ClientUtil.close(response); - } - - return item; - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - protected Client client; - - /** Field description */ - protected JerseyClientSession session; - - /** Field description */ - protected UrlProvider urlProvider; - - /** Field description */ - private Class itemClass; -} diff --git a/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/ClientUtil.java b/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/ClientUtil.java deleted file mode 100644 index e297405026..0000000000 --- a/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/ClientUtil.java +++ /dev/null @@ -1,238 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -//~--- JDK imports ------------------------------------------------------------ - -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.filter.LoggingFilter; - -/** - * - * @author Sebastian Sdorra - */ -public final class ClientUtil -{ - - /** the logger for ClientUtil */ - private static final Logger logger = - LoggerFactory.getLogger(ClientUtil.class); - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - */ - private ClientUtil() {} - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param exception - * @param response - */ - public static void appendContent(ScmClientException exception, - ClientResponse response) - { - try - { - exception.setContent(response.getEntity(String.class)); - } - catch (Exception ex) - { - logger.warn("could not read content", ex); - } - } - - /** - * Method description - * - * - * @param response - * @param expectedStatusCode - */ - public static void checkResponse(ClientResponse response, - int expectedStatusCode) - { - int sc = response.getStatus(); - - if (sc != expectedStatusCode) - { - if (logger.isWarnEnabled()) - { - logger.warn("response code {} expected, but {} returned", - expectedStatusCode, sc); - } - - sendException(response, sc); - } - } - - /** - * Method description - * - * - * @param response - * - */ - public static void checkResponse(ClientResponse response) - { - int sc = response.getStatus(); - - if (sc >= 300) - { - if (logger.isWarnEnabled()) - { - logger.warn("request failed, response code {} returned", sc); - } - - sendException(response, sc); - } - } - - /** - * Method description - * - * - * @param response - */ - public static void close(ClientResponse response) - { - if (response != null) - { - response.close(); - } - } - - /** - * Method description - * - * - * @param client - * @param url - * - * @return - */ - public static WebResource createResource(Client client, String url) - { - return createResource(client, url, false); - } - - /** - * Method description - * - * - * @param client - * @param url - * @param enableLogging - * - * @return - */ - public static WebResource createResource(Client client, String url, - boolean enableLogging) - { - WebResource resource = client.resource(url); - - if (enableLogging) - { - resource.addFilter(new LoggingFilter()); - } - - return resource; - } - - /** - * Method description - * - * - * @param response - * @param sc - */ - public static void sendException(ClientResponse response, int sc) - { - ScmClientException exception = null; - - switch (sc) - { - case ScmClientException.SC_UNAUTHORIZED : - exception = new ScmUnauthorizedException(); - - break; - - case ScmClientException.SC_FORBIDDEN : - exception = new ScmForbiddenException(); - - break; - - case ScmClientException.SC_NOTFOUND : - exception = new ScmNotFoundException(); - - break; - - default : - exception = new ScmClientException(sc); - appendContent(exception, response); - } - - throw exception; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param response - * - * @return - */ - public static boolean isSuccessfull(ClientResponse response) - { - int status = response.getStatus(); - - return (status > 200) && (status < 300); - } -} diff --git a/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseyClientChangesetHandler.java b/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseyClientChangesetHandler.java deleted file mode 100644 index 8cc8abb60a..0000000000 --- a/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseyClientChangesetHandler.java +++ /dev/null @@ -1,191 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.repository.Changeset; -import sonia.scm.repository.ChangesetPagingResult; -import sonia.scm.repository.Repository; - -//~--- JDK imports ------------------------------------------------------------ - -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; - -/** - * - * @author Sebastian Sdorra - */ -public class JerseyClientChangesetHandler implements ClientChangesetHandler -{ - - /** - * Constructs ... - * - * - * @param session - * @param repository - */ - public JerseyClientChangesetHandler(JerseyClientSession session, - Repository repository) - { - this.session = session; - this.repository = repository; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param revision - * - * @return - */ - @Override - public Changeset getChangeset(String revision) - { - Changeset changeset = null; - String url = - session.getUrlProvider().getRepositoryUrlProvider().getChangesetUrl( - repository.getId(), revision); - WebResource resource = session.getClient().resource(url); - ClientResponse response = null; - - try - { - response = resource.get(ClientResponse.class); - - if (response.getStatus() != ScmClientException.SC_NOTFOUND) - { - ClientUtil.checkResponse(response, 200); - changeset = response.getEntity(Changeset.class); - } - } - finally - { - ClientUtil.close(response); - } - - return changeset; - } - - /** - * Method description - * - * - * @param start - * @param limit - * - * @return - */ - @Override - public ChangesetPagingResult getChangesets(int start, int limit) - { - ChangesetPagingResult result = null; - String url = - session.getUrlProvider().getRepositoryUrlProvider().getChangesetUrl( - repository.getId(), start, limit); - WebResource resource = session.getClient().resource(url); - ClientResponse response = null; - - try - { - response = resource.get(ClientResponse.class); - - if (response.getStatus() != ScmClientException.SC_NOTFOUND) - { - ClientUtil.checkResponse(response, 200); - result = response.getEntity(ChangesetPagingResult.class); - } - } - finally - { - ClientUtil.close(response); - } - - return result; - } - - /** - * Method description - * - * - * - * @param path - * @param revision - * @param start - * @param limit - * - * @return - */ - @Override - public ChangesetPagingResult getChangesets(String path, String revision, - int start, int limit) - { - ChangesetPagingResult result = null; - String url = - session.getUrlProvider().getRepositoryUrlProvider().getChangesetUrl( - repository.getId(), path, revision, start, limit); - WebResource resource = session.getClient().resource(url); - ClientResponse response = null; - - try - { - response = resource.get(ClientResponse.class); - - if (response.getStatus() != ScmClientException.SC_NOTFOUND) - { - ClientUtil.checkResponse(response, 200); - result = response.getEntity(ChangesetPagingResult.class); - } - } - finally - { - ClientUtil.close(response); - } - - return result; - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private Repository repository; - - /** Field description */ - private JerseyClientSession session; -} diff --git a/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseyClientProvider.java b/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseyClientProvider.java deleted file mode 100644 index eb9825d470..0000000000 --- a/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseyClientProvider.java +++ /dev/null @@ -1,282 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -//~--- non-JDK imports -------------------------------------------------------- - -import com.google.common.base.Strings; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import sonia.scm.ScmState; -import sonia.scm.url.UrlProvider; -import sonia.scm.url.UrlProviderFactory; -import sonia.scm.util.AssertUtil; -import sonia.scm.util.HttpUtil; -import sonia.scm.util.Util; - -//~--- JDK imports ------------------------------------------------------------ - -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientHandlerException; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.api.client.filter.ClientFilter; -import com.sun.jersey.core.util.MultivaluedMapImpl; -import com.sun.jersey.multipart.impl.MultiPartWriter; - -import javax.ws.rs.core.MultivaluedMap; - -/** - * - * @author Sebastian Sdorra - */ -public class JerseyClientProvider implements ScmClientProvider -{ - - /** the logger for JerseyClientProvider */ - private static final Logger logger = - LoggerFactory.getLogger(JerseyClientProvider.class); - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - */ - public JerseyClientProvider() {} - - /** - * Constructs ... - * - * - * @param enableLogging - */ - public JerseyClientProvider(boolean enableLogging) - { - this.enableLogging = enableLogging; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param url - * @param username - * @param password - * - * @return - * - */ - @Override - public JerseyClientSession createSession(String url, String username, - String password) - { - AssertUtil.assertIsNotEmpty(url); - - String user = "anonymous"; - - if (Util.isNotEmpty(username)) - { - user = username; - } - - logger.info("create new session for {} with username {}", url, user); - - UrlProvider urlProvider = UrlProviderFactory.createUrlProvider(url, - UrlProviderFactory.TYPE_RESTAPI_XML); - - Client client = - Client.create(new DefaultClientConfig(MultiPartWriter.class)); - - boolean loginAttempt = isLoginAttempt(username, password); - ClientResponse response; - - if (loginAttempt) - { - response = login(urlProvider, client, username, password); - } - else - { - response = state(urlProvider, client); - } - - ClientUtil.checkResponse(response); - - ScmState state = response.getEntity(ScmState.class); - - if (!state.isSuccess()) - { - logger.warn("server returned state failed"); - - throw new ScmClientException("create ScmClientSession failed"); - } - - logger.info("create session successfully for user {}", user); - - if (loginAttempt) - { - appendAuthenticationFilter(client, state); - } - - return new JerseyClientSession(client, urlProvider, state); - } - - private void appendAuthenticationFilter(Client client, ScmState state) - { - String token = state.getToken(); - - if (Strings.isNullOrEmpty(token)) - { - throw new ScmClientException( - "scm-manager does not return a bearer token"); - } - - // authentication for further requests - client.addFilter(new AuthenticationFilter(token)); - } - - private ClientResponse login(UrlProvider urlProvider, Client client, - String username, String password) - { - String authUrl = urlProvider.getAuthenticationUrl(); - - if (logger.isDebugEnabled()) - { - logger.debug("try login at {}", authUrl); - } - - WebResource resource = ClientUtil.createResource(client, authUrl, - enableLogging); - - if (logger.isDebugEnabled()) - { - logger.debug("try login for {}", username); - } - - MultivaluedMap formData = new MultivaluedMapImpl(); - - formData.add("username", username); - formData.add("password", password); - formData.add("grant_type", "password"); - - return resource.type("application/x-www-form-urlencoded").post( - ClientResponse.class, formData); - } - - private ClientResponse state(UrlProvider urlProvider, Client client) - { - String stateUrl = urlProvider.getStateUrl(); - - if (logger.isDebugEnabled()) - { - logger.debug("retrive state from {}", stateUrl); - } - - WebResource resource = ClientUtil.createResource(client, stateUrl, - enableLogging); - - if (logger.isDebugEnabled()) - { - logger.debug("try anonymous login"); - } - - return resource.get(ClientResponse.class); - } - - //~--- get methods ---------------------------------------------------------- - - private boolean isLoginAttempt(String username, String password) - { - return Util.isNotEmpty(username) && Util.isNotEmpty(password); - } - - //~--- inner classes -------------------------------------------------------- - - /** - * Authentication filter - */ - private class AuthenticationFilter extends ClientFilter - { - - /** - * Constructs ... - * - * - * @param bearerToken - */ - public AuthenticationFilter(String bearerToken) - { - this.bearerToken = bearerToken; - } - - //~--- methods ------------------------------------------------------------ - - /** - * Method description - * - * - * @param request - * - * @return - * - * @throws ClientHandlerException - */ - @Override - public ClientResponse handle(ClientRequest request) - throws ClientHandlerException - { - request.getHeaders().putSingle(HttpUtil.HEADER_AUTHORIZATION, - HttpUtil.AUTHORIZATION_SCHEME_BEARER.concat(" ").concat(bearerToken)); - - return getNext().handle(request); - } - - //~--- fields ------------------------------------------------------------- - - /** Field description */ - private final String bearerToken; - } - - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private boolean enableLogging = false; -} diff --git a/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseyClientRepositoryBrowser.java b/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseyClientRepositoryBrowser.java deleted file mode 100644 index 571c30f7db..0000000000 --- a/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseyClientRepositoryBrowser.java +++ /dev/null @@ -1,232 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.repository.BlameLine; -import sonia.scm.repository.BlameResult; -import sonia.scm.repository.BrowserResult; -import sonia.scm.repository.FileObject; -import sonia.scm.repository.Repository; -import sonia.scm.util.AssertUtil; -import sonia.scm.util.Util; - -//~--- JDK imports ------------------------------------------------------------ - -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; - -import java.io.IOException; -import java.io.InputStream; - -import java.util.ArrayList; -import java.util.List; - -/** - * - * @author Sebastian Sdorra - */ -public class JerseyClientRepositoryBrowser implements ClientRepositoryBrowser -{ - - /** - * Constructs ... - * - * - * @param session - * @param repository - */ - public JerseyClientRepositoryBrowser(JerseyClientSession session, - Repository repository) - { - this.session = session; - this.repository = repository; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param revision - * @param path - * - * @return - */ - @Override - public List getBlameLines(String revision, String path) - { - List blameLines = null; - String url = - session.getUrlProvider().getRepositoryUrlProvider().getBlameUrl( - repository.getId(), path, revision); - WebResource resource = session.getClient().resource(url); - ClientResponse response = null; - - try - { - response = resource.get(ClientResponse.class); - - if (response.getStatus() != ScmClientException.SC_NOTFOUND) - { - ClientUtil.checkResponse(response, 200); - - BlameResult result = response.getEntity(BlameResult.class); - - AssertUtil.assertIsNotNull(result); - blameLines = result.getBlameLines(); - } - } - finally - { - ClientUtil.close(response); - } - - return blameLines; - } - - /** - * Method description - * - * - * @param revision - * @param path - * - * @return - * - * @throws IOException - */ - @Override - public InputStream getContent(String revision, String path) throws IOException - { - InputStream input = null; - String url = - session.getUrlProvider().getRepositoryUrlProvider().getContentUrl( - repository.getId(), path, revision); - WebResource resource = session.getClient().resource(url); - ClientResponse response = null; - - try - { - response = resource.get(ClientResponse.class); - - if (response.getStatus() != ScmClientException.SC_NOTFOUND) - { - ClientUtil.checkResponse(response, 200); - input = response.getEntityInputStream(); - } - } - finally - { - ClientUtil.close(response); - } - - return input; - } - - /** - * Method description - * - * - * @param revision - * @param path - * - * @return - */ - @Override - public List getFiles(String revision, String path) - { - List files = null; - String url = - session.getUrlProvider().getRepositoryUrlProvider().getBrowseUrl( - repository.getId(), path, revision); - WebResource resource = session.getClient().resource(url); - ClientResponse response = null; - - try - { - response = resource.get(ClientResponse.class); - - if (response.getStatus() != ScmClientException.SC_NOTFOUND) - { - ClientUtil.checkResponse(response, 200); - - BrowserResult result = response.getEntity(BrowserResult.class); - - AssertUtil.assertIsNotNull(result); - files = new ArrayList(); - - List foList = result.getFiles(); - - if (Util.isNotEmpty(foList)) - { - for (FileObject fo : foList) - { - files.add(new FileObjectWrapper(this, revision, fo)); - } - } - } - } - finally - { - ClientUtil.close(response); - } - - return files; - } - - /** - * Method description - * - * - * @param revision - * - * @return - */ - @Override - public List getFiles(String revision) - { - return getFiles(revision, Util.EMPTY_STRING); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private Repository repository; - - /** Field description */ - private JerseyClientSession session; -} diff --git a/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseyClientSession.java b/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseyClientSession.java deleted file mode 100644 index 5e0531be4e..0000000000 --- a/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseyClientSession.java +++ /dev/null @@ -1,189 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import sonia.scm.ScmState; -import sonia.scm.url.UrlProvider; - -//~--- JDK imports ------------------------------------------------------------ - -import com.sun.jersey.api.client.Client; - -/** - * - * @author Sebastian Sdorra - */ -public class JerseyClientSession implements ScmClientSession -{ - - /** the logger for JerseyClientSession */ - private static final Logger logger = - LoggerFactory.getLogger(JerseyClientSession.class); - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - * - * @param client - * @param urlProvider - * @param state - */ - public JerseyClientSession(Client client, UrlProvider urlProvider, - ScmState state) - { - this.client = client; - this.urlProvider = urlProvider; - this.state = state; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - */ - @Override - public void close() - { - if (logger.isInfoEnabled()) - { - logger.info("close client session"); - } - - client.destroy(); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public Client getClient() - { - return client; - } - - /** - * Method description - * - * - * @return - */ - @Override - public GroupClientHandler getGroupHandler() - { - return new JerseyGroupClientHandler(this); - } - - /** - * Method description - * - * - * @return - */ - @Override - public RepositoryClientHandler getRepositoryHandler() - { - return new JerseyRepositoryClientHandler(this); - } - - /** - * Method description - * - * - * @return - */ - @Override - public SecurityClientHandler getSecurityHandler() - { - return new JerseySecurityClientHandler(this); - } - - /** - * Method description - * - * - * @return - */ - @Override - public ScmState getState() - { - return state; - } - - /** - * Method description - * - * - * @return - */ - public UrlProvider getUrlProvider() - { - return urlProvider; - } - - /** - * Method description - * - * - * @return - */ - @Override - public UserClientHandler getUserHandler() - { - return new JerseyUserClientHandler(this); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private final Client client; - - /** Field description */ - private final ScmState state; - - /** Field description */ - private final UrlProvider urlProvider; -} diff --git a/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseyGroupClientHandler.java b/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseyGroupClientHandler.java deleted file mode 100644 index 0c22798279..0000000000 --- a/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseyGroupClientHandler.java +++ /dev/null @@ -1,122 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.group.Group; - -//~--- JDK imports ------------------------------------------------------------ - -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.GenericType; - -import java.util.List; - -/** - * - * @author Sebastian Sdorra - */ -public class JerseyGroupClientHandler extends AbstractClientHandler - implements GroupClientHandler -{ - - /** - * Constructs ... - * - * - * @param session - */ - public JerseyGroupClientHandler(JerseyClientSession session) - { - super(session, Group.class); - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - @Override - protected GenericType> createGenericListType() - { - return new GenericType>() {} - ; - } - - /** - * Method description - * - * - * @param response - * @param item - * @param newItem - */ - @Override - protected void postCreate(ClientResponse response, Group item, Group newItem) - { - newItem.copyProperties(item); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param itemId - * - * @return - */ - @Override - protected String getItemUrl(String itemId) - { - return urlProvider.getGroupUrlProvider().getDetailUrl(itemId); - } - - /** - * Method description - * - * - * @return - */ - @Override - protected String getItemsUrl() - { - return urlProvider.getGroupUrlProvider().getAllUrl(); - } -} diff --git a/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseyRepositoryClientHandler.java b/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseyRepositoryClientHandler.java deleted file mode 100644 index ff611c9aa2..0000000000 --- a/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseyRepositoryClientHandler.java +++ /dev/null @@ -1,386 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -//~--- non-JDK imports -------------------------------------------------------- - -import com.google.common.base.Strings; - -import sonia.scm.NotSupportedFeatuerException; -import sonia.scm.Type; -import sonia.scm.repository.ImportResult; -import sonia.scm.repository.Repository; -import sonia.scm.repository.Tags; -import sonia.scm.util.HttpUtil; -import sonia.scm.util.IOUtil; - -//~--- JDK imports ------------------------------------------------------------ - -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.GenericType; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.multipart.FormDataMultiPart; -import com.sun.jersey.multipart.file.StreamDataBodyPart; - -import java.io.IOException; -import java.io.InputStream; - -import java.util.Collection; -import java.util.List; - -import javax.ws.rs.core.MediaType; - -/** - * - * @author Sebastian Sdorra - */ -public class JerseyRepositoryClientHandler - extends AbstractClientHandler implements RepositoryClientHandler -{ - - /** Field description */ - private static final String IMPORT_TYPE_BUNDLE = "bundle"; - - /** Field description */ - private static final String IMPORT_TYPE_DIRECTORY = "directory"; - - /** Field description */ - private static final String IMPORT_TYPE_URL = "url"; - - /** Field description */ - private static final String PARAM_BUNDLE = "bundle"; - - /** Field description */ - private static final String PARAM_COMPRESSED = "compressed"; - - /** Field description */ - private static final String PARAM_NAME = "name"; - - /** Field description */ - private static final String URL_IMPORT = "import/repositories/"; - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - * - * @param session - */ - public JerseyRepositoryClientHandler(JerseyClientSession session) - { - super(session, Repository.class); - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param request - * - * @return - */ - @Override - public Repository importFromBundle(ImportBundleRequest request) - { - WebResource r = client.resource(getImportUrl(request.getType(), - IMPORT_TYPE_BUNDLE)).queryParam(PARAM_COMPRESSED, - Boolean.toString(request.isCompressed())); - Repository repository = null; - InputStream stream = null; - - try - { - stream = request.getBundle().openStream(); - - FormDataMultiPart form = new FormDataMultiPart(); - - form.field(PARAM_NAME, request.getName()); - form.bodyPart(new StreamDataBodyPart(PARAM_BUNDLE, stream)); - - ClientResponse response = - r.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form); - - ClientUtil.checkResponse(response); - - String location = - response.getHeaders().getFirst(HttpUtil.HEADER_LOCATION); - - if (Strings.isNullOrEmpty(location)) - { - throw new ScmClientException("no location header found after import"); - } - - repository = getItemByUrl(location); - } - catch (IOException ex) - { - throw new ScmClientException("could not import bundle", ex); - } - finally - { - IOUtil.close(stream); - } - - return repository; - } - - /** - * Method description - * - * - * @param type - * - * @return - */ - @Override - public ImportResultWrapper importFromDirectory(String type) - { - WebResource r = client.resource(getImportUrl(type, IMPORT_TYPE_DIRECTORY)); - ClientResponse response = r.post(ClientResponse.class); - - ClientUtil.checkResponse(response); - - return new ImportResultWrapper(this, type, - response.getEntity(ImportResult.class)); - } - - /** - * Method description - * - * - * @param request - * - * @return - */ - @Override - public Repository importFromUrl(ImportUrlRequest request) - { - WebResource r = client.resource(getImportUrl(request.getType(), - IMPORT_TYPE_URL)); - ClientResponse response = r.post(ClientResponse.class, request); - - ClientUtil.checkResponse(response); - - String location = response.getHeaders().getFirst(HttpUtil.HEADER_LOCATION); - - if (Strings.isNullOrEmpty(location)) - { - throw new ScmClientException("no location header found after import"); - } - - return getItemByUrl(location); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param type - * @param name - * - * @return - */ - @Override - public Repository get(String type, String name) - { - String url = urlProvider.getRepositoryUrlProvider().getDetailUrl(type, - name); - - return getItemByUrl(url); - } - - /** - * Method description - * - * - * @param repository - * - * @return - * - * @throws NotSupportedFeatuerException - */ - @Override - public ClientChangesetHandler getChangesetHandler(Repository repository) - throws NotSupportedFeatuerException - { - return new JerseyClientChangesetHandler(session, repository); - } - - /** - * Method description - * - * - * @param repository - * - * @return - * - */ - @Override - public JerseyClientRepositoryBrowser getRepositoryBrowser( - Repository repository) - { - return new JerseyClientRepositoryBrowser(session, repository); - } - - /** - * Method description - * - * - * @return - */ - @Override - public Collection getRepositoryTypes() - { - return session.getState().getRepositoryTypes(); - } - - /** - * Method description - * - * - * @param repository - * - * @return - */ - @Override - public Tags getTags(Repository repository) - { - Tags tags = null; - String url = session.getUrlProvider().getRepositoryUrlProvider().getTagsUrl( - repository.getId()); - WebResource resource = session.getClient().resource(url); - ClientResponse response = null; - - try - { - response = resource.get(ClientResponse.class); - - if (response.getStatus() != ScmClientException.SC_NOTFOUND) - { - ClientUtil.checkResponse(response, 200); - tags = response.getEntity(Tags.class); - } - } - finally - { - ClientUtil.close(response); - } - - return tags; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - @Override - protected GenericType> createGenericListType() - { - return new GenericType>() {} - ; - } - - /** - * Method description - * - * - * @param response - * @param repository - * @param newRepository - */ - @Override - protected void postCreate(ClientResponse response, Repository repository, - Repository newRepository) - { - newRepository.copyProperties(repository); - - // copyProperties does not copy the repository id - repository.setId(newRepository.getId()); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param itemId - * - * @return - */ - @Override - protected String getItemUrl(String itemId) - { - return urlProvider.getRepositoryUrlProvider().getDetailUrl(itemId); - } - - /** - * Method description - * - * - * @return - */ - @Override - protected String getItemsUrl() - { - return urlProvider.getRepositoryUrlProvider().getAllUrl(); - } - - /** - * Method description - * - * - * @param type - * @param importType - * - * @return - */ - private String getImportUrl(String type, String importType) - { - StringBuilder buffer = new StringBuilder(URL_IMPORT); - - buffer.append(type).append(HttpUtil.SEPARATOR_PATH).append(importType); - - return HttpUtil.append(urlProvider.getBaseUrl(), buffer.toString()); - } -} diff --git a/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseySecurityClientHandler.java b/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseySecurityClientHandler.java deleted file mode 100644 index 5f24752078..0000000000 --- a/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseySecurityClientHandler.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of SCM-Manager; - * 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -/** - * - * @author Sebastian Sdorra - */ -public class JerseySecurityClientHandler implements SecurityClientHandler -{ - - /** - * Constructs ... - * - * - * @param session - */ - JerseySecurityClientHandler(JerseyClientSession session) - { - this.session = session; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param value - * - * @return - */ - @Override - public String encrypt(String value) - { - String url = - session.getUrlProvider().getSecurityUrlProvider().getEncryptUrl(); - - return session.getClient().resource(url).post(String.class, value); - } - - /** - * Method description - * - * - * @return - */ - @Override - public String generateKey() - { - String url = - session.getUrlProvider().getSecurityUrlProvider().getGenerateKeyUrl(); - - return session.getClient().resource(url).get(String.class); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private final JerseyClientSession session; -} diff --git a/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseyUserClientHandler.java b/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseyUserClientHandler.java deleted file mode 100644 index a353434379..0000000000 --- a/scm-clients/scm-client-impl/src/main/java/sonia/scm/client/JerseyUserClientHandler.java +++ /dev/null @@ -1,122 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.user.User; - -//~--- JDK imports ------------------------------------------------------------ - -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.GenericType; - -import java.util.List; - -/** - * - * @author Sebastian Sdorra - */ -public class JerseyUserClientHandler extends AbstractClientHandler - implements UserClientHandler -{ - - /** - * Constructs ... - * - * - * @param session - */ - public JerseyUserClientHandler(JerseyClientSession session) - { - super(session, User.class); - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - @Override - protected GenericType> createGenericListType() - { - return new GenericType>() {} - ; - } - - /** - * Method description - * - * - * @param response - * @param item - * @param newItem - */ - @Override - protected void postCreate(ClientResponse response, User item, User newItem) - { - newItem.copyProperties(item); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param itemId - * - * @return - */ - @Override - protected String getItemUrl(String itemId) - { - return urlProvider.getUserUrlProvider().getDetailUrl(itemId); - } - - /** - * Method description - * - * - * @return - */ - @Override - protected String getItemsUrl() - { - return urlProvider.getUserUrlProvider().getAllUrl(); - } -} diff --git a/scm-clients/scm-client-impl/src/main/resources/META-INF/services/sonia.scm.client.ScmClientProvider b/scm-clients/scm-client-impl/src/main/resources/META-INF/services/sonia.scm.client.ScmClientProvider deleted file mode 100644 index ac345b3480..0000000000 --- a/scm-clients/scm-client-impl/src/main/resources/META-INF/services/sonia.scm.client.ScmClientProvider +++ /dev/null @@ -1 +0,0 @@ -sonia.scm.client.JerseyClientProvider \ No newline at end of file diff --git a/scm-clients/scm-client-impl/src/test/java/sonia/scm/client/it/AbstractClientHandlerTestBase.java b/scm-clients/scm-client-impl/src/test/java/sonia/scm/client/it/AbstractClientHandlerTestBase.java deleted file mode 100644 index fe4547ecb8..0000000000 --- a/scm-clients/scm-client-impl/src/test/java/sonia/scm/client/it/AbstractClientHandlerTestBase.java +++ /dev/null @@ -1,295 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client.it; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.junit.Test; - -import sonia.scm.ModelObject; -import sonia.scm.client.ClientHandler; -import sonia.scm.client.JerseyClientSession; -import sonia.scm.client.ScmForbiddenException; -import sonia.scm.client.ScmUnauthorizedException; - -import static org.junit.Assert.*; - -import static sonia.scm.client.it.ClientTestUtil.*; - -/** - * - * @author Sebastian Sdorra - * - * @param - */ -public abstract class AbstractClientHandlerTestBase -{ - - /** - * Method description - * - * - * @param session - * - * @return - */ - protected abstract ClientHandler createHandler( - JerseyClientSession session); - - /** - * Method description - * - * - * @return - */ - protected abstract ModifyTest createModifyTest(); - - /** - * Method description - * - * - * @param number - * - * @return - */ - protected abstract T createTestData(int number); - - /** - * Method description - * - * - */ - @Test - public void testCreate() - { - JerseyClientSession session = createAdminSession(); - T item = createTestData(1); - ClientHandler handler = createHandler(session); - - handler.create(item); - assertIsValid(item); - - String id = item.getId(); - T o = handler.get(id); - - assertNotNull(o); - assertEquals(item.getId(), o.getId()); - session.close(); - } - - /** - * Method description - * - * - */ - @Test - public void testDelete() - { - JerseyClientSession session = createAdminSession(); - T item = createTestData(2); - ClientHandler handler = createHandler(session); - - handler.create(item); - assertIsValid(item); - - String id = item.getId(); - - handler.delete(item); - - T o = handler.get(id); - - assertNull(o); - } - - /** - * Method description - * - * - */ - @Test(expected = ScmUnauthorizedException.class) - public void testDisabledCreateAnonymous() - { - JerseyClientSession session = createAnonymousSession(); - T item = createTestData(3); - - createHandler(session).create(item); - session.close(); - } - - /** - * Method description - * - * - */ - @Test - public void testEnabledCreateAnonymous() - { - setAnonymousAccess(true); - - JerseyClientSession session = createAnonymousSession(); - T item = createTestData(3); - boolean forbidden = false; - - try - { - createHandler(session).create(item); - } - catch (ScmForbiddenException ex) - { - forbidden = true; - } - - assertTrue(forbidden); - session.close(); - setAnonymousAccess(false); - } - - /** - * Method description - * - */ - @Test - public void testEnabledModifyAnonymous() - { - setAnonymousAccess(true); - - JerseyClientSession session = createAdminSession(); - T item = createTestData(4); - - createHandler(session).create(item); - assertIsValid(item); - session.close(); - session = createAnonymousSession(); - - ModifyTest mt = createModifyTest(); - - mt.modify(item); - - boolean notfound = false; - - try - { - createHandler(session).modify(item); - } - catch (ScmForbiddenException ex) - { - notfound = true; - } - - setAnonymousAccess(false); - session.close(); - session = createAdminSession(); - createHandler(session).delete(item); - session.close(); - assertTrue(notfound); - } - - /** - * Method description - * - */ - @Test - public void testModify() - { - long start = System.currentTimeMillis(); - JerseyClientSession session = createAdminSession(); - T item = createTestData(4); - ClientHandler handler = createHandler(session); - - handler.create(item); - assertIsValid(item); - item = handler.get(item.getId()); - - ModifyTest mt = createModifyTest(); - - mt.modify(item); - handler.modify(item); - item = handler.get(item.getId()); - assertIsValid(item); - assertTrue(mt.isCorrectModified(item)); - assertNotNull(item.getLastModified()); - assertTrue(item.getLastModified() > start); - assertTrue(item.getLastModified() < System.currentTimeMillis()); - handler.delete(item); - session.close(); - } - - /** - * Method description - * - * - * @param item - */ - protected void assertIsValid(T item) - { - assertNotNull(item); - assertNotNull(item.getId()); - assertTrue(item.getId().length() > 0); - } - - //~--- inner interfaces ----------------------------------------------------- - - /** - * Interface description - * - * - * @param - * - * @version Enter version here..., 11/05/13 - * @author Enter your name here... - */ - protected interface ModifyTest - { - - /** - * Method description - * - * - * @param item - */ - public void modify(T item); - - //~--- get methods -------------------------------------------------------- - - /** - * Method description - * - * - * @param item - * - * @return - */ - public boolean isCorrectModified(T item); - } -} diff --git a/scm-clients/scm-client-impl/src/test/java/sonia/scm/client/it/ClientTestUtil.java b/scm-clients/scm-client-impl/src/test/java/sonia/scm/client/it/ClientTestUtil.java deleted file mode 100644 index c567ff0e86..0000000000 --- a/scm-clients/scm-client-impl/src/test/java/sonia/scm/client/it/ClientTestUtil.java +++ /dev/null @@ -1,144 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client.it; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.client.ClientUtil; -import sonia.scm.client.JerseyClientProvider; -import sonia.scm.client.JerseyClientSession; -import sonia.scm.config.ScmConfiguration; -import sonia.scm.url.UrlProvider; - -//~--- JDK imports ------------------------------------------------------------ - -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.WebResource; - -/** - * - * @author Sebastian Sdorra - */ -public final class ClientTestUtil -{ - - /** Field description */ - public static final String ADMIN_PASSWORD = "scmadmin"; - - /** Field description */ - public static final String ADMIN_USERNAME = "scmadmin"; - - /** Field description */ - public static final String REPOSITORY_TYPE = "git"; - - /** Field description */ - public static final String URL_BASE = "http://localhost:8081/scm"; - - /** Field description */ - public static final boolean REQUEST_LOGGING = false; - - private ClientTestUtil() - { - } - - - - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @return - * - */ - public static JerseyClientSession createAdminSession() - { - return createSession(ADMIN_USERNAME, ADMIN_PASSWORD); - } - - /** - * Method description - * - * - * @return - * - */ - public static JerseyClientSession createAnonymousSession() - { - return createSession(null, null); - } - - /** - * Method description - * - * - * @param username - * @param password - * - * @return - * - */ - public static JerseyClientSession createSession(String username, - String password) - { - JerseyClientProvider provider = new JerseyClientProvider(REQUEST_LOGGING); - - return provider.createSession(URL_BASE, username, password); - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param access - * - */ - public static void setAnonymousAccess(boolean access) - { - JerseyClientSession adminSession = createAdminSession(); - UrlProvider up = adminSession.getUrlProvider(); - Client client = adminSession.getClient(); - WebResource resource = ClientUtil.createResource(client, up.getConfigUrl(), - REQUEST_LOGGING); - ScmConfiguration config = resource.get(ScmConfiguration.class); - - config.setAnonymousAccessEnabled(access); - resource.post(config); - adminSession.close(); - } -} diff --git a/scm-clients/scm-client-impl/src/test/java/sonia/scm/client/it/JerseyClientProviderITCase.java b/scm-clients/scm-client-impl/src/test/java/sonia/scm/client/it/JerseyClientProviderITCase.java deleted file mode 100644 index 3aab675b0b..0000000000 --- a/scm-clients/scm-client-impl/src/test/java/sonia/scm/client/it/JerseyClientProviderITCase.java +++ /dev/null @@ -1,138 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client.it; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.junit.Test; - -import sonia.scm.client.JerseyClientSession; -import sonia.scm.client.ScmClientException; -import sonia.scm.client.ScmUnauthorizedException; - -import static org.junit.Assert.*; - -import static sonia.scm.client.it.ClientTestUtil.*; - -//~--- JDK imports ------------------------------------------------------------ - -import java.io.IOException; - -/** - * - * @author Sebastian Sdorra - */ -public class JerseyClientProviderITCase -{ - - /** - * Method description - * - * - * - */ - @Test(expected = ScmUnauthorizedException.class) - public void createSessionAnonymousFailedTest() - { - createAnonymousSession().close(); - } - - /** - * Method description - * - * - * - */ - @Test - public void createSessionAnonymousTest() - { - - // enable anonymous access - setAnonymousAccess(true); - - // test anonymous access - createAnonymousSession().close(); - - // disable anonymous access - setAnonymousAccess(false); - } - - /** - * Method description - * - * - * - */ - @Test - public void createSessionTest() - { - JerseyClientSession session = createAdminSession(); - - assertNotNull(session); - assertNotNull(session.getState()); - assertNotNull(session.getState().getUser()); - assertEquals(session.getState().getUser().getName(), "scmadmin"); - session.close(); - } - - /** - * Method description - * - * - * - * @throws IOException - * @throws ScmClientException - */ - @Test(expected = ScmUnauthorizedException.class) - public void createSessionWithUnkownUserTest() - throws ScmClientException, IOException - { - createSession("dent", "dent123").close(); - } - - /** - * Method description - * - * - * - * @throws IOException - * @throws ScmClientException - */ - @Test(expected = ScmUnauthorizedException.class) - public void createSessionWithWrongPasswordTest() - throws ScmClientException, IOException - { - createSession("scmadmin", "ka123").close(); - } -} diff --git a/scm-clients/scm-client-impl/src/test/java/sonia/scm/client/it/JerseyGroupClientHandlerITCase.java b/scm-clients/scm-client-impl/src/test/java/sonia/scm/client/it/JerseyGroupClientHandlerITCase.java deleted file mode 100644 index 0650564741..0000000000 --- a/scm-clients/scm-client-impl/src/test/java/sonia/scm/client/it/JerseyGroupClientHandlerITCase.java +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client.it; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.client.ClientHandler; -import sonia.scm.client.JerseyClientSession; -import sonia.scm.client.it.AbstractClientHandlerTestBase.ModifyTest; -import sonia.scm.group.Group; - -/** - * - * @author Sebastian Sdorra - */ -public class JerseyGroupClientHandlerITCase - extends AbstractClientHandlerTestBase -{ - - /** - * Method description - * - * - * @param session - * - * @return - */ - @Override - protected ClientHandler createHandler(JerseyClientSession session) - { - return session.getGroupHandler(); - } - - /** - * Method description - * - * - * @return - */ - @Override - protected ModifyTest createModifyTest() - { - return new ModifyTest() - { - @Override - public void modify(Group item) - { - item.setDescription("Modified Description"); - } - @Override - public boolean isCorrectModified(Group item) - { - return "Modified Description".equals(item.getDescription()); - } - }; - } - - /** - * Method description - * - * - * @param number - * - * @return - */ - @Override - protected Group createTestData(int number) - { - return new Group("xml", "group-" + number); - } -} diff --git a/scm-clients/scm-client-impl/src/test/java/sonia/scm/client/it/JerseyRepositoryClientHandlerITCase.java b/scm-clients/scm-client-impl/src/test/java/sonia/scm/client/it/JerseyRepositoryClientHandlerITCase.java deleted file mode 100644 index d960d57392..0000000000 --- a/scm-clients/scm-client-impl/src/test/java/sonia/scm/client/it/JerseyRepositoryClientHandlerITCase.java +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client.it; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.client.ClientHandler; -import sonia.scm.client.JerseyClientSession; -import sonia.scm.client.it.AbstractClientHandlerTestBase.ModifyTest; -import sonia.scm.repository.Repository; -import sonia.scm.repository.RepositoryTestData; - -import static org.junit.Assert.*; - -import static sonia.scm.client.it.ClientTestUtil.*; - -/** - * - * @author Sebastian Sdorra - */ -public class JerseyRepositoryClientHandlerITCase - extends AbstractClientHandlerTestBase -{ - - /** - * Method description - * - * - * @param item - */ - @Override - protected void assertIsValid(Repository item) - { - super.assertIsValid(item); - assertNotNull(item.getCreationDate()); - assertTrue(item.getCreationDate() > 0); - assertTrue(item.getCreationDate() < System.currentTimeMillis()); - } - - /** - * Method description - * - * - * @param session - * - * @return - */ - @Override - protected ClientHandler createHandler(JerseyClientSession session) - { - return session.getRepositoryHandler(); - } - - /** - * Method description - * - * - * @return - */ - @Override - protected ModifyTest createModifyTest() - { - return new ModifyTest() - { - @Override - public void modify(Repository item) - { - item.setDescription("Modified description"); - } - @Override - public boolean isCorrectModified(Repository item) - { - return "Modified description".equals(item.getDescription()); - } - }; - } - - /** - * Method description - * - * - * @param number - * - * @return - */ - @Override - protected Repository createTestData(int number) - { - Repository repository = null; - - switch (number) - { - case 1 : - repository = RepositoryTestData.createHeartOfGold(REPOSITORY_TYPE); - - break; - - case 2 : - repository = RepositoryTestData.createHappyVerticalPeopleTransporter( - REPOSITORY_TYPE); - - break; - - case 3 : - repository = RepositoryTestData.create42Puzzle(REPOSITORY_TYPE); - - break; - - case 4 : - repository = RepositoryTestData.createRestaurantAtTheEndOfTheUniverse( - REPOSITORY_TYPE); - - break; - } - - return repository; - } -} diff --git a/scm-clients/scm-client-impl/src/test/java/sonia/scm/client/it/JerseyUserClientHandlerITCase.java b/scm-clients/scm-client-impl/src/test/java/sonia/scm/client/it/JerseyUserClientHandlerITCase.java deleted file mode 100644 index d84deabb42..0000000000 --- a/scm-clients/scm-client-impl/src/test/java/sonia/scm/client/it/JerseyUserClientHandlerITCase.java +++ /dev/null @@ -1,128 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.client.it; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.client.ClientHandler; -import sonia.scm.client.JerseyClientSession; -import sonia.scm.client.it.AbstractClientHandlerTestBase.ModifyTest; -import sonia.scm.user.User; -import sonia.scm.user.UserTestData; - -/** - * - * @author Sebastian Sdorra - */ -public class JerseyUserClientHandlerITCase - extends AbstractClientHandlerTestBase -{ - - /** - * Method description - * - * - * @param session - * - * @return - */ - @Override - protected ClientHandler createHandler(JerseyClientSession session) - { - return session.getUserHandler(); - } - - /** - * Method description - * - * - * @return - */ - @Override - protected ModifyTest createModifyTest() - { - return new ModifyTest() - { - @Override - public void modify(User item) - { - item.setDisplayName("Modified DisplayName"); - } - @Override - public boolean isCorrectModified(User item) - { - return "Modified DisplayName".equals(item.getDisplayName()); - } - }; - } - - /** - * Method description - * - * - * @param number - * - * @return - */ - @Override - protected User createTestData(int number) - { - User user = null; - - switch (number) - { - case 1 : - user = UserTestData.createAdams(); - - break; - - case 2 : - user = UserTestData.createDent(); - - break; - - case 3 : - user = UserTestData.createMarvin(); - - break; - - case 4 : - user = UserTestData.createPerfect(); - - break; - } - - return user; - } -} diff --git a/scm-clients/scm-client-impl/src/test/resources/logback.xml b/scm-clients/scm-client-impl/src/test/resources/logback.xml deleted file mode 100644 index 26effea73e..0000000000 --- a/scm-clients/scm-client-impl/src/test/resources/logback.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n - - - - - - - - - - \ No newline at end of file diff --git a/scm-core/pom.xml b/scm-core/pom.xml index ddd443afb4..a06eb544dc 100644 --- a/scm-core/pom.xml +++ b/scm-core/pom.xml @@ -159,7 +159,6 @@ org.apache.maven.plugins maven-javadoc-plugin - 2.9 true ${project.build.sourceEncoding} diff --git a/scm-core/src/main/java/sonia/scm/HandlerBase.java b/scm-core/src/main/java/sonia/scm/HandlerBase.java index 0baea8d929..6ce7d9a6a6 100644 --- a/scm-core/src/main/java/sonia/scm/HandlerBase.java +++ b/scm-core/src/main/java/sonia/scm/HandlerBase.java @@ -53,13 +53,9 @@ public interface HandlerBase /** * Persists a new object. * - * - * @param object to store - * - * @throws E - * @throws IOException + * @return The persisted object. */ - public void create(T object) throws E, IOException; + public T create(T object) throws E; /** * Removes a persistent object. @@ -70,7 +66,7 @@ public interface HandlerBase * @throws E * @throws IOException */ - public void delete(T object) throws E, IOException; + public void delete(T object) throws E; /** * Modifies a persistent object. @@ -81,5 +77,5 @@ public interface HandlerBase * @throws E * @throws IOException */ - public void modify(T object) throws E, IOException; + public void modify(T object) throws E; } diff --git a/scm-core/src/main/java/sonia/scm/Manager.java b/scm-core/src/main/java/sonia/scm/Manager.java index 79155b56a2..c0d074520a 100644 --- a/scm-core/src/main/java/sonia/scm/Manager.java +++ b/scm-core/src/main/java/sonia/scm/Manager.java @@ -33,7 +33,6 @@ package sonia.scm; -import java.io.IOException; import java.util.Collection; import java.util.Comparator; @@ -56,9 +55,8 @@ public interface Manager * @param object to refresh * * @throws E - * @throws IOException */ - void refresh(T object) throws E, IOException; + void refresh(T object) throws E; //~--- get methods ---------------------------------------------------------- diff --git a/scm-core/src/main/java/sonia/scm/ManagerDecorator.java b/scm-core/src/main/java/sonia/scm/ManagerDecorator.java index af0215202c..3b90002d13 100644 --- a/scm-core/src/main/java/sonia/scm/ManagerDecorator.java +++ b/scm-core/src/main/java/sonia/scm/ManagerDecorator.java @@ -35,7 +35,6 @@ package sonia.scm; //~--- JDK imports ------------------------------------------------------------ import java.io.IOException; - import java.util.Collection; import java.util.Comparator; @@ -78,16 +77,16 @@ public class ManagerDecorator * {@inheritDoc} */ @Override - public void create(T object) throws E, IOException + public T create(T object) throws E { - decorated.create(object); + return decorated.create(object); } /** * {@inheritDoc} */ @Override - public void delete(T object) throws E, IOException + public void delete(T object) throws E { decorated.delete(object); } @@ -105,7 +104,7 @@ public class ManagerDecorator * {@inheritDoc} */ @Override - public void modify(T object) throws E, IOException + public void modify(T object) throws E { decorated.modify(object); } @@ -114,7 +113,7 @@ public class ManagerDecorator * {@inheritDoc} */ @Override - public void refresh(T object) throws E, IOException + public void refresh(T object) throws E { decorated.refresh(object); } diff --git a/scm-core/src/main/java/sonia/scm/ModelObject.java b/scm-core/src/main/java/sonia/scm/ModelObject.java index 76ba021e67..cca9608ceb 100644 --- a/scm-core/src/main/java/sonia/scm/ModelObject.java +++ b/scm-core/src/main/java/sonia/scm/ModelObject.java @@ -53,5 +53,11 @@ public interface ModelObject * * @return unique id */ - public String getId(); + String getId(); + + void setLastModified(Long timestamp); + + Long getCreationDate(); + + void setCreationDate(Long timestamp); } diff --git a/scm-core/src/main/java/sonia/scm/config/ScmConfiguration.java b/scm-core/src/main/java/sonia/scm/config/ScmConfiguration.java index ac22c1403e..c7c3517099 100644 --- a/scm-core/src/main/java/sonia/scm/config/ScmConfiguration.java +++ b/scm-core/src/main/java/sonia/scm/config/ScmConfiguration.java @@ -1,19 +1,19 @@ /** * Copyright (c) 2010, Sebastian Sdorra * All rights reserved. - * + *

* Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + *

* 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. + * this list of conditions and the following disclaimer. * 2. 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. + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. * 3. Neither the name of SCM-Manager; nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * + * 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 @@ -24,39 +24,32 @@ * 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. - * + *

* http://bitbucket.org/sdorra/scm-manager - * */ - package sonia.scm.config; -//~--- non-JDK imports -------------------------------------------------------- import com.google.common.collect.Sets; import com.google.inject.Singleton; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import sonia.scm.event.ScmEventBus; import sonia.scm.util.HttpUtil; import sonia.scm.xml.XmlSetStringAdapter; -//~--- JDK imports ------------------------------------------------------------ - -import java.io.File; - -import java.util.Set; -import java.util.concurrent.TimeUnit; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import java.io.File; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +//~--- JDK imports ------------------------------------------------------------ /** * The main configuration object for SCM-Manager. @@ -67,38 +60,137 @@ import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; @Singleton @XmlRootElement(name = "scm-config") @XmlAccessorType(XmlAccessType.FIELD) -public class ScmConfiguration -{ +public class ScmConfiguration { - /** Default JavaScript date format */ + /** + * Default JavaScript date format + */ public static final String DEFAULT_DATEFORMAT = "YYYY-MM-DD HH:mm:ss"; - /** Default plugin url */ + /** + * Default plugin url + */ public static final String DEFAULT_PLUGINURL = "http://plugins.scm-manager.org/scm-plugin-backend/api/{version}/plugins?os={os}&arch={arch}&snapshot=false"; - /** Default plugin url from version 1.0 */ + /** + * Default plugin url from version 1.0 + */ public static final String OLD_PLUGINURL = "http://plugins.scm-manager.org/plugins.xml.gz"; - /** Path to the configuration file */ + /** + * Path to the configuration file + */ public static final String PATH = "config".concat(File.separator).concat("config.xml"); - /** the logger for ScmConfiguration */ + /** + * the logger for ScmConfiguration + */ private static final Logger logger = LoggerFactory.getLogger(ScmConfiguration.class); - //~--- methods -------------------------------------------------------------- + + @XmlElement(name = "admin-groups") + @XmlJavaTypeAdapter(XmlSetStringAdapter.class) + private Set adminGroups; + + + @XmlElement(name = "admin-users") + @XmlJavaTypeAdapter(XmlSetStringAdapter.class) + private Set adminUsers; + + + @XmlElement(name = "base-url") + private String baseUrl; + + + @XmlElement(name = "force-base-url") + private boolean forceBaseUrl; + + /** + * Maximum allowed login attempts. + * + * @since 1.34 + */ + @XmlElement(name = "login-attempt-limit") + private int loginAttemptLimit = -1; + + /** + * glob patterns for urls which are excluded from proxy + */ + @XmlElement(name = "proxy-excludes") + @XmlJavaTypeAdapter(XmlSetStringAdapter.class) + private Set proxyExcludes; + + + private String proxyPassword; + + + private int proxyPort = 8080; + + + private String proxyServer = "proxy.mydomain.com"; + + + private String proxyUser; + + /** + * Skip failed authenticators. + * + * @since 1.36 + */ + @XmlElement(name = "skip-failed-authenticators") + private boolean skipFailedAuthenticators = false; + + + @XmlElement(name = "plugin-url") + private String pluginUrl = DEFAULT_PLUGINURL; + + /** + * Login attempt timeout. + * + * @since 1.34 + */ + @XmlElement(name = "login-attempt-limit-timeout") + private long loginAttemptLimitTimeout = TimeUnit.MINUTES.toSeconds(5l); + + + private boolean enableProxy = false; + + /** + * Authentication realm for basic authentication. + */ + private String realmDescription = HttpUtil.AUTHENTICATION_REALM; + private boolean enableRepositoryArchive = false; + private boolean disableGroupingGrid = false; + /** + * JavaScript date format from moment.js + * + * @see http://momentjs.com/docs/#/parsing/ + */ + private String dateFormat = DEFAULT_DATEFORMAT; + private boolean anonymousAccessEnabled = false; + + /** + * Enables xsrf cookie protection. + * + * @since 1.47 + */ + @XmlElement(name = "xsrf-protection") + private boolean enabledXsrfProtection = true; + + @XmlElement(name = "default-namespace-strategy") + private String defaultNamespaceStrategy = "sonia.scm.repository.DefaultNamespaceStrategy"; + /** * Calls the {@link sonia.scm.ConfigChangedListener#configChanged(Object)} * method of all registered listeners. */ - public void fireChangeEvent() - { - if (logger.isDebugEnabled()) - { + public void fireChangeEvent() { + if (logger.isDebugEnabled()) { logger.debug("fire config changed event"); } @@ -109,12 +201,9 @@ public class ScmConfiguration /** * Load all properties from another {@link ScmConfiguration} object. * - * - * * @param other */ - public void load(ScmConfiguration other) - { + public void load(ScmConfiguration other) { this.realmDescription = other.realmDescription; this.dateFormat = other.dateFormat; this.pluginUrl = other.pluginUrl; @@ -135,29 +224,14 @@ public class ScmConfiguration this.loginAttemptLimit = other.loginAttemptLimit; this.loginAttemptLimitTimeout = other.loginAttemptLimitTimeout; this.enabledXsrfProtection = other.enabledXsrfProtection; + this.defaultNamespaceStrategy = other.defaultNamespaceStrategy; } - //~--- get methods ---------------------------------------------------------- - - /** - * Returns a set of admin group names. - * - * - * @return set of admin group names - */ - public Set getAdminGroups() - { + public Set getAdminGroups() { return adminGroups; } - /** - * Returns a set of admin user names. - * - * - * @return set of admin user names - */ - public Set getAdminUsers() - { + public Set getAdminUsers() { return adminUsers; } @@ -165,11 +239,10 @@ public class ScmConfiguration * Returns the complete base url of the scm-manager including the context path. * For example http://localhost:8080/scm * - * @since 1.5 * @return complete base url of the scm-manager + * @since 1.5 */ - public String getBaseUrl() - { + public String getBaseUrl() { return baseUrl; } @@ -177,23 +250,14 @@ public class ScmConfiguration * Returns the date format for the user interface. This format is a * JavaScript date format, from the library moment.js. * - * @see http://momentjs.com/docs/#/parsing/ * @return moment.js date format + * @see http://momentjs.com/docs/#/parsing/ */ - public String getDateFormat() - { + public String getDateFormat() { return dateFormat; } - /** - * Returns maximum allowed login attempts. - * - * @return maximum allowed login attempts - * - * @since 1.34 - */ - public int getLoginAttemptLimit() - { + public int getLoginAttemptLimit() { return loginAttemptLimit; } @@ -202,11 +266,9 @@ public class ScmConfiguration * because of too many failed login attempts. * * @return login attempt timeout in seconds - * * @since 1.34 */ - public long getLoginAttemptLimitTimeout() - { + public long getLoginAttemptLimitTimeout() { return loginAttemptLimitTimeout; } @@ -222,8 +284,7 @@ public class ScmConfiguration * * @return the complete plugin url. */ - public String getPluginUrl() - { + public String getPluginUrl() { return pluginUrl; } @@ -231,289 +292,141 @@ public class ScmConfiguration * Returns a set of glob patterns for urls which should excluded from * proxy settings. * - * * @return set of glob patterns * @since 1.23 */ - public Set getProxyExcludes() - { - if (proxyExcludes == null) - { + public Set getProxyExcludes() { + if (proxyExcludes == null) { proxyExcludes = Sets.newHashSet(); } return proxyExcludes; } - /** - * Method description - * - * - * @return - * @since 1.7 - */ - public String getProxyPassword() - { + public String getProxyPassword() { return proxyPassword; } - /** - * Returns the proxy port. - * - * - * @return proxy port - */ - public int getProxyPort() - { + public int getProxyPort() { return proxyPort; } /** * Returns the servername or ip of the proxyserver. * - * * @return servername or ip of the proxyserver */ - public String getProxyServer() - { + public String getProxyServer() { return proxyServer; } - /** - * Method description - * - * - * @return - * @since 1.7 - */ - public String getProxyUser() - { + public String getProxyUser() { return proxyUser; } - /** - * Returns the realm description. - * - * - * @return realm description - * @since 1.36 - */ - public String getRealmDescription() - { + public String getRealmDescription() { return realmDescription; } - - /** - * Returns true if the anonymous access to the SCM-Manager is enabled. - * - * - * @return true if the anonymous access to the SCM-Manager is enabled - */ - public boolean isAnonymousAccessEnabled() - { + public boolean isAnonymousAccessEnabled() { return anonymousAccessEnabled; } - /** - * Method description - * - * @since 1.9 - * @return - */ - public boolean isDisableGroupingGrid() - { + public boolean isDisableGroupingGrid() { return disableGroupingGrid; } /** * Returns {@code true} if the cookie xsrf protection is enabled. - * - * @see Issue 793 + * * @return {@code true} if the cookie xsrf protection is enabled - * + * @see Issue 793 * @since 1.47 */ - public boolean isEnabledXsrfProtection() - { + public boolean isEnabledXsrfProtection() { return enabledXsrfProtection; } - /** - * Returns true if proxy is enabled. - * - * - * @return true if proxy is enabled - */ - public boolean isEnableProxy() - { + public boolean isEnableProxy() { return enableProxy; } - /** - * Returns true if the repository archive is enabled. - * - * - * @return true if the repository archive is enabled - * @since 1.14 - */ - public boolean isEnableRepositoryArchive() - { + public boolean isEnableRepositoryArchive() { return enableRepositoryArchive; } - /** - * Returns true if force base url is enabled. - * - * @since 1.5 - * @return true if force base url is enabled - */ - public boolean isForceBaseUrl() - { + public boolean isForceBaseUrl() { return forceBaseUrl; } - /** - * Returns true if the login attempt limit is enabled. - * - * - * @return true if login attempt limit is enabled - * - * @since 1.37 - */ - public boolean isLoginAttemptLimitEnabled() - { + public boolean isLoginAttemptLimitEnabled() { return loginAttemptLimit > 0; } + public String getDefaultNamespaceStrategy() { + return defaultNamespaceStrategy; + } + + /** * Returns true if failed authenticators are skipped. * - * * @return true if failed authenticators are skipped - * * @since 1.36 */ - public boolean isSkipFailedAuthenticators() - { + public boolean isSkipFailedAuthenticators() { return skipFailedAuthenticators; } - //~--- set methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param adminGroups - */ - public void setAdminGroups(Set adminGroups) - { + public void setAdminGroups(Set adminGroups) { this.adminGroups = adminGroups; } - /** - * Method description - * - * - * @param adminUsers - */ - public void setAdminUsers(Set adminUsers) - { + public void setAdminUsers(Set adminUsers) { this.adminUsers = adminUsers; } - /** - * Method description - * - * - * @param anonymousAccessEnabled - */ - public void setAnonymousAccessEnabled(boolean anonymousAccessEnabled) - { + public void setAnonymousAccessEnabled(boolean anonymousAccessEnabled) { this.anonymousAccessEnabled = anonymousAccessEnabled; } - /** - * Method description - * - * - * @param baseUrl - * @since 1.5 - */ - public void setBaseUrl(String baseUrl) - { + public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; } - /** - * Sets the date format for the ui. - * - * - * @param dateFormat date format for ui - */ - public void setDateFormat(String dateFormat) - { + public void setDateFormat(String dateFormat) { this.dateFormat = dateFormat; } - /** - * Method description - * - * @since 1.9 - * - * @param disableGroupingGrid - */ - public void setDisableGroupingGrid(boolean disableGroupingGrid) - { + public void setDisableGroupingGrid(boolean disableGroupingGrid) { this.disableGroupingGrid = disableGroupingGrid; } - /** - * Method description - * - * - * @param enableProxy - */ - public void setEnableProxy(boolean enableProxy) - { + public void setEnableProxy(boolean enableProxy) { this.enableProxy = enableProxy; } /** * Enable or disable the repository archive. Default is disabled. * - * * @param enableRepositoryArchive true to disable the repository archive * @since 1.14 */ - public void setEnableRepositoryArchive(boolean enableRepositoryArchive) - { + public void setEnableRepositoryArchive(boolean enableRepositoryArchive) { this.enableRepositoryArchive = enableRepositoryArchive; } - /** - * Method description - * - * - * @param forceBaseUrl - * @since 1.5 - */ - public void setForceBaseUrl(boolean forceBaseUrl) - { + public void setForceBaseUrl(boolean forceBaseUrl) { this.forceBaseUrl = forceBaseUrl; } /** * Set maximum allowed login attempts. * - * * @param loginAttemptLimit login attempt limit - * * @since 1.34 */ - public void setLoginAttemptLimit(int loginAttemptLimit) - { + public void setLoginAttemptLimit(int loginAttemptLimit) { this.loginAttemptLimit = loginAttemptLimit; } @@ -522,22 +435,13 @@ public class ScmConfiguration * because of too many failed login attempts. * * @param loginAttemptLimitTimeout login attempt timeout in seconds - * * @since 1.34 */ - public void setLoginAttemptLimitTimeout(long loginAttemptLimitTimeout) - { + public void setLoginAttemptLimitTimeout(long loginAttemptLimitTimeout) { this.loginAttemptLimitTimeout = loginAttemptLimitTimeout; } - /** - * Method description - * - * - * @param pluginUrl - */ - public void setPluginUrl(String pluginUrl) - { + public void setPluginUrl(String pluginUrl) { this.pluginUrl = pluginUrl; } @@ -545,194 +449,56 @@ public class ScmConfiguration * Set glob patterns for urls which are should be excluded from proxy * settings. * - * * @param proxyExcludes glob patterns * @since 1.23 */ - public void setProxyExcludes(Set proxyExcludes) - { + public void setProxyExcludes(Set proxyExcludes) { this.proxyExcludes = proxyExcludes; } - /** - * Method description - * - * - * @param proxyPassword - * @since 1.7 - */ - public void setProxyPassword(String proxyPassword) - { + public void setProxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } - /** - * Method description - * - * - * @param proxyPort - */ - public void setProxyPort(int proxyPort) - { + public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; } - /** - * Method description - * - * - * @param proxyServer - */ - public void setProxyServer(String proxyServer) - { + public void setProxyServer(String proxyServer) { this.proxyServer = proxyServer; } - /** - * Method description - * - * - * @param proxyUser - * @since 1.7 - */ - public void setProxyUser(String proxyUser) - { + public void setProxyUser(String proxyUser) { this.proxyUser = proxyUser; } - /** - * Sets the realm description. - * - * - * @param realmDescription - * @since 1.36 - */ - public void setRealmDescription(String realmDescription) - { + public void setRealmDescription(String realmDescription) { this.realmDescription = realmDescription; } /** - * If set to true the authentication chain is not stopped, if an + * If set to true the authentication chain is not stopped, if an * authenticator finds the user but fails to authenticate the user. * * @param skipFailedAuthenticators true to skip failed authenticators - * * @since 1.36 */ - public void setSkipFailedAuthenticators(boolean skipFailedAuthenticators) - { + public void setSkipFailedAuthenticators(boolean skipFailedAuthenticators) { this.skipFailedAuthenticators = skipFailedAuthenticators; } /** * Set {@code true} to enable xsrf cookie protection. - * + * * @param enabledXsrfProtection {@code true} to enable xsrf protection * @see Issue 793 - * * @since 1.47 */ - public void setEnabledXsrfProtection(boolean enabledXsrfProtection) - { + public void setEnabledXsrfProtection(boolean enabledXsrfProtection) { this.enabledXsrfProtection = enabledXsrfProtection; } - //~--- fields --------------------------------------------------------------- - - /** Field description */ - @XmlElement(name = "admin-groups") - @XmlJavaTypeAdapter(XmlSetStringAdapter.class) - private Set adminGroups; - - /** Field description */ - @XmlElement(name = "admin-users") - @XmlJavaTypeAdapter(XmlSetStringAdapter.class) - private Set adminUsers; - - /** Field description */ - @XmlElement(name = "base-url") - private String baseUrl; - - /** Field description */ - @XmlElement(name = "force-base-url") - private boolean forceBaseUrl; - - /** - * Maximum allowed login attempts. - * - * @since 1.34 - */ - @XmlElement(name = "login-attempt-limit") - private int loginAttemptLimit = -1; - - /** glob patterns for urls which are excluded from proxy */ - @XmlElement(name = "proxy-excludes") - @XmlJavaTypeAdapter(XmlSetStringAdapter.class) - private Set proxyExcludes; - - /** Field description */ - private String proxyPassword; - - /** Field description */ - private int proxyPort = 8080; - - /** Field description */ - private String proxyServer = "proxy.mydomain.com"; - - /** Field description */ - private String proxyUser; - - /** - * Skip failed authenticators. - * - * @since 1.36 - */ - @XmlElement(name = "skip-failed-authenticators") - private boolean skipFailedAuthenticators = false; - - /** Field description */ - @XmlElement(name = "plugin-url") - private String pluginUrl = DEFAULT_PLUGINURL; - - /** - * Login attempt timeout. - * - * @since 1.34 - */ - @XmlElement(name = "login-attempt-limit-timeout") - private long loginAttemptLimitTimeout = TimeUnit.MINUTES.toSeconds(5l); - - /** Field description */ - private boolean enableProxy = false; - - /** - * - * Authentication realm for basic authentication. - * - */ - private String realmDescription = HttpUtil.AUTHENTICATION_REALM; - - /** Field description */ - private boolean enableRepositoryArchive = false; - - /** Field description */ - private boolean disableGroupingGrid = false; - - /** - * JavaScript date format from moment.js - * @see http://momentjs.com/docs/#/parsing/ - */ - private String dateFormat = DEFAULT_DATEFORMAT; - - /** Field description */ - private boolean anonymousAccessEnabled = false; - - /** - * Enables xsrf cookie protection. - * - * @since 1.47 - */ - @XmlElement(name = "xsrf-protection") - private boolean enabledXsrfProtection = true; + public void setDefaultNamespaceStrategy(String defaultNamespaceStrategy) { + this.defaultNamespaceStrategy = defaultNamespaceStrategy; + } } diff --git a/scm-core/src/main/java/sonia/scm/group/GroupAlreadyExistsException.java b/scm-core/src/main/java/sonia/scm/group/GroupAlreadyExistsException.java index 8389900098..2b3c73535e 100644 --- a/scm-core/src/main/java/sonia/scm/group/GroupAlreadyExistsException.java +++ b/scm-core/src/main/java/sonia/scm/group/GroupAlreadyExistsException.java @@ -42,15 +42,9 @@ package sonia.scm.group; public class GroupAlreadyExistsException extends GroupException { - /** Field description */ private static final long serialVersionUID = 4042878550219750430L; - /** - * Constructs a new instance. - * - * @param message exception message - */ - public GroupAlreadyExistsException(String message) { - super(message); + public GroupAlreadyExistsException(Group group) { + super(group.getName() + " group already exists"); } } diff --git a/scm-core/src/main/java/sonia/scm/group/GroupNotFoundException.java b/scm-core/src/main/java/sonia/scm/group/GroupNotFoundException.java index f4b9934128..2ea5d16cf0 100644 --- a/scm-core/src/main/java/sonia/scm/group/GroupNotFoundException.java +++ b/scm-core/src/main/java/sonia/scm/group/GroupNotFoundException.java @@ -52,39 +52,7 @@ public class GroupNotFoundException extends GroupException * Constructs a new GroupNotFoundException. * */ - public GroupNotFoundException() {} - - /** - * Constructs a new GroupNotFoundException. - * - * - * @param message message for the exception - */ - public GroupNotFoundException(String message) - { - super(message); - } - - /** - * Constructs a new GroupNotFoundException. - * - * - * @param throwable root cause - */ - public GroupNotFoundException(Throwable throwable) - { - super(throwable); - } - - /** - * Constructs a new GroupNotFoundException. - * - * - * @param message message for the exception - * @param throwable root cause - */ - public GroupNotFoundException(String message, Throwable throwable) - { - super(message, throwable); + public GroupNotFoundException(Group group) { + super("group " + group.getName() + " does not exist"); } } diff --git a/scm-core/src/main/java/sonia/scm/repository/AbstactImportHandler.java b/scm-core/src/main/java/sonia/scm/repository/AbstactImportHandler.java index 2da506674d..6e0827af4a 100644 --- a/scm-core/src/main/java/sonia/scm/repository/AbstactImportHandler.java +++ b/scm-core/src/main/java/sonia/scm/repository/AbstactImportHandler.java @@ -36,19 +36,16 @@ package sonia.scm.repository; //~--- non-JDK imports -------------------------------------------------------- import com.google.common.base.Throwables; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import sonia.scm.repository.ImportResult.Builder; -//~--- JDK imports ------------------------------------------------------------ - import java.io.File; import java.io.IOException; - import java.util.List; +//~--- JDK imports ------------------------------------------------------------ + /** * Abstract base class for directory based {@link ImportHandler} and * {@link AdvancedImportHandler}. @@ -164,23 +161,24 @@ public abstract class AbstactImportHandler implements AdvancedImportHandler logger.trace("search for repositories to import"); - try - { - - List repositoryNames = - RepositoryUtil.getRepositoryNames(getRepositoryHandler(), - getDirectoryNames()); - - for (String repositoryName : repositoryNames) - { - importRepository(manager, builder, throwExceptions, repositoryName); - } - - } - catch (IOException ex) - { - handleException(ex, throwExceptions); - } + // TODO #8783 +// try +// { +// +// List repositoryNames = +// RepositoryUtil.getRepositoryNames(getRepositoryHandler(), +// getDirectoryNames()); +// +// for (String repositoryName : repositoryNames) +// { +// importRepository(manager, builder, throwExceptions, repositoryName); +// } +// +// } +// catch (IOException ex) +// { +// handleException(ex, throwExceptions); +// } return builder.build(); } @@ -214,46 +212,48 @@ public abstract class AbstactImportHandler implements AdvancedImportHandler * @param manager * @param builder * @param throwExceptions - * @param repositoryName + * @param directoryName * * @throws IOException * @throws RepositoryException */ private void importRepository(RepositoryManager manager, Builder builder, - boolean throwExceptions, String repositoryName) + boolean throwExceptions, String directoryName) throws IOException, RepositoryException { - logger.trace("check repository {} for import", repositoryName); + logger.trace("check repository {} for import", directoryName); - Repository repository = manager.get(getTypeName(), repositoryName); - - if (repository == null) - { - try - { - importRepository(manager, repositoryName); - builder.addImportedDirectory(repositoryName); - } - catch (IOException ex) - { - builder.addFailedDirectory(repositoryName); - handleException(ex, throwExceptions); - } - catch (IllegalStateException ex) - { - builder.addFailedDirectory(repositoryName); - handleException(ex, throwExceptions); - } - catch (RepositoryException ex) - { - builder.addFailedDirectory(repositoryName); - handleException(ex, throwExceptions); - } - } - else if (logger.isDebugEnabled()) - { - logger.debug("repository {} is allready managed", repositoryName); - } + // TODO #8783 +// +// Repository repository = manager.get(namespaceAndName); +// +// if (repository == null) +// { +// try +// { +// importRepository(manager, repositoryName); +// builder.addImportedDirectory(repositoryName); +// } +// catch (IOException ex) +// { +// builder.addFailedDirectory(repositoryName); +// handleException(ex, throwExceptions); +// } +// catch (IllegalStateException ex) +// { +// builder.addFailedDirectory(repositoryName); +// handleException(ex, throwExceptions); +// } +// catch (RepositoryException ex) +// { +// builder.addFailedDirectory(repositoryName); +// handleException(ex, throwExceptions); +// } +// } +// else if (logger.isDebugEnabled()) +// { +// logger.debug("repository {} is already managed", repositoryName); +// } } /** diff --git a/scm-core/src/main/java/sonia/scm/repository/AbstractSimpleRepositoryHandler.java b/scm-core/src/main/java/sonia/scm/repository/AbstractSimpleRepositoryHandler.java index 670cab93e1..aa28403116 100644 --- a/scm-core/src/main/java/sonia/scm/repository/AbstractSimpleRepositoryHandler.java +++ b/scm-core/src/main/java/sonia/scm/repository/AbstractSimpleRepositoryHandler.java @@ -1,19 +1,19 @@ /** * Copyright (c) 2010, Sebastian Sdorra * All rights reserved. - * + *

* Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + *

* 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. + * this list of conditions and the following disclaimer. * 2. 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. + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. * 3. Neither the name of SCM-Manager; nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * + * 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 @@ -24,13 +24,11 @@ * 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. - * + *

* http://bitbucket.org/sdorra/scm-manager - * */ - package sonia.scm.repository; //~--- non-JDK imports -------------------------------------------------------- @@ -38,181 +36,123 @@ package sonia.scm.repository; import com.google.common.base.Charsets; import com.google.common.base.Throwables; import com.google.common.io.Resources; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import sonia.scm.ConfigurationException; import sonia.scm.io.CommandResult; import sonia.scm.io.ExtendedCommand; import sonia.scm.io.FileSystem; +import sonia.scm.store.ConfigurationStoreFactory; import sonia.scm.util.IOUtil; -//~--- JDK imports ------------------------------------------------------------ - import java.io.File; import java.io.IOException; - import java.net.URL; -import sonia.scm.store.ConfigurationStoreFactory; + +//~--- JDK imports ------------------------------------------------------------ /** - * - * @author Sebastian Sdorra - * - * * @param + * @author Sebastian Sdorra */ public abstract class AbstractSimpleRepositoryHandler - extends AbstractRepositoryHandler implements RepositoryDirectoryHandler -{ + extends AbstractRepositoryHandler implements RepositoryDirectoryHandler { - /** Field description */ public static final String DEFAULT_VERSION_INFORMATION = "unknown"; - /** Field description */ public static final String DIRECTORY_REPOSITORY = "repositories"; - /** Field description */ public static final String DOT = "."; - /** the logger for AbstractSimpleRepositoryHandler */ + /** + * the logger for AbstractSimpleRepositoryHandler + */ private static final Logger logger = LoggerFactory.getLogger(AbstractSimpleRepositoryHandler.class); - //~--- constructors --------------------------------------------------------- + private FileSystem fileSystem; + - /** - * Constructs ... - * - * - * @param storeFactory - * @param fileSystem - */ public AbstractSimpleRepositoryHandler(ConfigurationStoreFactory storeFactory, - FileSystem fileSystem) - { + FileSystem fileSystem) { super(storeFactory); this.fileSystem = fileSystem; } - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param repository - * - * @throws IOException - * @throws RepositoryException - */ @Override - public void create(Repository repository) - throws RepositoryException, IOException - { + public Repository create(Repository repository) + throws RepositoryException { File directory = getDirectory(repository); - if (directory.exists()) - { + if (directory.exists()) { throw RepositoryAlreadyExistsException.create(repository); } checkPath(directory); - try - { + try { fileSystem.create(directory); create(repository, directory); postCreate(repository, directory); - } - catch (Exception ex) - { - if (directory.exists()) - { - if (logger.isDebugEnabled()) - { - logger.debug( - "delete repository directory {}, because of failed repository creation", - directory); + return repository; + } catch (Exception ex) { + if (directory.exists()) { + logger.warn("delete repository directory {}, because of failed repository creation", directory); + try { + fileSystem.destroy(directory); + } catch (IOException e) { + logger.error("Could not destroy directory", e); } - - fileSystem.destroy(directory); } - Throwables.propagateIfPossible(ex, RepositoryException.class, - IOException.class); + Throwables.propagateIfPossible(ex, RepositoryException.class); + // This point will never be reached + return null; } } - /** - * Method description - * - * - * - * @param repository - * @return - */ @Override - public String createResourcePath(Repository repository) - { + public String createResourcePath(Repository repository) { StringBuilder path = new StringBuilder("/"); - path.append(getType().getName()).append("/").append(repository.getName()); + path.append(getType().getName()).append("/").append(repository.getId()); return path.toString(); } - /** - * Method description - * - * - * @param repository - * - * @throws IOException - * @throws RepositoryException - */ @Override public void delete(Repository repository) - throws RepositoryException, IOException - { + throws RepositoryException { File directory = getDirectory(repository); - if (directory.exists()) - { - fileSystem.destroy(directory); + if (directory.exists()) { + try { + fileSystem.destroy(directory); + } catch (IOException e) { + throw new RepositoryException("could not delete repository", e); + } cleanupEmptyDirectories(config.getRepositoryDirectory(), - directory.getParentFile()); - } - else if (logger.isWarnEnabled()) - { - logger.warn("repository {} not found", repository); + directory.getParentFile()); + } else { + logger.warn("repository {} not found", repository.getNamespaceAndName()); } } - /** - * Method description - * - */ @Override - public void loadConfig() - { + public void loadConfig() { super.loadConfig(); - if (config == null) - { + if (config == null) { config = createInitialConfig(); - if (config != null) - { + if (config != null) { File repositoryDirectory = config.getRepositoryDirectory(); - if (repositoryDirectory == null) - { + if (repositoryDirectory == null) { repositoryDirectory = new File( - baseDirectory, - DIRECTORY_REPOSITORY.concat(File.separator).concat( - getType().getName())); + baseDirectory, + DIRECTORY_REPOSITORY.concat(File.separator).concat( + getType().getName())); config.setRepositoryDirectory(repositoryDirectory); } @@ -222,108 +162,51 @@ public abstract class AbstractSimpleRepositoryHandler { + + private final Set strategies; + private final ScmConfiguration scmConfiguration; + + @Inject + public NamespaceStrategyProvider(Set strategies, ScmConfiguration scmConfiguration) { + this.strategies = strategies; + this.scmConfiguration = scmConfiguration; + } + + @Override + public NamespaceStrategy get() { + String namespaceStrategy = scmConfiguration.getDefaultNamespaceStrategy(); + + for (NamespaceStrategy s : this.strategies) { + if (s.getClass().getCanonicalName().equals(namespaceStrategy)) { + return s; + } + } + return null; + } + +} diff --git a/scm-core/src/main/java/sonia/scm/repository/Repository.java b/scm-core/src/main/java/sonia/scm/repository/Repository.java index b0a976db55..44841893e7 100644 --- a/scm-core/src/main/java/sonia/scm/repository/Repository.java +++ b/scm-core/src/main/java/sonia/scm/repository/Repository.java @@ -33,30 +33,25 @@ package sonia.scm.repository; -//~--- non-JDK imports -------------------------------------------------------- - import com.github.sdorra.ssp.PermissionObject; import com.github.sdorra.ssp.StaticPermissions; import com.google.common.base.Objects; import com.google.common.collect.Lists; - import sonia.scm.BasicPropertiesAware; import sonia.scm.ModelObject; import sonia.scm.util.HttpUtil; import sonia.scm.util.Util; import sonia.scm.util.ValidationUtil; -//~--- JDK imports ------------------------------------------------------------ - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlTransient; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; /** * Source code repository. @@ -64,90 +59,270 @@ import javax.xml.bind.annotation.XmlRootElement; * @author Sebastian Sdorra */ @StaticPermissions( - value = "repository", + value = "repository", permissions = {"read", "write", "modify", "delete", "healthCheck"} ) @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "repositories") -public class Repository extends BasicPropertiesAware implements ModelObject, PermissionObject -{ +public class Repository extends BasicPropertiesAware implements ModelObject, PermissionObject { + - /** Field description */ private static final long serialVersionUID = 3486560714961909711L; - //~--- constructors --------------------------------------------------------- + private String contact; + private Long creationDate; + private String description; + @XmlElement(name = "healthCheckFailure") + @XmlElementWrapper(name = "healthCheckFailures") + private List healthCheckFailures; + private String id; + private Long lastModified; + private String namespace; + private String name; + private List permissions; + @XmlElement(name = "public") + private boolean publicReadable = false; + private boolean archived = false; + private String type; + /** * Constructs a new {@link Repository}. * This constructor is used by JAXB. - * */ - public Repository() {} + public Repository() { + } /** * Constructs a new {@link Repository}. * - * - * - * @param id id of the {@link Repository} + * @param id id of the {@link Repository} * @param type type of the {@link Repository} * @param name name of the {@link Repository} */ - public Repository(String id, String type, String name) - { + public Repository(String id, String type, String namespace, String name) { this.id = id; this.type = type; + this.namespace = namespace; this.name = name; } /** * Constructs a new {@link Repository}. * - * - * - * @param id id of the {@link Repository} - * @param type type of the {@link Repository} - * @param name name of the {@link Repository} - * @param contact email address of a person who is responsible for - * this repository. + * @param id id of the {@link Repository} + * @param type type of the {@link Repository} + * @param name name of the {@link Repository} + * @param namespace namespace of the {@link Repository} + * @param contact email address of a person who is responsible for + * this repository. * @param description a short description of the repository * @param permissions permissions for specific users and groups. */ - public Repository(String id, String type, String name, String contact, - String description, Permission... permissions) - { + public Repository(String id, String type, String namespace, String name, String contact, + String description, Permission... permissions) { this.id = id; this.type = type; + this.namespace = namespace; this.name = name; this.contact = contact; this.description = description; this.permissions = Lists.newArrayList(); - if (Util.isNotEmpty(permissions)) - { + if (Util.isNotEmpty(permissions)) { this.permissions.addAll(Arrays.asList(permissions)); } } - //~--- methods -------------------------------------------------------------- + /** + * Returns a contact email address of a person who is responsible for + * the {@link Repository}. + * + * @return contact email address + */ + public String getContact() { + return contact; + } /** - * Create a clone of this {@link Repository} object. + * Returns a timestamp of the creation date of the {@link Repository}. * + * @return a timestamp of the creation date of the {@link Repository} + */ + public Long getCreationDate() { + return creationDate; + } + + /** + * Returns a short description of the {@link Repository}. * - * @return clone of this {@link Repository} + * @return short description + */ + public String getDescription() { + return description; + } + + /** + * Returns a {@link List} of {@link HealthCheckFailure}s. The {@link List} + * is empty if the repository is healthy. + * + * @return {@link List} of {@link HealthCheckFailure}s + * @since 1.36 + */ + @SuppressWarnings("unchecked") + public List getHealthCheckFailures() { + if (healthCheckFailures == null) { + healthCheckFailures = Collections.EMPTY_LIST; + } + + return healthCheckFailures; + } + + @Override + public String getId() { + return id; + } + + @Override + public Long getLastModified() { + return lastModified; + } + + + public String getName() { + return name; + } + + public String getNamespace() { return namespace; } + + @XmlTransient + public NamespaceAndName getNamespaceAndName() { + return new NamespaceAndName(getNamespace(), getName()); + } + + public List getPermissions() { + if (permissions == null) { + permissions = Lists.newArrayList(); + } + + return permissions; + } + + /** + * Returns the type (hg, git, svn ...) of the {@link Repository}. + * + * @return type of the repository */ @Override - public Repository clone() - { + public String getType() { + return type; + } + + /** + * Returns true if the repository is archived. + * + * @return true if the repository is archived + * @since 1.14 + */ + public boolean isArchived() { + return archived; + } + + /** + * Returns {@code true} if the repository is healthy. + * + * @return {@code true} if the repository is healthy + * @since 1.36 + */ + public boolean isHealthy() { + return Util.isEmpty(healthCheckFailures); + } + + /** + * Returns true if the {@link Repository} is public readable. + * + * @return true if the {@link Repository} is public readable + */ + public boolean isPublicReadable() { + return publicReadable; + } + + /** + * Returns true if the {@link Repository} is valid. + *

    + *
  • The name is not empty and contains only A-z, 0-9, _, -, /
  • + *
  • The type is not empty
  • + *
  • The contact is empty or contains a valid email address
  • + *
+ * + * @return true if the {@link Repository} is valid + */ + @Override + public boolean isValid() { + return ValidationUtil.isRepositoryNameValid(name) && Util.isNotEmpty(type) + && ((Util.isEmpty(contact)) + || ValidationUtil.isMailAddressValid(contact)); + } + + /** + * Archive or un archive this repository. + * + * @param archived true to enable archive + * @since 1.14 + */ + public void setArchived(boolean archived) { + this.archived = archived; + } + + public void setContact(String contact) { + this.contact = contact; + } + + public void setCreationDate(Long creationDate) { + this.creationDate = creationDate; + } + + public void setDescription(String description) { + this.description = description; + } + + public void setId(String id) { + this.id = id; + } + + public void setLastModified(Long lastModified) { + this.lastModified = lastModified; + } + + public void setNamespace(String namespace) { this.namespace = namespace; } + + public void setName(String name) { + this.name = name; + } + + public void setPermissions(List permissions) { + this.permissions = permissions; + } + + public void setPublicReadable(boolean publicReadable) { + this.publicReadable = publicReadable; + } + + public void setType(String type) { + this.type = type; + } + + public void setHealthCheckFailures(List healthCheckFailures) { + this.healthCheckFailures = healthCheckFailures; + } + + @Override + public Repository clone() { Repository repository = null; - try - { + try { repository = (Repository) super.clone(); - } - catch (CloneNotSupportedException ex) - { + } catch (CloneNotSupportedException ex) { throw new RuntimeException(ex); } @@ -157,11 +332,10 @@ public class Repository extends BasicPropertiesAware implements ModelObject, Per /** * Copies all properties of the {@link Repository} to the given one. * - * - * @param repository to copies all properties of this one + * @param repository the target {@link Repository} */ - public void copyProperties(Repository repository) - { + public void copyProperties(Repository repository) { + repository.setNamespace(namespace); repository.setName(name); repository.setContact(contact); repository.setCreationDate(creationDate); @@ -177,436 +351,70 @@ public class Repository extends BasicPropertiesAware implements ModelObject, Per /** * Creates the url of the repository. * - * * @param baseUrl base url of the server including the context path - * * @return url of the repository * @since 1.17 */ - public String createUrl(String baseUrl) - { - String url = HttpUtil.append(baseUrl, type); - - return HttpUtil.append(url, name); + public String createUrl(String baseUrl) { + return HttpUtil.concatenate(baseUrl, type, namespace, name); } /** * Returns true if the {@link Repository} is the same as the obj argument. * - * * @param obj the reference object with which to compare - * * @return true if the {@link Repository} is the same as the obj argument */ @Override - public boolean equals(Object obj) - { - if (obj == null) - { + public boolean equals(Object obj) { + if (obj == null) { return false; } - if (getClass() != obj.getClass()) - { + if (getClass() != obj.getClass()) { return false; } final Repository other = (Repository) obj; - //J- - return Objects.equal(id, other.id) - && Objects.equal(name, other.name) - && Objects.equal(contact, other.contact) - && Objects.equal(description, other.description) - && Objects.equal(publicReadable, other.publicReadable) - && Objects.equal(archived, other.archived) - && Objects.equal(permissions, other.permissions) - && Objects.equal(type, other.type) - && Objects.equal(creationDate, other.creationDate) - && Objects.equal(lastModified, other.lastModified) - && Objects.equal(properties, other.properties) - && Objects.equal(healthCheckFailures, other.healthCheckFailures); - //J+ + return Objects.equal(id, other.id) + && Objects.equal(namespace, other.namespace) + && Objects.equal(name, other.name) + && Objects.equal(contact, other.contact) + && Objects.equal(description, other.description) + && Objects.equal(publicReadable, other.publicReadable) + && Objects.equal(archived, other.archived) + && Objects.equal(permissions, other.permissions) + && Objects.equal(type, other.type) + && Objects.equal(creationDate, other.creationDate) + && Objects.equal(lastModified, other.lastModified) + && Objects.equal(properties, other.properties) + && Objects.equal(healthCheckFailures, other.healthCheckFailures); } - /** - * Returns the hash code value for the {@link Repository}. - * - * - * @return the hash code value for the {@link Repository} - */ @Override - public int hashCode() - { - return Objects.hashCode(id, name, contact, description, publicReadable, + public int hashCode() { + return Objects.hashCode(id, namespace, name, contact, description, publicReadable, archived, permissions, type, creationDate, lastModified, properties, healthCheckFailures); } - /** - * Returns a {@link String} that represents the {@link Repository}. - * - * - * @return {@link String} that represents the {@link Repository} - */ @Override - public String toString() - { - //J- + public String toString() { return Objects.toStringHelper(this) - .add("id", id) - .add("name", name) - .add("contact", contact) - .add("description", description) - .add("publicReadable", publicReadable) - .add("archived", archived) - .add("permissions", permissions) - .add("type", type) - .add("lastModified", lastModified) - .add("creationDate", creationDate) - .add("properties", properties) - .add("healthCheckFailures", healthCheckFailures) - .toString(); - //J+ + .add("id", id) + .add("namespace", namespace) + .add("name", name) + .add("contact", contact) + .add("description", description) + .add("publicReadable", publicReadable) + .add("archived", archived) + .add("permissions", permissions) + .add("type", type) + .add("lastModified", lastModified) + .add("creationDate", creationDate) + .add("properties", properties) + .add("healthCheckFailures", healthCheckFailures) + .toString(); } - - //~--- get methods ---------------------------------------------------------- - - /** - * Returns a contact email address of a person who is responsible for - * the {@link Repository}. - * - * - * @return contact email address - */ - public String getContact() - { - return contact; - } - - /** - * Returns a timestamp of the creation date of the {@link Repository}. - * - * - * @return a timestamp of the creation date of the {@link Repository} - */ - public Long getCreationDate() - { - return creationDate; - } - - /** - * Returns a short description of the {@link Repository}. - * - * - * @return short description - */ - public String getDescription() - { - return description; - } - - /** - * Returns a {@link List} of {@link HealthCheckFailure}s. The {@link List} - * is empty if the repository is healthy. - * - * - * @return {@link List} of {@link HealthCheckFailure}s - * @since 1.36 - */ - @SuppressWarnings("unchecked") - public List getHealthCheckFailures() - { - if (healthCheckFailures == null) - { - healthCheckFailures = Collections.EMPTY_LIST; - } - - return healthCheckFailures; - } - - /** - * Returns the unique id of the {@link Repository}. - * - * - * @return unique id - */ - @Override - public String getId() - { - return id; - } - - /** - * Returns the timestamp of the last modified date of the {@link Repository}. - * - * - * @return timestamp of the last modified date - */ - @Override - public Long getLastModified() - { - return lastModified; - } - - /** - * Returns the name of the {@link Repository}. - * - * - * @return name of the {@link Repository} - */ - public String getName() - { - return name; - } - - /** - * Returns the access permissions of the {@link Repository}. - * - * - * @return access permissions - */ - public List getPermissions() - { - if (permissions == null) - { - permissions = Lists.newArrayList(); - } - - return permissions; - } - - /** - * Returns the type (hg, git, svn ...) of the {@link Repository}. - * - * - * @return type of the repository - */ - @Override - public String getType() - { - return type; - } - - /** - * Returns true if the repository is archived. - * - * - * @return true if the repository is archived - * @since 1.14 - */ - public boolean isArchived() - { - return archived; - } - - /** - * Returns {@code true} if the repository is healthy. - * - * - * @return {@code true} if the repository is healthy - * - * @since 1.36 - */ - public boolean isHealthy() - { - return Util.isEmpty(healthCheckFailures); - } - - /** - * Returns true if the {@link Repository} is public readable. - * - * - * @return true if the {@link Repository} is public readable - */ - public boolean isPublicReadable() - { - return publicReadable; - } - - /** - * Returns true if the {@link Repository} is valid. - *
    - *
  • The name is not empty and contains only A-z, 0-9, _, -, /
  • - *
  • The type is not empty
  • - *
  • The contact is empty or contains a valid email address
  • - *
- * - * - * @return true if the {@link Repository} is valid - */ - @Override - public boolean isValid() - { - return ValidationUtil.isRepositoryNameValid(name) && Util.isNotEmpty(type) - && ((Util.isEmpty(contact)) - || ValidationUtil.isMailAddressValid(contact)); - } - - //~--- set methods ---------------------------------------------------------- - - /** - * Archive or un archive this repository. - * - * - * @param archived true to enable archive - * @since 1.14 - */ - public void setArchived(boolean archived) - { - this.archived = archived; - } - - /** - * Sets the contact of the {@link Repository}. The contact address should be - * a email address of a person who is responsible for the {@link Repository}. - * - * - * @param contact email address of a person who is responsible for - * the {@link Repository} - */ - public void setContact(String contact) - { - this.contact = contact; - } - - /** - * Set the creation date of the {@link Repository}. - * - * - * @param creationDate creation date of the {@link Repository} - */ - public void setCreationDate(Long creationDate) - { - this.creationDate = creationDate; - } - - /** - * Sets a short description of the {@link Repository}. - * - * - * @param description short description - */ - public void setDescription(String description) - { - this.description = description; - } - - /** - * The unique id of the {@link Repository}. - * - * - * @param id unique id - */ - public void setId(String id) - { - this.id = id; - } - - /** - * Set the last modified timestamp of the {@link Repository}. - * - * - * @param lastModified last modified timestamp - */ - public void setLastModified(Long lastModified) - { - this.lastModified = lastModified; - } - - /** - * Set the name of the {@link Repository}. - * - * - * @param name name of the {@link Repository} - */ - public void setName(String name) - { - this.name = name; - } - - /** - * Set the access permissions for the {@link Repository}. - * - * - * @param permissions list of access permissions - */ - public void setPermissions(List permissions) - { - this.permissions = permissions; - } - - /** - * Sets true if the {@link Repository} is public readable. - * - * - * @param publicReadable public readable - */ - public void setPublicReadable(boolean publicReadable) - { - this.publicReadable = publicReadable; - } - - /** - * Sets the type (hg, svn, git ...) of the {@link Repository}. - * - * - * @param type type of the {@link Repository} - */ - public void setType(String type) - { - this.type = type; - } - - /** - * Sets {@link HealthCheckFailure} for a unhealthy repository. - * - * @param healthCheckFailures list of {@link HealthCheckFailure}s - * - * @since 1.36 - */ - public void setHealthCheckFailures(List healthCheckFailures) - { - this.healthCheckFailures = healthCheckFailures; - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private String contact; - - /** Field description */ - private Long creationDate; - - /** Field description */ - private String description; - - /** - * @since 1.36 - */ - @XmlElement(name = "healthCheckFailure") - @XmlElementWrapper(name = "healthCheckFailures") - private List healthCheckFailures; - - /** Field description */ - private String id; - - /** Field description */ - private Long lastModified; - - /** Field description */ - private String name; - - /** Field description */ - private List permissions; - - /** Field description */ - @XmlElement(name = "public") - private boolean publicReadable = false; - - /** Field description */ - private boolean archived = false; - - /** Field description */ - private String type; } diff --git a/scm-core/src/main/java/sonia/scm/repository/RepositoryDAO.java b/scm-core/src/main/java/sonia/scm/repository/RepositoryDAO.java index 9a2d4b5662..ce309ecee6 100644 --- a/scm-core/src/main/java/sonia/scm/repository/RepositoryDAO.java +++ b/scm-core/src/main/java/sonia/scm/repository/RepositoryDAO.java @@ -49,27 +49,22 @@ public interface RepositoryDAO extends GenericDAO /** * Returns true if a repository with specified - * type and name exists in the backend. + * namespace and name exists in the backend. * * - * @param type type of the repository - * @param name name of the repository + * @param namespaceAndName namespace and name of the repository * * @return true if the repository exists */ - public boolean contains(String type, String name); + boolean contains(NamespaceAndName namespaceAndName); //~--- get methods ---------------------------------------------------------- /** - * Returns the repository with the specified type and name or null + * Returns the repository with the specified namespace and name or null * if no such repository exists in the backend. * - * - * @param type - * @param name - * - * @return repository with the specified type and name or null + * @return repository with the specified namespace and name or null */ - public Repository get(String type, String name); + Repository get(NamespaceAndName namespaceAndName); } diff --git a/scm-core/src/main/java/sonia/scm/repository/RepositoryDirectoryHandler.java b/scm-core/src/main/java/sonia/scm/repository/RepositoryDirectoryHandler.java index 3fda4a76be..2f766fb1f6 100644 --- a/scm-core/src/main/java/sonia/scm/repository/RepositoryDirectoryHandler.java +++ b/scm-core/src/main/java/sonia/scm/repository/RepositoryDirectoryHandler.java @@ -43,13 +43,5 @@ import java.io.File; public interface RepositoryDirectoryHandler extends RepositoryHandler { - /** - * Method description - * - * - * @param repository - * - * @return - */ public File getDirectory(Repository repository); } diff --git a/scm-core/src/main/java/sonia/scm/repository/RepositoryManager.java b/scm-core/src/main/java/sonia/scm/repository/RepositoryManager.java index 7cbac2b52e..493d8f6dbb 100644 --- a/scm-core/src/main/java/sonia/scm/repository/RepositoryManager.java +++ b/scm-core/src/main/java/sonia/scm/repository/RepositoryManager.java @@ -38,13 +38,12 @@ package sonia.scm.repository; import sonia.scm.Type; import sonia.scm.TypeManager; -//~--- JDK imports ------------------------------------------------------------ - -import java.io.IOException; - -import java.util.Collection; - import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.Collection; +import java.util.Optional; + +//~--- JDK imports ------------------------------------------------------------ /** * The central class for managing {@link Repository} objects. @@ -83,18 +82,17 @@ public interface RepositoryManager //~--- get methods ---------------------------------------------------------- /** - * Returns a {@link Repository} by its type and name or + * Returns a {@link Repository} by its namespace and name or * null if the {@link Repository} could not be found. * * - * @param type type of the {@link Repository} - * @param name name of the {@link Repository} + * @param namespaceAndName namespace and name of the {@link Repository} * * - * @return {@link Repository} by its type and name or null + * @return {@link Repository} by its namespace and name or null * if the {@link Repository} could not be found */ - public Repository get(String type, String name); + public Repository get(NamespaceAndName namespaceAndName); /** * Returns all configured repository types. @@ -115,18 +113,6 @@ public interface RepositoryManager */ public Repository getFromRequest(HttpServletRequest request); - /** - * Returns the {@link Repository} associated to the given type and path. - * - * - * @param type type of the repository (hg, git ...) - * @param uri - * - * @return the {@link Repository} associated to the given type and path - * @since 1.9 - */ - public Repository getFromTypeAndUri(String type, String uri); - /** * Returns the {@link Repository} associated to the request uri. * @@ -149,4 +135,11 @@ public interface RepositoryManager */ @Override public RepositoryHandler getHandler(String type); + + default Optional getByNamespace(String namespace, String name) { + return getAll() + .stream() + .filter(r -> r.getName().equals(name) && r.getNamespace().equals(namespace)) + .findFirst(); + } } diff --git a/scm-core/src/main/java/sonia/scm/repository/RepositoryManagerDecorator.java b/scm-core/src/main/java/sonia/scm/repository/RepositoryManagerDecorator.java index 632b54b741..6990baf7c5 100644 --- a/scm-core/src/main/java/sonia/scm/repository/RepositoryManagerDecorator.java +++ b/scm-core/src/main/java/sonia/scm/repository/RepositoryManagerDecorator.java @@ -38,13 +38,11 @@ package sonia.scm.repository; import sonia.scm.ManagerDecorator; import sonia.scm.Type; -//~--- JDK imports ------------------------------------------------------------ - +import javax.servlet.http.HttpServletRequest; import java.io.IOException; - import java.util.Collection; -import javax.servlet.http.HttpServletRequest; +//~--- JDK imports ------------------------------------------------------------ /** * Decorator for {@link RepositoryManager}. @@ -92,19 +90,10 @@ public class RepositoryManagerDecorator //~--- get methods ---------------------------------------------------------- - /** - * {@inheritDoc} - * - * - * @param type - * @param name - * - * @return - */ @Override - public Repository get(String type, String name) + public Repository get(NamespaceAndName namespaceAndName) { - return decorated.get(type, name); + return decorated.get(namespaceAndName); } /** @@ -146,21 +135,6 @@ public class RepositoryManagerDecorator return decorated.getFromRequest(request); } - /** - * {@inheritDoc} - * - * - * @param type - * @param uri - * - * @return - */ - @Override - public Repository getFromTypeAndUri(String type, String uri) - { - return decorated.getFromTypeAndUri(type, uri); - } - /** * {@inheritDoc} * diff --git a/scm-core/src/main/java/sonia/scm/repository/RepositoryNotFoundException.java b/scm-core/src/main/java/sonia/scm/repository/RepositoryNotFoundException.java index f1649efb43..11f1a98bfd 100644 --- a/scm-core/src/main/java/sonia/scm/repository/RepositoryNotFoundException.java +++ b/scm-core/src/main/java/sonia/scm/repository/RepositoryNotFoundException.java @@ -52,17 +52,11 @@ public class RepositoryNotFoundException extends RepositoryException * error detail message. * */ - public RepositoryNotFoundException() {} + public RepositoryNotFoundException(Repository repository) { + super("repository " + repository.getName() + "/" + repository.getNamespace() + " does not exist"); + } - /** - * Constructs a new {@link RepositoryNotFoundException} with the specified - * error detail message. - * - * - * @param message error detail message - */ - public RepositoryNotFoundException(String message) - { - super(message); + public RepositoryNotFoundException(String repositoryId) { + super("repository with id " + repositoryId + " does not exist"); } } diff --git a/scm-core/src/main/java/sonia/scm/repository/RepositoryUtil.java b/scm-core/src/main/java/sonia/scm/repository/RepositoryUtil.java index e271992248..0be291d4e1 100644 --- a/scm-core/src/main/java/sonia/scm/repository/RepositoryUtil.java +++ b/scm-core/src/main/java/sonia/scm/repository/RepositoryUtil.java @@ -35,278 +35,86 @@ package sonia.scm.repository; //~--- non-JDK imports -------------------------------------------------------- -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import com.google.common.base.Preconditions; import sonia.scm.io.DirectoryFileFilter; import sonia.scm.util.IOUtil; -//~--- JDK imports ------------------------------------------------------------ - import java.io.File; import java.io.IOException; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; +//~--- JDK imports ------------------------------------------------------------ + /** * * @author Sebastian Sdorra * @since 1.11 */ -public final class RepositoryUtil -{ +public final class RepositoryUtil { - /** the logger for RepositoryUtil */ - private static final Logger logger = - LoggerFactory.getLogger(RepositoryUtil.class); - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - */ private RepositoryUtil() {} - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param directory - * @param names - * - * @return - */ - public static List searchRepositoryDirectories(File directory, - String... names) - { - List repositories = new ArrayList(); + public static List searchRepositoryDirectories(File directory, String... names) { + List repositories = new ArrayList<>(); searchRepositoryDirectories(repositories, directory, Arrays.asList(names)); return repositories; } - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * - * @param handler - * @param directoryPath - * @return - * - * @throws IOException - */ - public static String getRepositoryName(AbstractRepositoryHandler handler, - String directoryPath) - throws IOException - { - return getRepositoryName(handler.getConfig().getRepositoryDirectory(), - new File(directoryPath)); + @SuppressWarnings("squid:S2083") // ignore, because the path is validated at {@link #getRepositoryId(File, File)} + public static String getRepositoryId(AbstractRepositoryHandler handler, String directoryPath) throws IOException { + return getRepositoryId(handler.getConfig().getRepositoryDirectory(), new File(directoryPath)); } - /** - * Method description - * - * - * - * @param config - * @param directoryPath - * @return - * - * @throws IOException - */ - public static String getRepositoryName(SimpleRepositoryConfig config, - String directoryPath) - throws IOException - { - return getRepositoryName(config.getRepositoryDirectory(), - new File(directoryPath)); + public static String getRepositoryId(AbstractRepositoryHandler handler, File directory) throws IOException { + return getRepositoryId(handler.getConfig(), directory); } - /** - * Method description - * - * - * - * @param handler - * @param directory - * @return - * - * @throws IOException - */ - public static String getRepositoryName(AbstractRepositoryHandler handler, - File directory) - throws IOException - { - return getRepositoryName(handler.getConfig().getRepositoryDirectory(), - directory); + public static String getRepositoryId(SimpleRepositoryConfig config, File directory) throws IOException { + return getRepositoryId(config.getRepositoryDirectory(), directory); } - /** - * Method description - * - * - * - * @param config - * @param directory - * @return - * - * @throws IOException - */ - public static String getRepositoryName(SimpleRepositoryConfig config, - File directory) - throws IOException - { - return getRepositoryName(config.getRepositoryDirectory(), directory); - } - - /** - * Method description - * - * - * - * @param baseDirectory - * @param directory - * @return - * - * @throws IOException - */ - public static String getRepositoryName(File baseDirectory, File directory) - throws IOException - { - String name = null; + public static String getRepositoryId(File baseDirectory, File directory) throws IOException { String path = directory.getCanonicalPath(); - int directoryLength = baseDirectory.getCanonicalPath().length(); + String basePath = baseDirectory.getCanonicalPath(); - if (directoryLength < path.length()) - { - name = IOUtil.trimSeperatorChars(path.substring(directoryLength)); + Preconditions.checkArgument( + path.startsWith(basePath), + "repository path %s is not in the main repository path %s", path, basePath + ); - // replace windows path seperator - name = name.replaceAll("\\\\", "/"); - } - else if (logger.isWarnEnabled()) - { - logger.warn("path is shorter as the main repository path"); - } + String id = IOUtil.trimSeperatorChars(path.substring(basePath.length())); - return name; + Preconditions.checkArgument( + !id.contains("\\") && !id.contains("/"), + "got illegal repository directory with separators in id: %s", path + ); + + return id; } - /** - * Method description - * - * - * @param handler - * @param directoryNames - * - * @return - * - * @throws IOException - */ - public static List getRepositoryNames( - AbstractRepositoryHandler handler, String... directoryNames) - throws IOException - { - return getRepositoryNames(handler.getConfig(), directoryNames); - } - - /** - * Method description - * - * - * @param config - * @param directoryNames - * - * @return - * - * @throws IOException - */ - public static List getRepositoryNames(SimpleRepositoryConfig config, - String... directoryNames) - throws IOException - { - return getRepositoryNames(config.getRepositoryDirectory(), directoryNames); - } - - /** - * Method description - * - * - * @param baseDirectory - * @param directoryNames - * - * @return - * - * @throws IOException - */ - public static List getRepositoryNames(File baseDirectory, - String... directoryNames) - throws IOException - { - List repositories = new ArrayList(); - List repositoryFiles = searchRepositoryDirectories(baseDirectory, - directoryNames); - - for (File file : repositoryFiles) - { - String name = getRepositoryName(baseDirectory, file); - - if (name != null) - { - repositories.add(name); - } - } - - return repositories; - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param repositories - * @param directory - * @param names - */ - private static void searchRepositoryDirectories(List repositories, - File directory, List names) - { + private static void searchRepositoryDirectories(List repositories, File directory, List names) { boolean found = false; - for (String name : names) - { - if (new File(directory, name).exists()) - { + for (String name : names) { + if (new File(directory, name).exists()) { found = true; break; } } - if (found) - { + if (found) { repositories.add(directory); - } - else - { + } else { File[] directories = directory.listFiles(DirectoryFileFilter.instance); - if (directories != null) - { - for (File d : directories) - { + if (directories != null) { + for (File d : directories) { searchRepositoryDirectories(repositories, d, names); } } diff --git a/scm-core/src/main/java/sonia/scm/repository/api/RepositoryServiceFactory.java b/scm-core/src/main/java/sonia/scm/repository/api/RepositoryServiceFactory.java index e07eee44f0..2e4ff644f4 100644 --- a/scm-core/src/main/java/sonia/scm/repository/api/RepositoryServiceFactory.java +++ b/scm-core/src/main/java/sonia/scm/repository/api/RepositoryServiceFactory.java @@ -37,20 +37,20 @@ package sonia.scm.repository.api; import com.github.legman.ReferenceType; import com.github.legman.Subscribe; - import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.google.inject.Singleton; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import sonia.scm.HandlerEventType; import sonia.scm.cache.Cache; import sonia.scm.cache.CacheManager; import sonia.scm.config.ScmConfiguration; +import sonia.scm.event.ScmEventBus; +import sonia.scm.repository.ClearRepositoryCacheEvent; +import sonia.scm.repository.NamespaceAndName; import sonia.scm.repository.PostReceiveRepositoryHookEvent; import sonia.scm.repository.PreProcessorUtil; import sonia.scm.repository.Repository; @@ -63,11 +63,9 @@ import sonia.scm.repository.spi.RepositoryServiceProvider; import sonia.scm.repository.spi.RepositoryServiceResolver; import sonia.scm.security.ScmSecurityException; -//~--- JDK imports ------------------------------------------------------------ - import java.util.Set; -import sonia.scm.event.ScmEventBus; -import sonia.scm.repository.ClearRepositoryCacheEvent; + +//~--- JDK imports ------------------------------------------------------------ /** * The {@link RepositoryServiceFactory} is the entrypoint of the repository api. @@ -179,8 +177,7 @@ public final class RepositoryServiceFactory if (repository == null) { - throw new RepositoryNotFoundException( - "could not find a repository with id ".concat(repositoryId)); + throw new RepositoryNotFoundException(repositoryId); } return create(repository); @@ -190,8 +187,7 @@ public final class RepositoryServiceFactory * Creates a new RepositoryService for the given repository. * * - * @param type type of the repository - * @param name name of the repository + * @param namespaceAndName namespace and name of the repository * * @return a implementation of RepositoryService * for the given type of repository @@ -204,24 +200,19 @@ public final class RepositoryServiceFactory * @throws ScmSecurityException if current user has not read permissions * for that repository */ - public RepositoryService create(String type, String name) + public RepositoryService create(NamespaceAndName namespaceAndName) throws RepositoryNotFoundException { - Preconditions.checkArgument(!Strings.isNullOrEmpty(type), - "a non empty type is required"); - Preconditions.checkArgument(!Strings.isNullOrEmpty(name), - "a non empty name is required"); + Preconditions.checkArgument(namespaceAndName != null, + "a non empty namespace and name is required"); - Repository repository = repositoryManager.get(type, name); + Repository repository = repositoryManager.get(namespaceAndName); if (repository == null) { - StringBuilder msg = - new StringBuilder("could not find a repository with type "); + String msg = "could not find a repository with namespace/name " + namespaceAndName; - msg.append(type).append(" and name ").append(name); - - throw new RepositoryNotFoundException(msg.toString()); + throw new RepositoryNotFoundException(msg); } return create(repository); @@ -253,7 +244,7 @@ public final class RepositoryServiceFactory for (RepositoryServiceResolver resolver : resolvers) { - RepositoryServiceProvider provider = resolver.reslove(repository); + RepositoryServiceProvider provider = resolver.resolve(repository); if (provider != null) { diff --git a/scm-core/src/main/java/sonia/scm/repository/spi/HookEventFacade.java b/scm-core/src/main/java/sonia/scm/repository/spi/HookEventFacade.java index 899892a5b7..93ed5f1111 100644 --- a/scm-core/src/main/java/sonia/scm/repository/spi/HookEventFacade.java +++ b/scm-core/src/main/java/sonia/scm/repository/spi/HookEventFacade.java @@ -35,7 +35,7 @@ package sonia.scm.repository.spi; import com.google.inject.Inject; import com.google.inject.Provider; - +import sonia.scm.repository.NamespaceAndName; import sonia.scm.repository.Repository; import sonia.scm.repository.RepositoryException; import sonia.scm.repository.RepositoryHookEvent; @@ -72,50 +72,15 @@ public final class HookEventFacade //~--- methods -------------------------------------------------------------- - /** - * Method description - * - * - * @param id - * - * @return - * - * @throws RepositoryException - */ - public HookEventHandler handle(String id) throws RepositoryException - { + public HookEventHandler handle(String id) throws RepositoryException { return handle(repositoryManagerProvider.get().get(id)); } - /** - * Method description - * - * - * @param type - * @param repositoryName - * - * @return - * - * @throws RepositoryException - */ - public HookEventHandler handle(String type, String repositoryName) - throws RepositoryException - { - return handle(repositoryManagerProvider.get().get(type, repositoryName)); + public HookEventHandler handle(NamespaceAndName namespaceAndName) throws RepositoryException { + return handle(repositoryManagerProvider.get().get(namespaceAndName)); } - /** - * Method description - * - * - * @param repository - * - * @return - * - * @throws RepositoryException - */ - public HookEventHandler handle(Repository repository) - throws RepositoryException + public HookEventHandler handle(Repository repository) throws RepositoryException { if (repository == null) { diff --git a/scm-core/src/main/java/sonia/scm/repository/spi/RepositoryServiceResolver.java b/scm-core/src/main/java/sonia/scm/repository/spi/RepositoryServiceResolver.java index f0ed4c0814..d747bbdce0 100644 --- a/scm-core/src/main/java/sonia/scm/repository/spi/RepositoryServiceResolver.java +++ b/scm-core/src/main/java/sonia/scm/repository/spi/RepositoryServiceResolver.java @@ -33,8 +33,6 @@ package sonia.scm.repository.spi; -//~--- non-JDK imports -------------------------------------------------------- - import sonia.scm.plugin.ExtensionPoint; import sonia.scm.repository.Repository; @@ -55,5 +53,5 @@ public interface RepositoryServiceResolver * * @return */ - public RepositoryServiceProvider reslove(Repository repository); + public RepositoryServiceProvider resolve(Repository repository); } diff --git a/scm-core/src/main/java/sonia/scm/security/SyncingRealmHelper.java b/scm-core/src/main/java/sonia/scm/security/SyncingRealmHelper.java index 4c5b5c4e53..9e0c97f234 100644 --- a/scm-core/src/main/java/sonia/scm/security/SyncingRealmHelper.java +++ b/scm-core/src/main/java/sonia/scm/security/SyncingRealmHelper.java @@ -30,12 +30,10 @@ package sonia.scm.security; import com.google.common.collect.ImmutableList; import com.google.inject.Inject; - import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.subject.SimplePrincipalCollection; - import sonia.scm.group.Group; import sonia.scm.group.GroupException; import sonia.scm.group.GroupManager; @@ -46,9 +44,6 @@ import sonia.scm.user.UserException; import sonia.scm.user.UserManager; import sonia.scm.web.security.AdministrationContext; - -import java.io.IOException; - import java.util.Collection; /** @@ -134,7 +129,7 @@ public final class SyncingRealmHelper { groupManager.create(group); } } - catch (GroupException | IOException ex) { + catch (GroupException ex) { throw new AuthenticationException("could not store group", ex); } }); @@ -155,7 +150,7 @@ public final class SyncingRealmHelper { userManager.create(user); } } - catch (UserException | IOException ex) { + catch (UserException ex) { throw new AuthenticationException("could not store user", ex); } }); diff --git a/scm-core/src/main/java/sonia/scm/url/ModelUrlProvider.java b/scm-core/src/main/java/sonia/scm/url/ModelUrlProvider.java deleted file mode 100644 index ea60645d00..0000000000 --- a/scm-core/src/main/java/sonia/scm/url/ModelUrlProvider.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ -package sonia.scm.url; - -/** - * @since 1.9 - * @author Sebastian Sdorra - */ -public interface ModelUrlProvider -{ - - /** - * Method description - * - * - * @param name - * - * @return - */ - public String getDetailUrl(String name); - - /** - * Method description - * - * - * @return - */ - public String getAllUrl(); - -} diff --git a/scm-core/src/main/java/sonia/scm/url/RepositoryUrlProvider.java b/scm-core/src/main/java/sonia/scm/url/RepositoryUrlProvider.java deleted file mode 100644 index ebc3f5b907..0000000000 --- a/scm-core/src/main/java/sonia/scm/url/RepositoryUrlProvider.java +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.url; - -/** - * @since 1.9 - * @author Sebastian Sdorra - */ -public interface RepositoryUrlProvider extends ModelUrlProvider -{ - - /** - * Method description - * - * - * @param repositoryId - * @param path - * @param revision - * - * @return - */ - public String getBlameUrl(String repositoryId, String path, String revision); - - /** - * Method description - * - * - * @param repositoryId - * @param path - * @param revision - * - * @return - */ - public String getBrowseUrl(String repositoryId, String path, String revision); - - /** - * Method description - * - * - * @param repositoryId - * @param path - * @param revision - * @param start - * @param limit - * - * @return - */ - public String getChangesetUrl(String repositoryId, String path, - String revision, int start, int limit); - - /** - * Method description - * - * - * @param repositoryId - * @param revision - * - * @return - * - * @since 1.12 - */ - public String getChangesetUrl(String repositoryId, String revision); - - /** - * Method description - * - * - * @param repositoryId - * @param start - * @param limit - * - * @return - */ - public String getChangesetUrl(String repositoryId, int start, int limit); - - /** - * Method description - * - * - * @param repositoryId - * @param path - * @param revision - * - * @return - */ - public String getContentUrl(String repositoryId, String path, - String revision); - - /** - * Method description - * - * - * @param type - * @param name - * - * @return - * @since 1.11 - */ - public String getDetailUrl(String type, String name); - - /** - * Method description - * - * - * @param repositoryId - * @param revision - * - * @return - */ - public String getDiffUrl(String repositoryId, String revision); - - /** - * Method description - * - * - * @param repositoryId - * - * @return - * @since 1.18 - */ - public String getTagsUrl(String repositoryId); -} diff --git a/scm-core/src/main/java/sonia/scm/url/RestModelUrlProvider.java b/scm-core/src/main/java/sonia/scm/url/RestModelUrlProvider.java deleted file mode 100644 index 3974135a53..0000000000 --- a/scm-core/src/main/java/sonia/scm/url/RestModelUrlProvider.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.util.HttpUtil; - -/** - * @since 1.9 - * @author Sebastian Sdorra - */ -public class RestModelUrlProvider implements ModelUrlProvider -{ - - /** - * Constructs ... - * - * - * @param baseUrl - * @param modelSuffix - * @param extension - */ - public RestModelUrlProvider(String baseUrl, String modelSuffix, - String extension) - { - this.base = HttpUtil.append(baseUrl, modelSuffix); - this.extension = extension; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - @Override - public String getAllUrl() - { - return base.concat(extension); - } - - /** - * Method description - * - * - * @param name - * - * @return - */ - @Override - public String getDetailUrl(String name) - { - return HttpUtil.append(base, name).concat(extension); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - protected String base; - - /** Field description */ - protected String extension; -} diff --git a/scm-core/src/main/java/sonia/scm/url/RestRepositoryUrlProvider.java b/scm-core/src/main/java/sonia/scm/url/RestRepositoryUrlProvider.java deleted file mode 100644 index 6c4f0f3235..0000000000 --- a/scm-core/src/main/java/sonia/scm/url/RestRepositoryUrlProvider.java +++ /dev/null @@ -1,278 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.util.UrlBuilder; - -/** - * @since 1.9 - * @author Sebastian Sdorra - */ -public class RestRepositoryUrlProvider extends RestModelUrlProvider - implements RepositoryUrlProvider -{ - - /** Field description */ - public static final String PARAMETER_LIMIT = "limit"; - - /** Field description */ - public static final String PARAMETER_PATH = "path"; - - /** Field description */ - public static final String PARAMETER_REVISION = "revision"; - - /** Field description */ - public static final String PARAMETER_START = "start"; - - /** Field description */ - public static final String PART_BLAME = "blame"; - - /** Field description */ - public static final String PART_BROWSE = "browse"; - - /** - * @since 1.12 - */ - public static final String PART_CHANGESET = "changeset"; - - /** Field description */ - public static final String PART_CHANGESETS = "changesets"; - - /** Field description */ - public static final String PART_CONTENT = "content"; - - /** Field description */ - public static final String PART_DIFF = "diff"; - - /** Field description */ - public static final String PART_TAGS = "tags"; - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - * - * @param baseUrl - * @param modelSuffix - * @param extension - */ - public RestRepositoryUrlProvider(String baseUrl, String modelSuffix, - String extension) - { - super(baseUrl, modelSuffix, extension); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param repositoryId - * @param path - * @param revision - * - * @return - */ - @Override - public String getBlameUrl(String repositoryId, String path, String revision) - { - revision = UrlUtil.fixRevision(revision); - - return new UrlBuilder(base).appendUrlPart(repositoryId).appendUrlPart( - PART_BLAME).append(extension).appendParameter( - PARAMETER_PATH, path).appendParameter( - PARAMETER_REVISION, revision).toString(); - } - - /** - * Method description - * - * - * @param repositoryId - * @param path - * @param revision - * - * @return - */ - @Override - public String getBrowseUrl(String repositoryId, String path, String revision) - { - revision = UrlUtil.fixRevision(revision); - - return new UrlBuilder(base).appendUrlPart(repositoryId).appendUrlPart( - PART_BROWSE).append(extension).appendParameter( - PARAMETER_PATH, path).appendParameter( - PARAMETER_REVISION, revision).toString(); - } - - /** - * Method description - * - * - * @param repositoryId - * @param path - * @param revision - * @param start - * @param limit - * - * @return - */ - @Override - public String getChangesetUrl(String repositoryId, String path, - String revision, int start, int limit) - { - revision = UrlUtil.fixRevision(revision); - - return new UrlBuilder(base).appendUrlPart(repositoryId).appendUrlPart( - PART_CHANGESETS).append(extension).appendParameter( - PARAMETER_PATH, path).appendParameter( - PARAMETER_REVISION, revision).appendParameter( - PARAMETER_START, start).appendParameter( - PARAMETER_LIMIT, limit).toString(); - } - - /** - * Method description - * - * - * @param repositoryId - * @param start - * @param limit - * - * @return - */ - @Override - public String getChangesetUrl(String repositoryId, int start, int limit) - { - return new UrlBuilder(base).appendUrlPart(repositoryId).appendUrlPart( - PART_CHANGESETS).append(extension).appendParameter( - PARAMETER_START, start).appendParameter( - PARAMETER_LIMIT, limit).toString(); - } - - /** - * Method description - * - * - * @param repositoryId - * @param revision - * - * @return - * - * @since 1.12 - */ - @Override - public String getChangesetUrl(String repositoryId, String revision) - { - revision = UrlUtil.fixRevision(revision); - - return new UrlBuilder(base).appendUrlPart(repositoryId).appendUrlPart( - PART_CHANGESET).appendUrlPart(revision).append(extension).toString(); - } - - /** - * Method description - * - * - * @param repositoryId - * @param path - * @param revision - * - * @return - */ - @Override - public String getContentUrl(String repositoryId, String path, String revision) - { - revision = UrlUtil.fixRevision(revision); - - return new UrlBuilder(base).appendUrlPart(repositoryId).appendUrlPart( - PART_CONTENT).appendParameter(PARAMETER_PATH, path).appendParameter( - PARAMETER_REVISION, revision).toString(); - } - - /** - * Method description - * - * - * @param type - * @param name - * - * @return - * @since 1.11 - */ - @Override - public String getDetailUrl(String type, String name) - { - return new UrlBuilder(base).appendUrlPart(type).appendUrlPart(name).append( - extension).toString(); - } - - /** - * Method description - * - * - * @param repositoryId - * @param revision - * - * @return - */ - @Override - public String getDiffUrl(String repositoryId, String revision) - { - revision = UrlUtil.fixRevision(revision); - - return new UrlBuilder(base).appendUrlPart(repositoryId).appendUrlPart( - PART_DIFF).appendParameter(PARAMETER_REVISION, revision).toString(); - } - - /** - * Method description - * - * - * @param repositoryId - * - * @return - * @since 1.18 - */ - @Override - public String getTagsUrl(String repositoryId) - { - return new UrlBuilder(base).appendUrlPart(repositoryId).appendUrlPart( - PART_TAGS).append(extension).toString(); - } -} diff --git a/scm-core/src/main/java/sonia/scm/url/RestSecurityUrlProvider.java b/scm-core/src/main/java/sonia/scm/url/RestSecurityUrlProvider.java deleted file mode 100644 index 513f728708..0000000000 --- a/scm-core/src/main/java/sonia/scm/url/RestSecurityUrlProvider.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of SCM-Manager; - * 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.util.HttpUtil; - -/** - * - * @author Sebastian Sdorra - * @since 1.41 - */ -public class RestSecurityUrlProvider implements SecurityUrlProvider -{ - - /** Field description */ - private static final String PATH_ENCRYPT = "security/cipher/encrypt"; - - /** Field description */ - private static final String PATH_KEY = "security/key"; - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - * - * @param baseUrl - */ - public RestSecurityUrlProvider(String baseUrl) - { - this.baseUrl = baseUrl; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - @Override - public String getEncryptUrl() - { - return HttpUtil.append(baseUrl, PATH_ENCRYPT); - } - - /** - * Method description - * - * - * @return - */ - @Override - public String getGenerateKeyUrl() - { - return HttpUtil.append(baseUrl, PATH_KEY); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private final String baseUrl; -} diff --git a/scm-core/src/main/java/sonia/scm/url/RestUrlProvider.java b/scm-core/src/main/java/sonia/scm/url/RestUrlProvider.java deleted file mode 100644 index 4abba6db0b..0000000000 --- a/scm-core/src/main/java/sonia/scm/url/RestUrlProvider.java +++ /dev/null @@ -1,190 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.util.HttpUtil; - -/** - * @since 1.9 - * @author Sebastian Sdorra - */ -public class RestUrlProvider implements UrlProvider -{ - - /** Field description */ - public static final String PART_API = "api/rest/"; - - /** Field description */ - public static final String PART_AUTHENTICATION = "auth/access_token"; - - /** Field description */ - public static final String PART_CONFIG = "config"; - - /** Field description */ - public static final String PART_GROUP = "groups"; - - /** Field description */ - public static final String PART_REPOSITORIES = "repositories"; - - /** Field description */ - public static final String PART_STATE = "auth"; - - /** Field description */ - public static final String PART_USER = "users"; - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - * - * @param baseUrl - * @param extension - */ - public RestUrlProvider(String baseUrl, String extension) - { - this.baseUrl = HttpUtil.append(baseUrl, PART_API); - this.extension = extension; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - @Override - public String getAuthenticationUrl() - { - return HttpUtil.append(baseUrl, PART_AUTHENTICATION).concat(extension); - } - - /** - * Method description - * - * - * @return - * - * @since 1.43 - */ - @Override - public String getBaseUrl() - { - return baseUrl; - } - - /** - * Method description - * - * - * @return - */ - @Override - public String getConfigUrl() - { - return HttpUtil.append(baseUrl, PART_CONFIG).concat(extension); - } - - /** - * Method description - * - * - * @return - */ - @Override - public ModelUrlProvider getGroupUrlProvider() - { - return new RestModelUrlProvider(baseUrl, PART_GROUP, extension); - } - - /** - * Method description - * - * - * @return - */ - @Override - public RepositoryUrlProvider getRepositoryUrlProvider() - { - return new RestRepositoryUrlProvider(baseUrl, PART_REPOSITORIES, extension); - } - - /** - * Method description - * - * - * @return - */ - @Override - public SecurityUrlProvider getSecurityUrlProvider() - { - return new RestSecurityUrlProvider(baseUrl); - } - - /** - * Method description - * - * - * @return - */ - @Override - public String getStateUrl() - { - return HttpUtil.append(baseUrl, PART_STATE).concat(extension); - } - - /** - * Method description - * - * - * @return - */ - @Override - public ModelUrlProvider getUserUrlProvider() - { - return new RestModelUrlProvider(baseUrl, PART_USER, extension); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - protected String baseUrl; - - /** Field description */ - protected String extension; -} diff --git a/scm-core/src/main/java/sonia/scm/url/SecurityUrlProvider.java b/scm-core/src/main/java/sonia/scm/url/SecurityUrlProvider.java deleted file mode 100644 index e000c9b754..0000000000 --- a/scm-core/src/main/java/sonia/scm/url/SecurityUrlProvider.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of SCM-Manager; - * 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.url; - -/** - * - * @author Sebastian Sdorra - * @since 1.41 - */ -public interface SecurityUrlProvider -{ - - /** - * Method description - * - * - * @return - */ - public String getGenerateKeyUrl(); - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public String getEncryptUrl(); -} diff --git a/scm-core/src/main/java/sonia/scm/url/UrlProvider.java b/scm-core/src/main/java/sonia/scm/url/UrlProvider.java deleted file mode 100644 index 1ab798d60b..0000000000 --- a/scm-core/src/main/java/sonia/scm/url/UrlProvider.java +++ /dev/null @@ -1,110 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.url; - -/** - * @since 1.9 - * @author Sebastian Sdorra - */ -public interface UrlProvider -{ - - /** - * Method description - * - * - * @return - */ - public String getAuthenticationUrl(); - - /** - * Method description - * - * - * @return - * - * @since 1.43 - */ - public String getBaseUrl(); - - /** - * Method description - * - * - * @return - */ - public String getConfigUrl(); - - /** - * Method description - * - * - * @return - */ - public ModelUrlProvider getGroupUrlProvider(); - - /** - * Method description - * - * - * @return - */ - public RepositoryUrlProvider getRepositoryUrlProvider(); - - /** - * Method description - * - * - * @return - * - * @since 1.41 - */ - public SecurityUrlProvider getSecurityUrlProvider(); - - /** - * Method description - * - * - * @return - */ - public String getStateUrl(); - - /** - * Method description - * - * - * @return - */ - public ModelUrlProvider getUserUrlProvider(); -} diff --git a/scm-core/src/main/java/sonia/scm/url/UrlProviderFactory.java b/scm-core/src/main/java/sonia/scm/url/UrlProviderFactory.java deleted file mode 100644 index bb4b998817..0000000000 --- a/scm-core/src/main/java/sonia/scm/url/UrlProviderFactory.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.url; - -/** - * @since 1.9 - * @author Sebastian Sdorra - */ -public final class UrlProviderFactory -{ - - /** Field description */ - public static final String TYPE_RESTAPI_JSON = "json-rest-api"; - - /** Field description */ - public static final String TYPE_RESTAPI_XML = "xml-rest-api"; - - /** Field description */ - public static final String TYPE_WUI = "wui"; - - /** Field description */ - private static final String EXTENSION_JSON = ".json"; - - /** Field description */ - private static final String EXTENSION_XML = ".xml"; - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - */ - private UrlProviderFactory() {} - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * - * @param baseUrl - * @param type - * - * @return - */ - public static UrlProvider createUrlProvider(String baseUrl, String type) - { - UrlProvider provider = null; - - if (TYPE_RESTAPI_JSON.equals(type)) - { - provider = new RestUrlProvider(baseUrl, EXTENSION_JSON); - } - else if (TYPE_RESTAPI_XML.equals(type)) - { - provider = new RestUrlProvider(baseUrl, EXTENSION_XML); - } - else if (TYPE_WUI.equals(type)) - { - provider = new WUIUrlProvider(baseUrl); - } - - return provider; - } -} diff --git a/scm-core/src/main/java/sonia/scm/url/UrlUtil.java b/scm-core/src/main/java/sonia/scm/url/UrlUtil.java deleted file mode 100644 index 0d90da10b6..0000000000 --- a/scm-core/src/main/java/sonia/scm/url/UrlUtil.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.util.Util; - -/** - * - * @author Sebastian Sdorra - * @since 1.11 - */ -public final class UrlUtil -{ - - /** - * Constructs ... - * - */ - private UrlUtil() {} - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param revision - * - * @return - */ - public static String fixRevision(String revision) - { - String fixedRevision = revision; - - if (Util.isNotEmpty(revision)) - { - int index = revision.indexOf(':'); - - if (index > 0) - { - fixedRevision = revision.substring(index + 1); - } - } - - return fixedRevision; - } -} diff --git a/scm-core/src/main/java/sonia/scm/url/WUIModelUrlProvider.java b/scm-core/src/main/java/sonia/scm/url/WUIModelUrlProvider.java deleted file mode 100644 index bef0ef3b68..0000000000 --- a/scm-core/src/main/java/sonia/scm/url/WUIModelUrlProvider.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.util.HttpUtil; - -/** - * @since 1.9 - * @author Sebastian Sdorra - */ -public class WUIModelUrlProvider implements ModelUrlProvider -{ - - /** - * Constructs ... - * - * - * @param baseUrl - * @param component - */ - public WUIModelUrlProvider(String baseUrl, String component) - { - this.url = HttpUtil.appendHash(baseUrl, component); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - @Override - public String getAllUrl() - { - return url; - } - - /** - * Method description - * - * - * @param name - * - * @return - */ - @Override - public String getDetailUrl(String name) - { - return url.concat(WUIUrlBuilder.SEPARATOR).concat(name); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private String url; -} diff --git a/scm-core/src/main/java/sonia/scm/url/WUIRepositoryUrlProvider.java b/scm-core/src/main/java/sonia/scm/url/WUIRepositoryUrlProvider.java deleted file mode 100644 index 7809adbcc3..0000000000 --- a/scm-core/src/main/java/sonia/scm/url/WUIRepositoryUrlProvider.java +++ /dev/null @@ -1,274 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.util.HttpUtil; - -/** - * - * @author Sebastian Sdorra - */ -public class WUIRepositoryUrlProvider extends WUIModelUrlProvider - implements RepositoryUrlProvider -{ - - /** Field description */ - public static final String COMPONENT_BROWSER = "repositoryBrowser"; - - /** - * @since 1.15 - */ - public static final String COMPONENT_CHANGESET = "changesetPanel"; - - /** Field description */ - public static final String COMPONENT_CHANGESETS = - "repositoryChangesetViewerPanel"; - - /** Field description */ - public static final String COMPONENT_CONTENT = "contentPanel"; - - /** Field description */ - public static final String COMPONENT_DETAIL = "repositoryPanel"; - - /** Field description */ - public static final String COMPONENT_DIFF = "diffPanel"; - - /** Field description */ - public static final String VIEW_BLAME = "blame"; - - /** - * @since 1.12 - */ - public static final String VIEW_CHANGESET = "changeset"; - - /** Field description */ - public static final String VIEW_CONTENT = "content"; - - /** Field description */ - public static final String VIEW_HISTORY = "history"; - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - * - * @param baseUrl - * @param component - */ - public WUIRepositoryUrlProvider(String baseUrl, String component) - { - super(baseUrl, component); - this.baseUrl = baseUrl; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param repositoryId - * @param path - * @param revision - * - * @return - */ - @Override - public String getBlameUrl(String repositoryId, String path, String revision) - { - revision = UrlUtil.fixRevision(revision); - - return new WUIUrlBuilder(baseUrl, COMPONENT_CONTENT).append( - repositoryId).append(revision).append(path).append(VIEW_BLAME).toString(); - } - - /** - * Method description - * - * - * @param repositoryId - * @param path - * @param revision - * - * @return - */ - @Override - public String getBrowseUrl(String repositoryId, String path, String revision) - { - revision = UrlUtil.fixRevision(revision); - - return new WUIUrlBuilder(baseUrl, COMPONENT_BROWSER).append( - repositoryId).append(revision).append(path).toString(); - } - - /** - * Method description - * - * - * @param repositoryId - * @param path - * @param revision - * @param start - * @param limit - * - * @return - */ - @Override - public String getChangesetUrl(String repositoryId, String path, - String revision, int start, int limit) - { - revision = UrlUtil.fixRevision(revision); - - // TODO handle start and limit - return new WUIUrlBuilder(baseUrl, COMPONENT_CONTENT).append( - repositoryId).append(revision).append(path).append( - VIEW_HISTORY).toString(); - } - - /** - * Method description - * - * - * @param repositoryId - * @param start - * @param limit - * - * @return - */ - @Override - public String getChangesetUrl(String repositoryId, int start, int limit) - { - return new WUIUrlBuilder(baseUrl, COMPONENT_CHANGESETS).append( - repositoryId).append(start).append(limit).toString(); - } - - /** - * Method description - * - * - * @param repositoryId - * @param revision - * - * @return - * - * @since 1.12 - */ - @Override - public String getChangesetUrl(String repositoryId, String revision) - { - revision = UrlUtil.fixRevision(revision); - - return new WUIUrlBuilder(baseUrl, - COMPONENT_CHANGESET).append(repositoryId).append(revision).toString(); - } - - /** - * Method description - * - * - * @param repositoryId - * @param path - * @param revision - * - * @return - */ - @Override - public String getContentUrl(String repositoryId, String path, String revision) - { - revision = UrlUtil.fixRevision(revision); - - return new WUIUrlBuilder(baseUrl, COMPONENT_CONTENT).append( - repositoryId).append(revision).append(path).append( - VIEW_HISTORY).toString(); - } - - /** - * Method description - * - * - * @param type - * @param name - * - * @return - * @since 1.11 - */ - @Override - public String getDetailUrl(String type, String name) - { - name = type.concat(HttpUtil.SEPARATOR_PATH).concat(name); - - return new WUIUrlBuilder(baseUrl, COMPONENT_DETAIL).append(name).toString(); - } - - /** - * Method description - * - * - * @param repositoryId - * @param revision - * - * @return - */ - @Override - public String getDiffUrl(String repositoryId, String revision) - { - revision = UrlUtil.fixRevision(revision); - - return new WUIUrlBuilder(baseUrl, - COMPONENT_DIFF).append(repositoryId).append(revision).toString(); - } - - /** - * Method description - * - * - * @param repositoryId - * - * @return - * @since 1.18 - */ - @Override - public String getTagsUrl(String repositoryId) - { - return getBrowseUrl(repositoryId, null, null); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private String baseUrl; -} diff --git a/scm-core/src/main/java/sonia/scm/url/WUIUrlBuilder.java b/scm-core/src/main/java/sonia/scm/url/WUIUrlBuilder.java deleted file mode 100644 index c9744effe3..0000000000 --- a/scm-core/src/main/java/sonia/scm/url/WUIUrlBuilder.java +++ /dev/null @@ -1,123 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.util.HttpUtil; - -/** - * @since 1.9 - * @author Sebastian Sdorra - */ -public class WUIUrlBuilder -{ - - /** Field description */ - public static final String NULL = "null"; - - /** Field description */ - public static final String SEPARATOR = ";"; - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - * - * @param baseUrl - * @param component - */ - public WUIUrlBuilder(String baseUrl, String component) - { - this.url = HttpUtil.appendHash(baseUrl, component); - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param value - * - * @return - */ - public WUIUrlBuilder append(String value) - { - if (value == null) - { - value = NULL; - } - - if (!this.url.endsWith(SEPARATOR)) - { - this.url = this.url.concat(SEPARATOR); - } - - this.url = this.url.concat(value); - - return this; - } - - /** - * Method description - * - * - * @param value - * - * @return - */ - public WUIUrlBuilder append(int value) - { - return append(String.valueOf(value)); - } - - /** - * Method description - * - * - * @return - */ - @Override - public String toString() - { - return url; - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private String url; -} diff --git a/scm-core/src/main/java/sonia/scm/url/WUIUrlProvider.java b/scm-core/src/main/java/sonia/scm/url/WUIUrlProvider.java deleted file mode 100644 index bd94bf562e..0000000000 --- a/scm-core/src/main/java/sonia/scm/url/WUIUrlProvider.java +++ /dev/null @@ -1,182 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.util.HttpUtil; - -/** - * @since 1.9 - * @author Sebastian Sdorra - */ -public class WUIUrlProvider implements UrlProvider -{ - - /** Field description */ - public static final String COMPONENT_CONFIG = "scmConfig"; - - /** Field description */ - public static final String COMPONENT_GROUP = "groupPanel"; - - /** Field description */ - public static final String COMPONENT_REPOSITORY = "repositoryPanel"; - - /** Field description */ - public static final String COMPONENT_USER = "userPanel"; - - /** Field description */ - public static final String PART_INDEX = "index.html"; - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - * - * @param baseUrl - */ - public WUIUrlProvider(String baseUrl) - { - this.baseUrl = HttpUtil.append(baseUrl, PART_INDEX); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Returns the baseUrl, because there is no authentication url. - * - * - * @returns the baseUrl, because there is no authentication url - * - * @return - */ - @Override - public String getAuthenticationUrl() - { - return baseUrl; - } - - /** - * Method description - * - * - * @return - * - * @since 1.43 - */ - @Override - public String getBaseUrl() - { - return baseUrl; - } - - /** - * Method description - * - * - * @return - */ - @Override - public String getConfigUrl() - { - return HttpUtil.appendHash(baseUrl, COMPONENT_CONFIG); - } - - /** - * Method description - * - * - * @return - */ - @Override - public ModelUrlProvider getGroupUrlProvider() - { - return new WUIModelUrlProvider(baseUrl, COMPONENT_GROUP); - } - - /** - * Method description - * - * - * @return - */ - @Override - public RepositoryUrlProvider getRepositoryUrlProvider() - { - return new WUIRepositoryUrlProvider(baseUrl, COMPONENT_REPOSITORY); - } - - /** - * Method description - * - * - * @return - */ - @Override - public SecurityUrlProvider getSecurityUrlProvider() - { - throw new UnsupportedOperationException( - "this provider does not support security url provider."); - } - - /** - * Returns the baseUrl, because there is no state url. - * - * - * @return the baseUrl, because there is no state url - */ - @Override - public String getStateUrl() - { - return baseUrl; - } - - /** - * Method description - * - * - * @return - */ - @Override - public ModelUrlProvider getUserUrlProvider() - { - return new WUIModelUrlProvider(baseUrl, COMPONENT_USER); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private String baseUrl; -} diff --git a/scm-core/src/main/java/sonia/scm/user/UserAlreadyExistsException.java b/scm-core/src/main/java/sonia/scm/user/UserAlreadyExistsException.java index 8c8f2542f0..1c77cb4f86 100644 --- a/scm-core/src/main/java/sonia/scm/user/UserAlreadyExistsException.java +++ b/scm-core/src/main/java/sonia/scm/user/UserAlreadyExistsException.java @@ -41,19 +41,11 @@ package sonia.scm.user; public class UserAlreadyExistsException extends UserException { - /** Field description */ private static final long serialVersionUID = 9182294539718090814L; //~--- constructors --------------------------------------------------------- - /** - * Constructs a new instance. - * - * @param message message of exception - * @since 1.5 - */ - public UserAlreadyExistsException(String message) - { - super(message); + public UserAlreadyExistsException(User user) { + super(user.getName() + " user already exists"); } } diff --git a/scm-core/src/main/java/sonia/scm/user/UserNotFoundException.java b/scm-core/src/main/java/sonia/scm/user/UserNotFoundException.java index 16ee045a75..82b1c2abb8 100644 --- a/scm-core/src/main/java/sonia/scm/user/UserNotFoundException.java +++ b/scm-core/src/main/java/sonia/scm/user/UserNotFoundException.java @@ -51,39 +51,7 @@ public class UserNotFoundException extends UserException * Constructs a new UserNotFoundException. * */ - public UserNotFoundException() {} - - /** - * Constructs a new UserNotFoundException. - * - * - * @param message message for the exception - */ - public UserNotFoundException(String message) - { - super(message); - } - - /** - * Constructs a new UserNotFoundException. - * - * - * @param throwable root cause - */ - public UserNotFoundException(Throwable throwable) - { - super(throwable); - } - - /** - * Constructs a new UserNotFoundException. - * - * - * @param message message for the exception - * @param throwable root cause - */ - public UserNotFoundException(String message, Throwable throwable) - { - super(message, throwable); + public UserNotFoundException(User user) { + super("user " + user.getName() + " does not exist"); } } diff --git a/scm-core/src/main/java/sonia/scm/util/HttpUtil.java b/scm-core/src/main/java/sonia/scm/util/HttpUtil.java index 27abcaffbe..30995a0b3c 100644 --- a/scm-core/src/main/java/sonia/scm/util/HttpUtil.java +++ b/scm-core/src/main/java/sonia/scm/util/HttpUtil.java @@ -39,27 +39,23 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.CharMatcher; import com.google.common.base.Objects; import com.google.common.base.Strings; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import sonia.scm.config.ScmConfiguration; -//~--- JDK imports ------------------------------------------------------------ - +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; - import java.net.URLDecoder; import java.net.URLEncoder; - +import java.util.Arrays; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +//~--- JDK imports ------------------------------------------------------------ /** * Util method for the http protocol. @@ -86,9 +82,9 @@ public final class HttpUtil /** * Name of bearer authentication cookie. - * + * * TODO find a better place - * + * * @since 2.0.0 */ public static final String COOKIE_BEARER_AUTHENTICATION = "X-Bearer-Token"; @@ -101,7 +97,7 @@ public final class HttpUtil * @since 2.0.0 */ public static final String HEADER_AUTHORIZATION = "Authorization"; - + /** * content-length header * @since 1.46 @@ -252,13 +248,23 @@ public final class HttpUtil //~--- methods -------------------------------------------------------------- + /** + * Joins all path elements together separated by {@code {@link #SEPARATOR_PATH}}. + * + * @param pathElements path elements + * + * @return concatenated path + * @since 2.0.0 + */ + public static String concatenate(String... pathElements) { + return Arrays.stream(pathElements).reduce(HttpUtil::append).orElse(""); + } + /** * Appends the suffix to given uri. * - * - * @param uri uri + * @param uri uri * @param suffix suffix - * * @return * @since 1.9 */ diff --git a/scm-core/src/main/java/sonia/scm/web/VndMediaType.java b/scm-core/src/main/java/sonia/scm/web/VndMediaType.java index c30a03c004..6d20d14043 100644 --- a/scm-core/src/main/java/sonia/scm/web/VndMediaType.java +++ b/scm-core/src/main/java/sonia/scm/web/VndMediaType.java @@ -14,8 +14,10 @@ public class VndMediaType { public static final String USER = PREFIX + "user" + SUFFIX; public static final String GROUP = PREFIX + "group" + SUFFIX; + public static final String REPOSITORY = PREFIX + "repository" + SUFFIX; public static final String USER_COLLECTION = PREFIX + "userCollection" + SUFFIX; public static final String GROUP_COLLECTION = PREFIX + "groupCollection" + SUFFIX; + public static final String REPOSITORY_COLLECTION = PREFIX + "repositoryCollection" + SUFFIX; public static final String ME = PREFIX + "me" + SUFFIX; private VndMediaType() { diff --git a/scm-core/src/main/java/sonia/scm/web/filter/RegexPermissionFilter.java b/scm-core/src/main/java/sonia/scm/web/filter/RegexPermissionFilter.java deleted file mode 100644 index 40c41a5954..0000000000 --- a/scm-core/src/main/java/sonia/scm/web/filter/RegexPermissionFilter.java +++ /dev/null @@ -1,133 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.web.filter; - -//~--- non-JDK imports -------------------------------------------------------- - - -import sonia.scm.config.ScmConfiguration; -import sonia.scm.repository.Repository; -import sonia.scm.repository.RepositoryManager; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.servlet.http.HttpServletRequest; - -/** - * - * @author Sebastian Sdorra - */ -public abstract class RegexPermissionFilter extends PermissionFilter -{ - - /** Field description */ - public static final Pattern PATTERN_REPOSITORYNAME = - Pattern.compile("/[^/]+/([^/]+)(?:/.*)?"); - - //~--- constructors --------------------------------------------------------- - - /** - * Constructs ... - * - * - * - * @param configuration - * @param repositoryManager - */ - public RegexPermissionFilter(ScmConfiguration configuration, - RepositoryManager repositoryManager) - { - super(configuration); - this.repositoryManager = repositoryManager; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - protected abstract String getType(); - - /** - * Method description - * - * - * @param request - * - * @return - */ - @Override - protected Repository getRepository(HttpServletRequest request) - { - Repository repository = null; - String uri = request.getRequestURI(); - - uri = uri.substring(request.getContextPath().length()); - - Matcher m = PATTERN_REPOSITORYNAME.matcher(uri); - - if (m.matches()) - { - String repositoryname = m.group(1); - - repository = getRepository(repositoryname); - } - - return repository; - } - - /** - * Method description - * - * - * @param name - * - * @return - */ - protected Repository getRepository(String name) - { - return repositoryManager.get(getType(), name); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private RepositoryManager repositoryManager; -} diff --git a/scm-core/src/test/java/sonia/scm/ManagerTest.java b/scm-core/src/test/java/sonia/scm/ManagerTest.java index 749e579386..06c8eb3ea6 100644 --- a/scm-core/src/test/java/sonia/scm/ManagerTest.java +++ b/scm-core/src/test/java/sonia/scm/ManagerTest.java @@ -88,7 +88,7 @@ public class ManagerTest { public Collection getAll(Comparator comparator, int start, int limit) { return null; } @Override - public void create(TypedObject object) {} + public TypedObject create(TypedObject object) { return null; } @Override public void delete(TypedObject object) {} diff --git a/scm-core/src/test/java/sonia/scm/repository/RepositoryTest.java b/scm-core/src/test/java/sonia/scm/repository/RepositoryTest.java index 98e714b67f..f13f4cbc67 100644 --- a/scm-core/src/test/java/sonia/scm/repository/RepositoryTest.java +++ b/scm-core/src/test/java/sonia/scm/repository/RepositoryTest.java @@ -32,11 +32,9 @@ package sonia.scm.repository; -//~--- non-JDK imports -------------------------------------------------------- - import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; /** * @@ -52,7 +50,7 @@ public class RepositoryTest @Test public void testCreateUrl() { - Repository repository = new Repository("123", "hg", "test/repo"); + Repository repository = new Repository("123", "hg", "test", "repo"); assertEquals("http://localhost:8080/scm/hg/test/repo", repository.createUrl("http://localhost:8080/scm")); diff --git a/scm-core/src/test/java/sonia/scm/repository/RepositoryUtilTest.java b/scm-core/src/test/java/sonia/scm/repository/RepositoryUtilTest.java new file mode 100644 index 0000000000..25fa3eeeb3 --- /dev/null +++ b/scm-core/src/test/java/sonia/scm/repository/RepositoryUtilTest.java @@ -0,0 +1,73 @@ +package sonia.scm.repository; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.io.File; +import java.io.IOException; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +@RunWith(MockitoJUnitRunner.class) +public class RepositoryUtilTest { + + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Mock + private AbstractRepositoryHandler repositoryHandler; + + private SimpleRepositoryConfig repositoryConfig = new SimpleRepositoryConfig(); + + @Before + public void setUpMocks() { + when(repositoryHandler.getConfig()).thenReturn(repositoryConfig); + } + + @Test + public void testGetRepositoryId() throws IOException { + File repositoryTypeRoot = temporaryFolder.newFolder(); + repositoryConfig.setRepositoryDirectory(repositoryTypeRoot); + + File repository = new File(repositoryTypeRoot, "abc"); + String id = RepositoryUtil.getRepositoryId(repositoryHandler, repository.getPath()); + assertEquals("abc", id); + } + + @Test(expected = IllegalArgumentException.class) + public void testGetRepositoryIdWithInvalidPath() throws IOException { + File repositoryTypeRoot = temporaryFolder.newFolder(); + repositoryConfig.setRepositoryDirectory(repositoryTypeRoot); + + File repository = new File("/etc/abc"); + String id = RepositoryUtil.getRepositoryId(repositoryHandler, repository.getPath()); + assertEquals("abc", id); + } + + @Test(expected = IllegalArgumentException.class) + public void testGetRepositoryIdWithInvalidPathButSameLength() throws IOException { + File repositoryTypeRoot = temporaryFolder.newFolder(); + repositoryConfig.setRepositoryDirectory(repositoryTypeRoot); + + File repository = new File(temporaryFolder.newFolder(), "abc"); + + String id = RepositoryUtil.getRepositoryId(repositoryHandler, repository.getPath()); + assertEquals("abc", id); + } + + @Test(expected = IllegalArgumentException.class) + public void testGetRepositoryIdWithInvalidId() throws IOException { + File repositoryTypeRoot = temporaryFolder.newFolder(); + repositoryConfig.setRepositoryDirectory(repositoryTypeRoot); + + File repository = new File(repositoryTypeRoot, "abc/123"); + RepositoryUtil.getRepositoryId(repositoryHandler, repository.getPath()); + } + +} diff --git a/scm-core/src/test/java/sonia/scm/url/JSONRestModelUrlProviderTest.java b/scm-core/src/test/java/sonia/scm/url/JSONRestModelUrlProviderTest.java deleted file mode 100644 index 778ca9883b..0000000000 --- a/scm-core/src/test/java/sonia/scm/url/JSONRestModelUrlProviderTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - -package sonia.scm.url; - -/** - * - * @author Sebastian Sdorra - */ -public class JSONRestModelUrlProviderTest extends RestModelUrlProviderTestBase -{ - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - @Override - protected UrlProvider createUrlProvider(String baseUrl) - { - return UrlProviderFactory.createUrlProvider(baseUrl, - UrlProviderFactory.TYPE_RESTAPI_JSON); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - @Override - protected String getExtension() - { - return EXTENSION_JSON; - } -} diff --git a/scm-core/src/test/java/sonia/scm/url/JSONRestRepositoryUrlProviderTest.java b/scm-core/src/test/java/sonia/scm/url/JSONRestRepositoryUrlProviderTest.java deleted file mode 100644 index 68c38d0446..0000000000 --- a/scm-core/src/test/java/sonia/scm/url/JSONRestRepositoryUrlProviderTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - -package sonia.scm.url; - -/** - * - * @author Sebastian Sdorra - */ -public class JSONRestRepositoryUrlProviderTest - extends RestRepositoryUrlProviderTestBase -{ - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - @Override - protected RepositoryUrlProvider createRepositoryUrlProvider(String baseUrl) - { - return UrlProviderFactory.createUrlProvider(baseUrl, - UrlProviderFactory.TYPE_RESTAPI_JSON).getRepositoryUrlProvider(); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - @Override - protected String getExtension() - { - return EXTENSION_JSON; - } -} diff --git a/scm-core/src/test/java/sonia/scm/url/JSONRestUrlProviderTest.java b/scm-core/src/test/java/sonia/scm/url/JSONRestUrlProviderTest.java deleted file mode 100644 index a887efa96c..0000000000 --- a/scm-core/src/test/java/sonia/scm/url/JSONRestUrlProviderTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - -package sonia.scm.url; - -/** - * - * @author Sebastian Sdorra - */ -public class JSONRestUrlProviderTest extends RestUrlProviderTestBase -{ - - /** - * Method description - * - * - * - * @param baseUrl - * @return - */ - @Override - protected UrlProvider createUrlProvider(String baseUrl) - { - return UrlProviderFactory.createUrlProvider(baseUrl, - UrlProviderFactory.TYPE_RESTAPI_JSON); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - @Override - protected String getExtension() - { - return EXTENSION_JSON; - } -} diff --git a/scm-core/src/test/java/sonia/scm/url/ModelUrlProviderTestBase.java b/scm-core/src/test/java/sonia/scm/url/ModelUrlProviderTestBase.java deleted file mode 100644 index 14d38c1928..0000000000 --- a/scm-core/src/test/java/sonia/scm/url/ModelUrlProviderTestBase.java +++ /dev/null @@ -1,184 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * - * @author Sebastian Sdorra - */ -public abstract class ModelUrlProviderTestBase extends UrlTestBase -{ - - /** Field description */ - public static final String ITEM = "hitchhiker"; - - /** Field description */ - public static final String MODEL_GROUPS = "groups"; - - /** Field description */ - public static final String MODEL_REPOSITORY = "repositories"; - - /** Field description */ - public static final String MODEL_USERS = "users"; - - /** Field description */ - private static final String[] MODELS = new String[] { MODEL_REPOSITORY, - MODEL_USERS, MODEL_GROUPS }; - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * - * @param baseUrl - * @return - */ - protected abstract ModelUrlProvider createGroupModelUrlProvider( - String baseUrl); - - /** - * Method description - * - * - * - * @param baseUrl - * @return - */ - protected abstract ModelUrlProvider createRepositoryModelUrlProvider( - String baseUrl); - - /** - * Method description - * - * - * - * @param baseUrl - * @return - */ - protected abstract ModelUrlProvider createUserModelUrlProvider( - String baseUrl); - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param baseUrl - * @param model - * - * @return - */ - protected abstract String getExpectedAllUrl(String baseUrl, String model); - - /** - * Method description - * - * - * @param baseUrl - * @param model - * @param item - * - * @return - */ - protected abstract String getExpectedDetailUrl(String baseUrl, String model, - String item); - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Test - public void testGetAllUrl() - { - for (String model : MODELS) - { - assertEquals(getExpectedAllUrl(BASEURL, model), - createModelUrlProvider(BASEURL, model).getAllUrl()); - } - } - - /** - * Method description - * - */ - @Test - public void testGetDetailUrl() - { - for (String model : MODELS) - { - assertEquals(getExpectedDetailUrl(BASEURL, model, ITEM), - createModelUrlProvider(BASEURL, model).getDetailUrl(ITEM)); - } - } - - /** - * Method description - * - * - * - * @param baseUrl - * @param model - * - * @return - */ - private ModelUrlProvider createModelUrlProvider(String baseUrl, String model) - { - ModelUrlProvider urlProvider = null; - - if (MODEL_REPOSITORY.equals(model)) - { - urlProvider = createRepositoryModelUrlProvider(baseUrl); - } - else if (MODEL_USERS.equals(model)) - { - urlProvider = createUserModelUrlProvider(baseUrl); - } - else if (MODEL_GROUPS.equals(model)) - { - urlProvider = createGroupModelUrlProvider(baseUrl); - } - - return urlProvider; - } -} diff --git a/scm-core/src/test/java/sonia/scm/url/RepositoryUrlProviderTestBase.java b/scm-core/src/test/java/sonia/scm/url/RepositoryUrlProviderTestBase.java deleted file mode 100644 index 0c2e36dfd3..0000000000 --- a/scm-core/src/test/java/sonia/scm/url/RepositoryUrlProviderTestBase.java +++ /dev/null @@ -1,265 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * - * @author Sebastian Sdorra - */ -public abstract class RepositoryUrlProviderTestBase extends UrlTestBase -{ - - /** Field description */ - private static final String NAME = "scm/main"; - - /** Field description */ - private static final String PATH = "scm-webapp/pom.xml"; - - /** Field description */ - private static final String REPOSITORY_ID = - "E3882BE7-7D0D-421B-B178-B2AA9E897135"; - - /** Field description */ - private static final String REVISION = "b282fb2dd12a"; - - /** Field description */ - private static final String TYPE = "hg"; - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - protected abstract RepositoryUrlProvider createRepositoryUrlProvider( - String baseUrl); - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param baseUrl - * @param repositoryId - * @param path - * @param revision - * - * @return - */ - protected abstract String getExpectedBlameUrl(String baseUrl, - String repositoryId, String path, String revision); - - /** - * Method description - * - * - * - * @param baseUrl - * @param repositoryId - * @param path - * @param revision - * - * @return - */ - protected abstract String getExpectedBrowseUrl(String baseUrl, - String repositoryId, String path, String revision); - - /** - * Method description - * - * - * - * @param baseUrl - * @param repositoryId - * @param path - * @param revision - * @param start - * @param limit - * - * @return - */ - protected abstract String getExpectedChangesetUrl(String baseUrl, - String repositoryId, String path, String revision, int start, - int limit); - - /** - * Method description - * - * - * - * @param baseUrl - * @param repositoryId - * @param start - * @param limit - * - * @return - */ - protected abstract String getExpectedChangesetUrl(String baseUrl, - String repositoryId, int start, int limit); - - /** - * Method description - * - * - * - * @param baseUrl - * @param repositoryId - * @param path - * @param revision - * - * @return - */ - protected abstract String getExpectedContentUrl(String baseUrl, - String repositoryId, String path, String revision); - - /** - * Method description - * - * - * - * @param baseUrl - * @param type - * @param name - * - * @return - * @since 1.11 - */ - protected abstract String getExpectedDetailUrl(String baseUrl, String type, - String name); - - /** - * Method description - * - * - * - * @param baseUrl - * @param repositoryId - * @param revision - * - * @return - */ - protected abstract String getExpectedDiffUrl(String baseUrl, - String repositoryId, String revision); - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Test - public void testGetBlameUrl() - { - assertEquals( - getExpectedBlameUrl(BASEURL, REPOSITORY_ID, PATH, REVISION), - createRepositoryUrlProvider(BASEURL).getBlameUrl( - REPOSITORY_ID, PATH, REVISION)); - } - - /** - * Method description - * - */ - @Test - public void testGetBrowserUrl() - { - assertEquals( - getExpectedBrowseUrl(BASEURL, REPOSITORY_ID, PATH, REVISION), - createRepositoryUrlProvider(BASEURL).getBrowseUrl( - REPOSITORY_ID, PATH, REVISION)); - } - - /** - * Method description - * - */ - @Test - public void testGetChangesetUrl() - { - assertEquals( - getExpectedChangesetUrl(BASEURL, REPOSITORY_ID, PATH, REVISION, 0, 20), - createRepositoryUrlProvider(BASEURL).getChangesetUrl( - REPOSITORY_ID, PATH, REVISION, 0, 20)); - assertEquals( - getExpectedChangesetUrl(BASEURL, REPOSITORY_ID, 0, 20), - createRepositoryUrlProvider(BASEURL).getChangesetUrl( - REPOSITORY_ID, 0, 20)); - } - - /** - * Method description - * - */ - @Test - public void testGetContentUrl() - { - assertEquals( - getExpectedContentUrl(BASEURL, REPOSITORY_ID, PATH, REVISION), - createRepositoryUrlProvider(BASEURL).getContentUrl( - REPOSITORY_ID, PATH, REVISION)); - } - - /** - * Method description - * - */ - @Test - public void testGetDetailUrl() - { - assertEquals(getExpectedDetailUrl(BASEURL, TYPE, NAME), - createRepositoryUrlProvider(BASEURL).getDetailUrl(TYPE, NAME)); - } - - /** - * Method description - * - */ - @Test - public void testGetDiffUrl() - { - assertEquals(getExpectedDiffUrl(BASEURL, REPOSITORY_ID, REVISION), - createRepositoryUrlProvider(BASEURL).getDiffUrl(REPOSITORY_ID, - REVISION)); - } -} diff --git a/scm-core/src/test/java/sonia/scm/url/RestModelUrlProviderTestBase.java b/scm-core/src/test/java/sonia/scm/url/RestModelUrlProviderTestBase.java deleted file mode 100644 index 2e7f25818f..0000000000 --- a/scm-core/src/test/java/sonia/scm/url/RestModelUrlProviderTestBase.java +++ /dev/null @@ -1,159 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.util.HttpUtil; - -/** - * - * @author Sebastian Sdorra - */ -public abstract class RestModelUrlProviderTestBase - extends ModelUrlProviderTestBase -{ - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - protected abstract UrlProvider createUrlProvider(String baseUrl); - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - protected abstract String getExtension(); - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - @Override - protected ModelUrlProvider createGroupModelUrlProvider(String baseUrl) - { - return createUrlProvider(baseUrl).getGroupUrlProvider(); - } - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - @Override - protected ModelUrlProvider createRepositoryModelUrlProvider(String baseUrl) - { - return createUrlProvider(baseUrl).getRepositoryUrlProvider(); - } - - /** - * Method description - * - * - * @param baseUrl - * @param urlPart - * - * @return - */ - protected String createRestUrl(String baseUrl, String urlPart) - { - return createRestUrl(baseUrl, urlPart, getExtension()); - } - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - @Override - protected ModelUrlProvider createUserModelUrlProvider(String baseUrl) - { - return createUrlProvider(baseUrl).getUserUrlProvider(); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param baseUrl - * @param model - * - * @return - */ - @Override - protected String getExpectedAllUrl(String baseUrl, String model) - { - return createRestUrl(baseUrl, model); - } - - /** - * Method description - * - * - * @param baseUrl - * @param model - * @param item - * - * @return - */ - @Override - protected String getExpectedDetailUrl(String baseUrl, String model, - String item) - { - return createRestUrl(baseUrl, - model.concat(HttpUtil.SEPARATOR_PATH).concat(item)); - } -} diff --git a/scm-core/src/test/java/sonia/scm/url/RestRepositoryUrlProviderTestBase.java b/scm-core/src/test/java/sonia/scm/url/RestRepositoryUrlProviderTestBase.java deleted file mode 100644 index 31783f7eea..0000000000 --- a/scm-core/src/test/java/sonia/scm/url/RestRepositoryUrlProviderTestBase.java +++ /dev/null @@ -1,230 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.util.HttpUtil; - -/** - * - * @author Sebastian Sdorra - */ -public abstract class RestRepositoryUrlProviderTestBase - extends RepositoryUrlProviderTestBase -{ - - /** Field description */ - public static final String URLPART_PREFIX = "repositories"; - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - protected abstract String getExtension(); - - /** - * Method description - * - * - * @param baseUrl - * @param repositoryId - * @param path - * @param revision - * - * @return - */ - @Override - protected String getExpectedBlameUrl(String baseUrl, String repositoryId, - String path, String revision) - { - return createRestUrl( - baseUrl, - repositoryId.concat(HttpUtil.SEPARATOR_PATH).concat("blame")).concat( - "?path=").concat(path).concat("&revision=").concat(revision); - } - - /** - * Method description - * - * - * @param baseUrl - * @param repositoryId - * @param path - * @param revision - * - * @return - */ - @Override - protected String getExpectedBrowseUrl(String baseUrl, String repositoryId, - String path, String revision) - { - return createRestUrl( - baseUrl, - repositoryId.concat(HttpUtil.SEPARATOR_PATH).concat("browse")).concat( - "?path=").concat(path).concat("&revision=").concat(revision); - } - - /** - * Method description - * - * - * @param baseUrl - * @param repositoryId - * @param path - * @param revision - * @param start - * @param limit - * - * @return - */ - @Override - protected String getExpectedChangesetUrl(String baseUrl, String repositoryId, - String path, String revision, int start, int limit) - { - return createRestUrl( - baseUrl, - repositoryId.concat(HttpUtil.SEPARATOR_PATH).concat( - "changesets")).concat("?path=").concat(path).concat( - "&revision=").concat(revision).concat("&start=").concat( - String.valueOf(start)).concat("&limit=").concat( - String.valueOf(limit)); - } - - /** - * Method description - * - * - * @param baseUrl - * @param repositoryId - * @param start - * @param limit - * - * @return - */ - @Override - protected String getExpectedChangesetUrl(String baseUrl, String repositoryId, - int start, int limit) - { - return createRestUrl( - baseUrl, - repositoryId.concat(HttpUtil.SEPARATOR_PATH).concat( - "changesets")).concat("?start=").concat(String.valueOf(start)).concat( - "&limit=").concat(String.valueOf(limit)); - } - - /** - * Method description - * - * - * @param baseUrl - * @param repositoryId - * @param path - * @param revision - * - * @return - */ - @Override - protected String getExpectedContentUrl(String baseUrl, String repositoryId, - String path, String revision) - { - return createRestUrl( - baseUrl, - "repositories".concat(HttpUtil.SEPARATOR_PATH).concat( - repositoryId).concat(HttpUtil.SEPARATOR_PATH).concat( - "content"), "").concat("?path=").concat(path).concat( - "&revision=").concat(revision); - } - - /** - * Method description - * - * - * @param baseUrl - * @param type - * @param name - * - * @return - */ - @Override - protected String getExpectedDetailUrl(String baseUrl, String type, - String name) - { - return createRestUrl(baseUrl, - type.concat(HttpUtil.SEPARATOR_PATH).concat(name)); - } - - /** - * Method description - * - * - * @param baseUrl - * @param repositoryId - * @param revision - * - * @return - */ - @Override - protected String getExpectedDiffUrl(String baseUrl, String repositoryId, - String revision) - { - return createRestUrl( - baseUrl, - "repositories".concat(HttpUtil.SEPARATOR_PATH).concat( - repositoryId).concat(HttpUtil.SEPARATOR_PATH).concat( - "diff"), "").concat("?revision=").concat(revision); - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param baseUrl - * @param urlPart - * - * @return - */ - private String createRestUrl(String baseUrl, String urlPart) - { - return createRestUrl( - baseUrl, - URLPART_PREFIX.concat(HttpUtil.SEPARATOR_PATH).concat(urlPart), - getExtension()); - } -} diff --git a/scm-core/src/test/java/sonia/scm/url/RestUrlProviderTestBase.java b/scm-core/src/test/java/sonia/scm/url/RestUrlProviderTestBase.java deleted file mode 100644 index 3b39e22816..0000000000 --- a/scm-core/src/test/java/sonia/scm/url/RestUrlProviderTestBase.java +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - -package sonia.scm.url; - -/** - * - * @author Sebastian Sdorra - */ -public abstract class RestUrlProviderTestBase extends UrlProviderTestBase -{ - - /** - * Method description - * - * - * @return - */ - protected abstract String getExtension(); - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param baseUrl - * @param urlPart - * - * @return - */ - protected String createRestUrl(String baseUrl, String urlPart) - { - return createRestUrl(baseUrl, urlPart, getExtension()); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - @Override - protected String getExpectedAuthenticationUrl(String baseUrl) - { - return createRestUrl(baseUrl, "auth/access_token"); - } - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - @Override - protected String getExpectedConfigUrl(String baseUrl) - { - return createRestUrl(baseUrl, "config"); - } - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - @Override - protected String getExpectedStateUrl(String baseUrl) - { - return createRestUrl(baseUrl, "auth"); - } -} diff --git a/scm-core/src/test/java/sonia/scm/url/UrlProviderTestBase.java b/scm-core/src/test/java/sonia/scm/url/UrlProviderTestBase.java deleted file mode 100644 index 61c35b7b64..0000000000 --- a/scm-core/src/test/java/sonia/scm/url/UrlProviderTestBase.java +++ /dev/null @@ -1,156 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * - * @author Sebastian Sdorra - */ -public abstract class UrlProviderTestBase extends UrlTestBase -{ - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * - * @param baseUrl - * @return - */ - protected abstract UrlProvider createUrlProvider(String baseUrl); - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - protected abstract String getExpectedAuthenticationUrl(String baseUrl); - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - protected abstract String getExpectedConfigUrl(String baseUrl); - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - protected abstract String getExpectedStateUrl(String baseUrl); - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Test - public void testGetAuthenticationUrl() - { - assertEquals(getExpectedAuthenticationUrl(BASEURL), - createUrlProvider(BASEURL).getAuthenticationUrl()); - } - - /** - * Method description - * - */ - @Test - public void testGetConfigUrl() - { - assertEquals(getExpectedConfigUrl(BASEURL), - createUrlProvider(BASEURL).getConfigUrl()); - } - - /** - * Method description - * - */ - @Test - public void testGetGroupUrlProvider() - { - assertNotNull(createUrlProvider(BASEURL).getGroupUrlProvider()); - } - - /** - * Method description - * - */ - @Test - public void testGetStateUrl() - { - assertEquals(getExpectedStateUrl(BASEURL), - createUrlProvider(BASEURL).getStateUrl()); - } - - /** - * Method description - * - */ - @Test - public void testGetUserRepositoryUrlProvider() - { - assertNotNull(createUrlProvider(BASEURL).getRepositoryUrlProvider()); - } - - /** - * Method description - * - */ - @Test - public void testGetUserUrlProvider() - { - assertNotNull(createUrlProvider(BASEURL).getUserUrlProvider()); - } -} diff --git a/scm-core/src/test/java/sonia/scm/url/UrlTestBase.java b/scm-core/src/test/java/sonia/scm/url/UrlTestBase.java deleted file mode 100644 index 28202cb420..0000000000 --- a/scm-core/src/test/java/sonia/scm/url/UrlTestBase.java +++ /dev/null @@ -1,133 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.util.HttpUtil; - -/** - * - * @author Sebastian Sdorra - */ -public abstract class UrlTestBase -{ - - /** Field description */ - public static final String EXTENSION_JSON = ".json"; - - /** Field description */ - public static final String EXTENSION_XML = ".xml"; - - /** Field description */ - public static final String URLSUFFIX_INDEX = "/index.html"; - - /** Field description */ - public static final String URLSUFFIX_RESTAPI = "/api/rest/"; - - /** Field description */ - protected static final String BASEURL = "http://scm.scm-manager.org/scm"; - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - protected String createBaseRestUrl(String baseUrl) - { - return baseUrl.concat(URLSUFFIX_RESTAPI); - } - - /** - * Method description - * - * - * @param baseUrl - * @param urlPart - * @param extension - * - * @return - */ - protected String createRestUrl(String baseUrl, String urlPart, - String extension) - { - return createBaseRestUrl(baseUrl).concat(urlPart).concat(extension); - } - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - protected String createWuiUrl(String baseUrl) - { - return baseUrl.concat(URLSUFFIX_INDEX); - } - - /** - * Method description - * - * - * @param baseUrl - * @param param - * - * @return - */ - protected String createWuiUrl(String baseUrl, String param) - { - return baseUrl.concat(URLSUFFIX_INDEX).concat( - HttpUtil.SEPARATOR_HASH).concat(param); - } - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - protected UrlProvider createWuiUrlProvider(String baseUrl) - { - return UrlProviderFactory.createUrlProvider(baseUrl, - UrlProviderFactory.TYPE_WUI); - } -} diff --git a/scm-core/src/test/java/sonia/scm/url/UrlUtilTest.java b/scm-core/src/test/java/sonia/scm/url/UrlUtilTest.java deleted file mode 100644 index 255d7912df..0000000000 --- a/scm-core/src/test/java/sonia/scm/url/UrlUtilTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * - * @author Sebastian Sdorra - */ -public class UrlUtilTest -{ - - /** - * Method description - * - */ - @Test - public void testFixRevision() - { - assertEquals("42694c4a4a7a", UrlUtil.fixRevision("42694c4a4a7a")); - assertEquals("42694c4a4a7a", UrlUtil.fixRevision("298:42694c4a4a7a")); - assertNull(UrlUtil.fixRevision(null)); - } -} diff --git a/scm-core/src/test/java/sonia/scm/url/WUIModelUrlProviderTest.java b/scm-core/src/test/java/sonia/scm/url/WUIModelUrlProviderTest.java deleted file mode 100644 index b6073a841a..0000000000 --- a/scm-core/src/test/java/sonia/scm/url/WUIModelUrlProviderTest.java +++ /dev/null @@ -1,158 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - -package sonia.scm.url; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.HashMap; -import java.util.Map; - -/** - * - * @author Sebastian Sdorra - */ -public class WUIModelUrlProviderTest extends ModelUrlProviderTestBase -{ - - /** - * Constructs ... - * - */ - public WUIModelUrlProviderTest() - { - modelMap = new HashMap(); - modelMap.put(MODEL_REPOSITORY, "repositoryPanel"); - modelMap.put(MODEL_USERS, "userPanel"); - modelMap.put(MODEL_GROUPS, "groupPanel"); - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - @Override - protected ModelUrlProvider createGroupModelUrlProvider(String baseUrl) - { - return createWuiUrlProvider(baseUrl).getGroupUrlProvider(); - } - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - @Override - protected ModelUrlProvider createRepositoryModelUrlProvider(String baseUrl) - { - return createWuiUrlProvider(baseUrl).getRepositoryUrlProvider(); - } - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - @Override - protected ModelUrlProvider createUserModelUrlProvider(String baseUrl) - { - return createWuiUrlProvider(baseUrl).getUserUrlProvider(); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param baseUrl - * @param model - * - * @return - */ - @Override - protected String getExpectedAllUrl(String baseUrl, String model) - { - return createModelBaseUrl(baseUrl, model); - } - - /** - * Method description - * - * - * @param baseUrl - * @param model - * @param item - * - * @return - */ - @Override - protected String getExpectedDetailUrl(String baseUrl, String model, - String item) - { - return createModelBaseUrl(baseUrl, model).concat( - WUIUrlBuilder.SEPARATOR).concat(item); - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param baseUrl - * @param model - * - * @return - */ - private String createModelBaseUrl(String baseUrl, String model) - { - return createWuiUrl(baseUrl, modelMap.get(model)); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private Map modelMap; -} diff --git a/scm-core/src/test/java/sonia/scm/url/WUIRepositoryUrlProviderTest.java b/scm-core/src/test/java/sonia/scm/url/WUIRepositoryUrlProviderTest.java deleted file mode 100644 index 91a1a8fb8a..0000000000 --- a/scm-core/src/test/java/sonia/scm/url/WUIRepositoryUrlProviderTest.java +++ /dev/null @@ -1,218 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -import sonia.scm.util.HttpUtil; - -/** - * - * @author Sebastian Sdorra - */ -public class WUIRepositoryUrlProviderTest extends RepositoryUrlProviderTestBase -{ - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - @Override - protected RepositoryUrlProvider createRepositoryUrlProvider(String baseUrl) - { - return UrlProviderFactory.createUrlProvider(baseUrl, - UrlProviderFactory.TYPE_WUI).getRepositoryUrlProvider(); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param baseUrl - * @param repositoryId - * @param path - * @param revision - * - * @return - */ - @Override - protected String getExpectedBlameUrl(String baseUrl, String repositoryId, - String path, String revision) - { - return createRepositoryWuiUrl(baseUrl, "contentPanel", repositoryId).concat( - ";").concat(revision).concat(";").concat(path).concat(";blame"); - } - - /** - * Method description - * - * - * @param baseUrl - * @param repositoryId - * @param path - * @param revision - * - * @return - */ - @Override - protected String getExpectedBrowseUrl(String baseUrl, String repositoryId, - String path, String revision) - { - return createRepositoryWuiUrl( - baseUrl, "repositoryBrowser", repositoryId).concat(";").concat( - revision).concat(";").concat(path); - } - - /** - * Method description - * - * - * @param baseUrl - * @param repositoryId - * @param path - * @param revision - * @param start - * @param limit - * - * @return - */ - @Override - protected String getExpectedChangesetUrl(String baseUrl, String repositoryId, - String path, String revision, int start, int limit) - { - return createRepositoryWuiUrl(baseUrl, "contentPanel", repositoryId).concat( - ";").concat(revision).concat(";").concat(path).concat(";history"); - } - - /** - * Method description - * - * - * @param baseUrl - * @param repositoryId - * @param start - * @param limit - * - * @return - */ - @Override - protected String getExpectedChangesetUrl(String baseUrl, String repositoryId, - int start, int limit) - { - return createRepositoryWuiUrl( - baseUrl, "repositoryChangesetViewerPanel", repositoryId).concat( - ";").concat(String.valueOf(start)).concat(";").concat( - String.valueOf(limit)); - } - - /** - * Method description - * - * - * @param baseUrl - * @param repositoryId - * @param path - * @param revision - * - * @return - */ - @Override - protected String getExpectedContentUrl(String baseUrl, String repositoryId, - String path, String revision) - { - return createRepositoryWuiUrl(baseUrl, "contentPanel", repositoryId).concat( - ";").concat(revision).concat(";").concat(path).concat(";history"); - } - - /** - * Method description - * - * - * @param baseUrl - * @param type - * @param name - * - * @return - */ - @Override - protected String getExpectedDetailUrl(String baseUrl, String type, - String name) - { - return createRepositoryWuiUrl( - baseUrl, "repositoryPanel", - type.concat(HttpUtil.SEPARATOR_PATH).concat(name)); - } - - /** - * Method description - * - * - * @param baseUrl - * @param repositoryId - * @param revision - * - * @return - */ - @Override - protected String getExpectedDiffUrl(String baseUrl, String repositoryId, - String revision) - { - return createRepositoryWuiUrl(baseUrl, "diffPanel", - repositoryId).concat(";").concat(revision); - } - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param baseUrl - * @param component - * @param repository - * - * @return - */ - private String createRepositoryWuiUrl(String baseUrl, String component, - String repository) - { - return createWuiUrl(baseUrl, component).concat( - WUIUrlBuilder.SEPARATOR).concat(repository); - } -} diff --git a/scm-core/src/test/java/sonia/scm/url/WUIUrlBuilderTest.java b/scm-core/src/test/java/sonia/scm/url/WUIUrlBuilderTest.java deleted file mode 100644 index 4fdefc5fb1..0000000000 --- a/scm-core/src/test/java/sonia/scm/url/WUIUrlBuilderTest.java +++ /dev/null @@ -1,114 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -import org.junit.Test; - -import sonia.scm.util.HttpUtil; - -import static org.junit.Assert.*; - -/** - * - * @author Sebastian Sdorra - */ -public class WUIUrlBuilderTest -{ - - /** Field description */ - private static final String BASEURL = - "http://scm.scm-manager.org/scm/index.html"; - - /** Field description */ - private static final String COMPONENT = "testCmp"; - - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - */ - @Test - public void testStringAppend() - { - WUIUrlBuilder builder = createBuilder(); - - builder.append("testParam"); - assertEquals(createBaseWuiUrl().concat(";testParam"), builder.toString()); - builder = createBuilder(); - builder.append("param1").append("param2").append("param3"); - assertEquals(createBaseWuiUrl().concat(";param1;param2;param3"), - builder.toString()); - } - - /** - * Method description - * - */ - @Test - public void testIntAppend() - { - WUIUrlBuilder builder = createBuilder(); - - builder.append(3); - assertEquals(createBaseWuiUrl().concat(";3"), builder.toString()); - builder = createBuilder(); - builder.append(1).append(2).append(3); - assertEquals(createBaseWuiUrl().concat(";1;2;3"), - builder.toString()); - } - - /** - * Method description - * - * - * @return - */ - private String createBaseWuiUrl() - { - return BASEURL.concat(HttpUtil.SEPARATOR_HASH).concat(COMPONENT); - } - - /** - * Method description - * - * - * @return - */ - private WUIUrlBuilder createBuilder() - { - return new WUIUrlBuilder(BASEURL, COMPONENT); - } -} diff --git a/scm-core/src/test/java/sonia/scm/url/WUIUrlProviderTest.java b/scm-core/src/test/java/sonia/scm/url/WUIUrlProviderTest.java deleted file mode 100644 index 19ec89835a..0000000000 --- a/scm-core/src/test/java/sonia/scm/url/WUIUrlProviderTest.java +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -/** - * - * @author Sebastian Sdorra - */ -public class WUIUrlProviderTest extends UrlProviderTestBase -{ - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - @Override - protected UrlProvider createUrlProvider(String baseUrl) - { - return UrlProviderFactory.createUrlProvider(baseUrl, - UrlProviderFactory.TYPE_WUI); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - @Override - protected String getExpectedAuthenticationUrl(String baseUrl) - { - return createWuiUrl(baseUrl); - } - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - @Override - protected String getExpectedConfigUrl(String baseUrl) - { - return createWuiUrl(baseUrl, "scmConfig"); - } - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - @Override - protected String getExpectedStateUrl(String baseUrl) - { - return createWuiUrl(baseUrl); - } -} diff --git a/scm-core/src/test/java/sonia/scm/url/XMLRestModelUrlProviderTest.java b/scm-core/src/test/java/sonia/scm/url/XMLRestModelUrlProviderTest.java deleted file mode 100644 index 7017e0551a..0000000000 --- a/scm-core/src/test/java/sonia/scm/url/XMLRestModelUrlProviderTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - -package sonia.scm.url; - -/** - * - * @author Sebastian Sdorra - */ -public class XMLRestModelUrlProviderTest extends RestModelUrlProviderTestBase -{ - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - @Override - protected UrlProvider createUrlProvider(String baseUrl) - { - return UrlProviderFactory.createUrlProvider(baseUrl, - UrlProviderFactory.TYPE_RESTAPI_XML); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - @Override - protected String getExtension() - { - return EXTENSION_XML; - } -} diff --git a/scm-core/src/test/java/sonia/scm/url/XMLRestUrlProviderTest.java b/scm-core/src/test/java/sonia/scm/url/XMLRestUrlProviderTest.java deleted file mode 100644 index 33e19aa258..0000000000 --- a/scm-core/src/test/java/sonia/scm/url/XMLRestUrlProviderTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - -package sonia.scm.url; - -/** - * - * @author Sebastian Sdorra - */ -public class XMLRestUrlProviderTest extends RestUrlProviderTestBase -{ - - /** - * Method description - * - * - * @param baseUrl - * - * @return - */ - @Override - protected UrlProvider createUrlProvider(String baseUrl) - { - return UrlProviderFactory.createUrlProvider(baseUrl, - UrlProviderFactory.TYPE_RESTAPI_XML); - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - @Override - protected String getExtension() - { - return EXTENSION_XML; - } -} diff --git a/scm-core/src/test/java/sonia/scm/util/HttpUtilTest.java b/scm-core/src/test/java/sonia/scm/util/HttpUtilTest.java index b85221f8c8..5e6fa3e10e 100644 --- a/scm-core/src/test/java/sonia/scm/util/HttpUtilTest.java +++ b/scm-core/src/test/java/sonia/scm/util/HttpUtilTest.java @@ -54,6 +54,18 @@ import javax.servlet.http.HttpServletRequest; public class HttpUtilTest { + @Test + public void concatenateTest() { + assertEquals( + "/scm/git/hitchhiker/tricia", + HttpUtil.concatenate("/scm", "git", "hitchhiker", "tricia") + ); + assertEquals( + "scm/git/hitchhiker/tricia", + HttpUtil.concatenate("scm", "git", "hitchhiker", "tricia") + ); + } + /** * Method description * @@ -63,19 +75,19 @@ public class HttpUtilTest { //J- assertEquals( - "http://www.scm-manager/scm/test", + "http://www.scm-manager/scm/test", HttpUtil.append("http://www.scm-manager/scm/", "test") ); assertEquals( - "http://www.scm-manager/scm/test", + "http://www.scm-manager/scm/test", HttpUtil.append("http://www.scm-manager/scm", "test") ); assertEquals( - "http://www.scm-manager/scm/test", + "http://www.scm-manager/scm/test", HttpUtil.append("http://www.scm-manager/scm", "/test") ); assertEquals( - "http://www.scm-manager/scm/test", + "http://www.scm-manager/scm/test", HttpUtil.append("http://www.scm-manager/scm/", "/test") ); //J+ diff --git a/scm-dao-xml/src/main/java/sonia/scm/repository/xml/XmlRepositoryDAO.java b/scm-dao-xml/src/main/java/sonia/scm/repository/xml/XmlRepositoryDAO.java index 7c17c365aa..4510706721 100644 --- a/scm-dao-xml/src/main/java/sonia/scm/repository/xml/XmlRepositoryDAO.java +++ b/scm-dao-xml/src/main/java/sonia/scm/repository/xml/XmlRepositoryDAO.java @@ -36,11 +36,11 @@ package sonia.scm.repository.xml; import com.google.inject.Inject; import com.google.inject.Singleton; - +import sonia.scm.repository.NamespaceAndName; import sonia.scm.repository.Repository; import sonia.scm.repository.RepositoryDAO; -import sonia.scm.xml.AbstractXmlDAO; import sonia.scm.store.ConfigurationStoreFactory; +import sonia.scm.xml.AbstractXmlDAO; /** * @@ -71,36 +71,18 @@ public class XmlRepositoryDAO //~--- methods -------------------------------------------------------------- - /** - * Method description - * - * - * @param type - * @param name - * - * @return - */ @Override - public boolean contains(String type, String name) + public boolean contains(NamespaceAndName namespaceAndName) { - return db.contains(type, name); + return db.contains(namespaceAndName); } //~--- get methods ---------------------------------------------------------- - /** - * Method description - * - * - * @param type - * @param name - * - * @return - */ @Override - public Repository get(String type, String name) + public Repository get(NamespaceAndName namespaceAndName) { - return db.get(type, name); + return db.get(namespaceAndName); } //~--- methods -------------------------------------------------------------- diff --git a/scm-dao-xml/src/main/java/sonia/scm/repository/xml/XmlRepositoryDatabase.java b/scm-dao-xml/src/main/java/sonia/scm/repository/xml/XmlRepositoryDatabase.java index a5c599c291..93be611213 100644 --- a/scm-dao-xml/src/main/java/sonia/scm/repository/xml/XmlRepositoryDatabase.java +++ b/scm-dao-xml/src/main/java/sonia/scm/repository/xml/XmlRepositoryDatabase.java @@ -35,34 +35,26 @@ package sonia.scm.repository.xml; //~--- non-JDK imports -------------------------------------------------------- +import sonia.scm.repository.NamespaceAndName; import sonia.scm.repository.Repository; import sonia.scm.xml.XmlDatabase; -//~--- JDK imports ------------------------------------------------------------ - -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.Map; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.Map; + +//~--- JDK imports ------------------------------------------------------------ -/** - * - * @author Sebastian Sdorra - */ @XmlRootElement(name = "repository-db") @XmlAccessorType(XmlAccessType.FIELD) public class XmlRepositoryDatabase implements XmlDatabase { - /** - * Constructs ... - * - */ public XmlRepositoryDatabase() { long c = System.currentTimeMillis(); @@ -71,108 +63,43 @@ public class XmlRepositoryDatabase implements XmlDatabase lastModified = c; } - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @param type - * @param name - * - * @return - */ - static String createKey(String type, String name) + static String createKey(NamespaceAndName namespaceAndName) { - return type.concat(":").concat(name); + return namespaceAndName.getNamespace() + ":" + namespaceAndName.getName(); } - /** - * Method description - * - * - * @param repository - * - * @return - */ static String createKey(Repository repository) { - return createKey(repository.getType(), repository.getName()); + return createKey(repository.getNamespaceAndName()); } - /** - * Method description - * - * - * @param repository - */ @Override public void add(Repository repository) { repositoryMap.put(createKey(repository), repository); } - /** - * Method description - * - * - * - * @param type - * @param name - * - * @return - */ - public boolean contains(String type, String name) + public boolean contains(NamespaceAndName namespaceAndName) { - return repositoryMap.containsKey(createKey(type, name)); + return repositoryMap.containsKey(createKey(namespaceAndName)); } - /** - * Method description - * - * - * @param id - * - * @return - */ @Override public boolean contains(String id) { return get(id) != null; } - /** - * Method description - * - * - * @param repository - * - * @return - */ public boolean contains(Repository repository) { return repositoryMap.containsKey(createKey(repository)); } - /** - * Method description - * - * - * @param repository - */ public void remove(Repository repository) { repositoryMap.remove(createKey(repository)); } - /** - * Method description - * - * - * @param id - * - * @return - */ @Override public Repository remove(String id) { @@ -183,12 +110,6 @@ public class XmlRepositoryDatabase implements XmlDatabase return r; } - /** - * Method description - * - * - * @return - */ @Override public Collection values() { @@ -197,18 +118,9 @@ public class XmlRepositoryDatabase implements XmlDatabase //~--- get methods ---------------------------------------------------------- - /** - * Method description - * - * - * @param type - * @param name - * - * @return - */ - public Repository get(String type, String name) + public Repository get(NamespaceAndName namespaceAndName) { - return repositoryMap.get(createKey(type, name)); + return repositoryMap.get(createKey(namespaceAndName)); } /** @@ -298,6 +210,5 @@ public class XmlRepositoryDatabase implements XmlDatabase /** Field description */ @XmlJavaTypeAdapter(XmlRepositoryMapAdapter.class) @XmlElement(name = "repositories") - private Map repositoryMap = new LinkedHashMap(); + private Map repositoryMap = new LinkedHashMap<>(); } diff --git a/scm-dao-xml/src/main/java/sonia/scm/repository/xml/XmlRepositoryMapAdapter.java b/scm-dao-xml/src/main/java/sonia/scm/repository/xml/XmlRepositoryMapAdapter.java index a90a2d4fa9..4d6686dfb2 100644 --- a/scm-dao-xml/src/main/java/sonia/scm/repository/xml/XmlRepositoryMapAdapter.java +++ b/scm-dao-xml/src/main/java/sonia/scm/repository/xml/XmlRepositoryMapAdapter.java @@ -37,57 +37,28 @@ package sonia.scm.repository.xml; import sonia.scm.repository.Repository; -//~--- JDK imports ------------------------------------------------------------ - +import javax.xml.bind.annotation.adapters.XmlAdapter; import java.util.LinkedHashMap; import java.util.Map; -import javax.xml.bind.annotation.adapters.XmlAdapter; +//~--- JDK imports ------------------------------------------------------------ /** * * @author Sebastian Sdorra */ -public class XmlRepositoryMapAdapter - extends XmlAdapter> -{ +public class XmlRepositoryMapAdapter extends XmlAdapter> { - /** - * Method description - * - * - * @param repositoryMap - * - * @return - * - * @throws Exception - */ @Override - public XmlRepositoryList marshal(Map repositoryMap) - throws Exception - { + public XmlRepositoryList marshal(Map repositoryMap) { return new XmlRepositoryList(repositoryMap); } - /** - * Method description - * - * - * @param repositories - * - * @return - * - * @throws Exception - */ @Override - public Map unmarshal(XmlRepositoryList repositories) - throws Exception - { - Map repositoryMap = new LinkedHashMap(); + public Map unmarshal(XmlRepositoryList repositories) { + Map repositoryMap = new LinkedHashMap<>(); - for (Repository repository : repositories) - { + for (Repository repository : repositories) { repositoryMap.put(XmlRepositoryDatabase.createKey(repository), repository); } diff --git a/scm-plugins/scm-git-plugin/src/main/java/sonia/scm/repository/GitRepositoryModifyListener.java b/scm-plugins/scm-git-plugin/src/main/java/sonia/scm/repository/GitRepositoryModifyListener.java index db2b7b09ec..1cbcdc35bf 100644 --- a/scm-plugins/scm-git-plugin/src/main/java/sonia/scm/repository/GitRepositoryModifyListener.java +++ b/scm-plugins/scm-git-plugin/src/main/java/sonia/scm/repository/GitRepositoryModifyListener.java @@ -30,9 +30,9 @@ */ package sonia.scm.repository; +import com.github.legman.Subscribe; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; -import com.google.common.eventbus.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sonia.scm.EagerSingleton; diff --git a/scm-plugins/scm-git-plugin/src/main/java/sonia/scm/repository/spi/GitRepositoryServiceResolver.java b/scm-plugins/scm-git-plugin/src/main/java/sonia/scm/repository/spi/GitRepositoryServiceResolver.java index 70609eee87..52c5171627 100644 --- a/scm-plugins/scm-git-plugin/src/main/java/sonia/scm/repository/spi/GitRepositoryServiceResolver.java +++ b/scm-plugins/scm-git-plugin/src/main/java/sonia/scm/repository/spi/GitRepositoryServiceResolver.java @@ -76,7 +76,7 @@ public class GitRepositoryServiceResolver implements RepositoryServiceResolver * @return */ @Override - public GitRepositoryServiceProvider reslove(Repository repository) + public GitRepositoryServiceProvider resolve(Repository repository) { GitRepositoryServiceProvider provider = null; diff --git a/scm-plugins/scm-git-plugin/src/main/java/sonia/scm/web/GitReceiveHook.java b/scm-plugins/scm-git-plugin/src/main/java/sonia/scm/web/GitReceiveHook.java index 3ecd6047e9..eeda60ed02 100644 --- a/scm-plugins/scm-git-plugin/src/main/java/sonia/scm/web/GitReceiveHook.java +++ b/scm-plugins/scm-git-plugin/src/main/java/sonia/scm/web/GitReceiveHook.java @@ -40,24 +40,21 @@ import org.eclipse.jgit.transport.PostReceiveHook; import org.eclipse.jgit.transport.PreReceiveHook; import org.eclipse.jgit.transport.ReceiveCommand; import org.eclipse.jgit.transport.ReceivePack; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import sonia.scm.repository.GitRepositoryHandler; import sonia.scm.repository.RepositoryHookType; import sonia.scm.repository.RepositoryUtil; import sonia.scm.repository.spi.GitHookContextProvider; import sonia.scm.repository.spi.HookEventFacade; -//~--- JDK imports ------------------------------------------------------------ - import java.io.File; import java.io.IOException; - import java.util.Collection; import java.util.List; +//~--- JDK imports ------------------------------------------------------------ + /** * * @author Sebastian Sdorra @@ -131,15 +128,14 @@ public class GitReceiveHook implements PreReceiveHook, PostReceiveHook try { Repository repository = rpack.getRepository(); - String repositoryName = resolveRepositoryName(repository); + String id = resolveRepositoryId(repository); - logger.trace("resolved repository name to {}", repositoryName); + logger.trace("resolved repository to id {}", id); GitHookContextProvider context = new GitHookContextProvider(rpack, receiveCommands); - hookEventFacade.handle(GitRepositoryHandler.TYPE_NAME, - repositoryName).fireHookEvent(type, context); + hookEventFacade.handle(id).fireHookEvent(type, context); } catch (Exception ex) @@ -191,7 +187,7 @@ public class GitReceiveHook implements PreReceiveHook, PostReceiveHook * * @throws IOException */ - private String resolveRepositoryName(Repository repository) throws IOException + private String resolveRepositoryId(Repository repository) throws IOException { File directory; @@ -204,7 +200,7 @@ public class GitReceiveHook implements PreReceiveHook, PostReceiveHook directory = repository.getWorkTree(); } - return RepositoryUtil.getRepositoryName(handler, directory); + return RepositoryUtil.getRepositoryId(handler, directory); } //~--- fields --------------------------------------------------------------- diff --git a/scm-plugins/scm-git-plugin/src/main/java/sonia/scm/web/GitRepositoryResolver.java b/scm-plugins/scm-git-plugin/src/main/java/sonia/scm/web/GitRepositoryResolver.java index 2ddf4b3de9..76e742a71a 100644 --- a/scm-plugins/scm-git-plugin/src/main/java/sonia/scm/web/GitRepositoryResolver.java +++ b/scm-plugins/scm-git-plugin/src/main/java/sonia/scm/web/GitRepositoryResolver.java @@ -36,8 +36,8 @@ package sonia.scm.web; //~--- non-JDK imports -------------------------------------------------------- import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; import com.google.inject.Inject; - import org.eclipse.jgit.errors.RepositoryNotFoundException; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.RepositoryCache; @@ -46,19 +46,17 @@ import org.eclipse.jgit.transport.resolver.RepositoryResolver; import org.eclipse.jgit.transport.resolver.ServiceNotAuthorizedException; import org.eclipse.jgit.transport.resolver.ServiceNotEnabledException; import org.eclipse.jgit.util.FS; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import sonia.scm.repository.GitConfig; import sonia.scm.repository.GitRepositoryHandler; +import sonia.scm.repository.RepositoryProvider; -//~--- JDK imports ------------------------------------------------------------ - +import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; -import javax.servlet.http.HttpServletRequest; +//~--- JDK imports ------------------------------------------------------------ /** * @@ -72,17 +70,11 @@ public class GitRepositoryResolver implements RepositoryResolver env = ImmutableMap.of( "repository", repository, - "branches", createBranchesModel(repository), - "commitViewLink", rup.getChangesetUrl(repository.getId(), 0, 20), - "sourceViewLink", rup.getBrowseUrl(repository.getId(), null, null) + "branches", createBranchesModel(repository) ); //J+ diff --git a/scm-plugins/scm-git-plugin/src/main/java/sonia/scm/web/lfs/LfsStoreRemoveListener.java b/scm-plugins/scm-git-plugin/src/main/java/sonia/scm/web/lfs/LfsStoreRemoveListener.java index 3d69dcabe6..18fb333c74 100644 --- a/scm-plugins/scm-git-plugin/src/main/java/sonia/scm/web/lfs/LfsStoreRemoveListener.java +++ b/scm-plugins/scm-git-plugin/src/main/java/sonia/scm/web/lfs/LfsStoreRemoveListener.java @@ -32,7 +32,7 @@ package sonia.scm.web.lfs; -import com.google.common.eventbus.Subscribe; +import com.github.legman.Subscribe; import com.google.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/scm-plugins/scm-git-plugin/src/main/resources/sonia/scm/git.index.mustache b/scm-plugins/scm-git-plugin/src/main/resources/sonia/scm/git.index.mustache index 81d7a5bfa3..4571e327e3 100644 --- a/scm-plugins/scm-git-plugin/src/main/resources/sonia/scm/git.index.mustache +++ b/scm-plugins/scm-git-plugin/src/main/resources/sonia/scm/git.index.mustache @@ -118,23 +118,6 @@ {{/branches}} - -

Notes

- -
-

- This page is only a quick view for git commits. - The full commit view is here. -

- -

Git Informations

    @@ -144,4 +127,4 @@
- \ No newline at end of file + diff --git a/scm-plugins/scm-git-plugin/src/test/java/sonia/scm/repository/GitRepositoryHandlerTest.java b/scm-plugins/scm-git-plugin/src/test/java/sonia/scm/repository/GitRepositoryHandlerTest.java index 5d9b338875..47ca08b597 100644 --- a/scm-plugins/scm-git-plugin/src/test/java/sonia/scm/repository/GitRepositoryHandlerTest.java +++ b/scm-plugins/scm-git-plugin/src/test/java/sonia/scm/repository/GitRepositoryHandlerTest.java @@ -1,19 +1,19 @@ /** * Copyright (c) 2010, Sebastian Sdorra * All rights reserved. - * + *

* Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + *

* 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. + * this list of conditions and the following disclaimer. * 2. 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. + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. * 3. Neither the name of SCM-Manager; nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * + * 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 @@ -24,50 +24,45 @@ * 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. - * + *

* http://bitbucket.org/sdorra/scm-manager - * */ - package sonia.scm.repository; //~--- non-JDK imports -------------------------------------------------------- -import sonia.scm.io.DefaultFileSystem; - -import static org.junit.Assert.*; - -//~--- JDK imports ------------------------------------------------------------ - -import java.io.File; -import sonia.scm.store.ConfigurationStoreFactory; +import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; +import sonia.scm.io.DefaultFileSystem; import sonia.scm.schedule.Scheduler; +import sonia.scm.store.ConfigurationStoreFactory; + +import java.io.File; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +//~--- JDK imports ------------------------------------------------------------ /** * * @author Sebastian Sdorra */ @RunWith(MockitoJUnitRunner.class) -public class GitRepositoryHandlerTest extends SimpleRepositoryHandlerTestBase -{ +public class GitRepositoryHandlerTest extends SimpleRepositoryHandlerTestBase { @Mock private Scheduler scheduler; - - /** - * Method description - * - * - * @param directory - */ + + @Mock + private ConfigurationStoreFactory factory; + @Override - protected void checkDirectory(File directory) - { + protected void checkDirectory(File directory) { File head = new File(directory, "HEAD"); assertTrue(head.exists()); @@ -84,21 +79,12 @@ public class GitRepositoryHandlerTest extends SimpleRepositoryHandlerTestBase assertTrue(refs.isDirectory()); } - /** - * Method description - * - * - * @param factory - * @param directory - * - * @return - */ + @Override protected RepositoryHandler createRepositoryHandler(ConfigurationStoreFactory factory, - File directory) - { + File directory) { GitRepositoryHandler repositoryHandler = new GitRepositoryHandler(factory, - new DefaultFileSystem(), scheduler); + new DefaultFileSystem(), scheduler); repositoryHandler.init(contextProvider); @@ -110,4 +96,19 @@ public class GitRepositoryHandlerTest extends SimpleRepositoryHandlerTestBase return repositoryHandler; } + + @Test + public void getDirectory() { + GitRepositoryHandler repositoryHandler = new GitRepositoryHandler(factory, + new DefaultFileSystem(), scheduler); + + GitConfig gitConfig = new GitConfig(); + gitConfig.setRepositoryDirectory(new File("/path")); + repositoryHandler.setConfig(gitConfig); + + Repository repository = new Repository("id", "git", "Space", "Name"); + + File path = repositoryHandler.getDirectory(repository); + assertEquals("/path/id", path.getAbsolutePath()); + } } diff --git a/scm-plugins/scm-git-plugin/src/test/java/sonia/scm/repository/GitRepositoryPathMatcherTest.java b/scm-plugins/scm-git-plugin/src/test/java/sonia/scm/repository/GitRepositoryPathMatcherTest.java index 7adc4a6913..598d3b6400 100644 --- a/scm-plugins/scm-git-plugin/src/test/java/sonia/scm/repository/GitRepositoryPathMatcherTest.java +++ b/scm-plugins/scm-git-plugin/src/test/java/sonia/scm/repository/GitRepositoryPathMatcherTest.java @@ -31,7 +31,9 @@ package sonia.scm.repository; import org.junit.Test; -import static org.junit.Assert.*; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; /** * Unit tests for {@link GitRepositoryPathMatcher}. @@ -45,18 +47,18 @@ public class GitRepositoryPathMatcherTest { @Test public void testIsPathMatching() { - assertFalse(pathMatcher.isPathMatching(repository("my-repo"), "my-repoo")); - assertFalse(pathMatcher.isPathMatching(repository("my"), "my-repo")); - assertFalse(pathMatcher.isPathMatching(repository("my"), "my-repo/with/path")); + assertFalse(pathMatcher.isPathMatching(repository("space", "my-repo"), "my-repoo")); + assertFalse(pathMatcher.isPathMatching(repository("space", "my"), "my-repo")); + assertFalse(pathMatcher.isPathMatching(repository("space", "my"), "my-repo/with/path")); - assertTrue(pathMatcher.isPathMatching(repository("my-repo"), "my-repo")); - assertTrue(pathMatcher.isPathMatching(repository("my-repo"), "my-repo.git")); - assertTrue(pathMatcher.isPathMatching(repository("my-repo"), "my-repo/with/path")); - assertTrue(pathMatcher.isPathMatching(repository("my-repo"), "my-repo.git/with/path")); + assertTrue(pathMatcher.isPathMatching(repository("space", "my-repo"), "my-repo")); + assertTrue(pathMatcher.isPathMatching(repository("space", "my-repo"), "my-repo.git")); + assertTrue(pathMatcher.isPathMatching(repository("space", "my-repo"), "my-repo/with/path")); + assertTrue(pathMatcher.isPathMatching(repository("space", "my-repo"), "my-repo.git/with/path")); } - private Repository repository(String name) { - return new Repository(name, GitRepositoryHandler.TYPE_NAME, name); + private Repository repository(String namespace, String name) { + return new Repository(name, GitRepositoryHandler.TYPE_NAME, namespace, name); } } diff --git a/scm-plugins/scm-git-plugin/src/test/java/sonia/scm/repository/spi/AbstractRemoteCommandTestBase.java b/scm-plugins/scm-git-plugin/src/test/java/sonia/scm/repository/spi/AbstractRemoteCommandTestBase.java index a76d110561..e2a401bf7d 100644 --- a/scm-plugins/scm-git-plugin/src/test/java/sonia/scm/repository/spi/AbstractRemoteCommandTestBase.java +++ b/scm-plugins/scm-git-plugin/src/test/java/sonia/scm/repository/spi/AbstractRemoteCommandTestBase.java @@ -38,34 +38,31 @@ package sonia.scm.repository.spi; import com.google.common.base.Charsets; import com.google.common.io.Files; import com.google.inject.Provider; - import org.eclipse.jgit.api.CommitCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.transport.ScmTransportProtocol; import org.eclipse.jgit.transport.Transport; - import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.rules.TemporaryFolder; - import sonia.scm.repository.Changeset; import sonia.scm.repository.GitRepositoryHandler; import sonia.scm.repository.Repository; import sonia.scm.user.User; import sonia.scm.user.UserTestData; -import static org.junit.Assert.*; - -import static org.mockito.Mockito.*; - -//~--- JDK imports ------------------------------------------------------------ - import java.io.File; import java.io.IOException; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +//~--- JDK imports ------------------------------------------------------------ + /** * * @author Sebastian Sdorra @@ -88,8 +85,8 @@ public class AbstractRemoteCommandTestBase outgoingDirectory = tempFolder.newFile("outgoing"); outgoingDirectory.delete(); - incomgingRepository = new Repository("1", "git", "incoming"); - outgoingRepository = new Repository("2", "git", "outgoing"); + incomgingRepository = new Repository("1", "git", "space", "incoming"); + outgoingRepository = new Repository("2", "git", "space", "outgoing"); incoming = Git.init().setDirectory(incomingDirectory).setBare(false).call(); outgoing = Git.init().setDirectory(outgoingDirectory).setBare(false).call(); diff --git a/scm-plugins/scm-git-plugin/src/test/java/sonia/scm/web/lfs/LfsBlobStoreFactoryTest.java b/scm-plugins/scm-git-plugin/src/test/java/sonia/scm/web/lfs/LfsBlobStoreFactoryTest.java index 2eb8968405..fe48e403c5 100644 --- a/scm-plugins/scm-git-plugin/src/test/java/sonia/scm/web/lfs/LfsBlobStoreFactoryTest.java +++ b/scm-plugins/scm-git-plugin/src/test/java/sonia/scm/web/lfs/LfsBlobStoreFactoryTest.java @@ -35,14 +35,15 @@ package sonia.scm.web.lfs; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; -import static org.mockito.Matchers.matches; import org.mockito.Mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; import org.mockito.runners.MockitoJUnitRunner; import sonia.scm.repository.Repository; import sonia.scm.store.BlobStoreFactory; +import static org.mockito.Matchers.matches; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + /** * Unit tests for {@link LfsBlobStoreFactory}. * @@ -59,7 +60,7 @@ public class LfsBlobStoreFactoryTest { @Test public void getBlobStore() throws Exception { - lfsBlobStoreFactory.getLfsBlobStore(new Repository("the-id", "GIT", "the-name")); + lfsBlobStoreFactory.getLfsBlobStore(new Repository("the-id", "GIT", "space", "the-name")); // just make sure the right parameter is passed, as properly validating the return value is nearly impossible with // the return value (and should not be part of this test) diff --git a/scm-plugins/scm-git-plugin/src/test/java/sonia/scm/web/lfs/servlet/LfsServletFactoryTest.java b/scm-plugins/scm-git-plugin/src/test/java/sonia/scm/web/lfs/servlet/LfsServletFactoryTest.java index c670032089..74674cc9db 100644 --- a/scm-plugins/scm-git-plugin/src/test/java/sonia/scm/web/lfs/servlet/LfsServletFactoryTest.java +++ b/scm-plugins/scm-git-plugin/src/test/java/sonia/scm/web/lfs/servlet/LfsServletFactoryTest.java @@ -7,8 +7,9 @@ import javax.servlet.http.HttpServletRequest; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; /** * Created by omilke on 18.05.2017. @@ -18,14 +19,15 @@ public class LfsServletFactoryTest { @Test public void buildBaseUri() throws Exception { + String repositoryNamespace = "space"; String repositoryName = "git-lfs-demo"; - String result = LfsServletFactory.buildBaseUri(new Repository("", "GIT", repositoryName), RequestWithUri(repositoryName, true)); + String result = LfsServletFactory.buildBaseUri(new Repository("", "GIT", repositoryNamespace, repositoryName), RequestWithUri(repositoryName, true)); assertThat(result, is(equalTo("http://localhost:8081/scm/git/git-lfs-demo.git/info/lfs/objects/"))); //result will be with dot-gix suffix, ide - result = LfsServletFactory.buildBaseUri(new Repository("", "GIT", repositoryName), RequestWithUri(repositoryName, false)); + result = LfsServletFactory.buildBaseUri(new Repository("", "GIT", repositoryNamespace, repositoryName), RequestWithUri(repositoryName, false)); assertThat(result, is(equalTo("http://localhost:8081/scm/git/git-lfs-demo.git/info/lfs/objects/"))); } diff --git a/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/repository/spi/HgHookChangesetProvider.java b/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/repository/spi/HgHookChangesetProvider.java index 17c0816686..59ad0c3345 100644 --- a/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/repository/spi/HgHookChangesetProvider.java +++ b/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/repository/spi/HgHookChangesetProvider.java @@ -34,20 +34,18 @@ package sonia.scm.repository.spi; //~--- non-JDK imports -------------------------------------------------------- import com.aragost.javahg.Repository; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import sonia.scm.repository.HgHookManager; import sonia.scm.repository.HgRepositoryHandler; import sonia.scm.repository.RepositoryHookType; import sonia.scm.repository.spi.javahg.HgLogChangesetCommand; import sonia.scm.web.HgUtil; -//~--- JDK imports ------------------------------------------------------------ - import java.io.File; +//~--- JDK imports ------------------------------------------------------------ + /** * * @author Sebastian Sdorra @@ -63,22 +61,12 @@ public class HgHookChangesetProvider implements HookChangesetProvider //~--- constructors --------------------------------------------------------- - /** - * Constructs ... - * - * - * @param handler - * @param repositoryName - * @param hookManager - * @param startRev - * @param type - */ public HgHookChangesetProvider(HgRepositoryHandler handler, - String repositoryName, HgHookManager hookManager, String startRev, + String id, HgHookManager hookManager, String startRev, RepositoryHookType type) { this.handler = handler; - this.repositoryName = repositoryName; + this.id = id; this.hookManager = hookManager; this.startRev = startRev; this.type = type; @@ -136,7 +124,7 @@ public class HgHookChangesetProvider implements HookChangesetProvider private Repository open() { File directory = handler.getConfig().getRepositoryDirectory(); - File repositoryDirectory = new File(directory, repositoryName); + File repositoryDirectory = new File(directory, id); // use HG_PENDING only for pre receive hooks boolean pending = type == RepositoryHookType.PRE_RECEIVE; @@ -155,7 +143,7 @@ public class HgHookChangesetProvider implements HookChangesetProvider private HgHookManager hookManager; /** Field description */ - private String repositoryName; + private String id; /** Field description */ private HookChangesetResponse response; diff --git a/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/repository/spi/HgHookContextProvider.java b/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/repository/spi/HgHookContextProvider.java index dede59796c..5b354ecec4 100644 --- a/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/repository/spi/HgHookContextProvider.java +++ b/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/repository/spi/HgHookContextProvider.java @@ -38,16 +38,16 @@ import sonia.scm.repository.HgRepositoryHandler; import sonia.scm.repository.RepositoryHookType; import sonia.scm.repository.api.HgHookBranchProvider; import sonia.scm.repository.api.HgHookMessageProvider; +import sonia.scm.repository.api.HgHookTagProvider; import sonia.scm.repository.api.HookBranchProvider; import sonia.scm.repository.api.HookFeature; import sonia.scm.repository.api.HookMessageProvider; - -//~--- JDK imports ------------------------------------------------------------ +import sonia.scm.repository.api.HookTagProvider; import java.util.EnumSet; import java.util.Set; -import sonia.scm.repository.api.HgHookTagProvider; -import sonia.scm.repository.api.HookTagProvider; + +//~--- JDK imports ------------------------------------------------------------ /** * Mercurial implementation of {@link HookContextProvider}. @@ -67,17 +67,16 @@ public class HgHookContextProvider extends HookContextProvider * Constructs a new instance. * * @param handler mercurial repository handler - * @param repositoryName name of changed repository + * @param namespaceAndName namespace and name of changed repository * @param hookManager mercurial hook manager * @param startRev start revision * @param type type of hook */ public HgHookContextProvider(HgRepositoryHandler handler, - String repositoryName, HgHookManager hookManager, String startRev, + String id, HgHookManager hookManager, String startRev, RepositoryHookType type) { - this.hookChangesetProvider = new HgHookChangesetProvider(handler, - repositoryName, hookManager, startRev, type); + this.hookChangesetProvider = new HgHookChangesetProvider(handler, id, hookManager, startRev, type); } //~--- get methods ---------------------------------------------------------- diff --git a/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/repository/spi/HgRepositoryServiceResolver.java b/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/repository/spi/HgRepositoryServiceResolver.java index 9b87991ae6..d322cb8e9f 100644 --- a/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/repository/spi/HgRepositoryServiceResolver.java +++ b/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/repository/spi/HgRepositoryServiceResolver.java @@ -82,7 +82,7 @@ public class HgRepositoryServiceResolver implements RepositoryServiceResolver * @return */ @Override - public HgRepositoryServiceProvider reslove(Repository repository) + public HgRepositoryServiceProvider resolve(Repository repository) { HgRepositoryServiceProvider provider = null; diff --git a/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/web/HgCGIServlet.java b/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/web/HgCGIServlet.java index e00304c977..6cb4d523f0 100644 --- a/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/web/HgCGIServlet.java +++ b/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/web/HgCGIServlet.java @@ -39,10 +39,8 @@ import com.google.common.base.Stopwatch; import com.google.common.base.Strings; import com.google.inject.Inject; import com.google.inject.Singleton; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import sonia.scm.SCMContext; import sonia.scm.config.ScmConfiguration; import sonia.scm.repository.HgConfig; @@ -60,19 +58,17 @@ import sonia.scm.web.cgi.CGIExecutor; import sonia.scm.web.cgi.CGIExecutorFactory; import sonia.scm.web.cgi.EnvList; -//~--- JDK imports ------------------------------------------------------------ - -import java.io.File; -import java.io.IOException; -import java.util.Base64; - -import java.util.Enumeration; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; +import java.io.File; +import java.io.IOException; +import java.util.Base64; +import java.util.Enumeration; + +//~--- JDK imports ------------------------------------------------------------ /** * @@ -305,7 +301,7 @@ public class HgCGIServlet extends HttpServlet executor.setExceptionHandler(exceptionHandler); executor.setStatusCodeHandler(exceptionHandler); executor.setContentLengthWorkaround(true); - executor.getEnvironment().set(ENV_REPOSITORY_NAME, name); + executor.getEnvironment().set(ENV_REPOSITORY_NAME, repository.getNamespace() + "/" + repository.getName()); executor.getEnvironment().set(ENV_REPOSITORY_PATH, directory.getAbsolutePath()); diff --git a/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/web/HgHookCallbackServlet.java b/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/web/HgHookCallbackServlet.java index abbf09380a..2734996686 100644 --- a/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/web/HgHookCallbackServlet.java +++ b/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/web/HgHookCallbackServlet.java @@ -40,13 +40,10 @@ import com.google.common.io.Closeables; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; - import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import sonia.scm.repository.HgContext; import sonia.scm.repository.HgHookManager; import sonia.scm.repository.HgRepositoryHandler; @@ -62,19 +59,17 @@ import sonia.scm.security.Tokens; import sonia.scm.util.HttpUtil; import sonia.scm.util.Util; -//~--- JDK imports ------------------------------------------------------------ - -import java.io.IOException; -import java.io.PrintWriter; - -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +//~--- JDK imports ------------------------------------------------------------ /** * @@ -167,27 +162,24 @@ public class HgHookCallbackServlet extends HttpServlet } } - /** - * Method description - * - * - * @param request - * @param response - * - * @throws IOException - * @throws ServletException - */ @Override - protected void doPost(HttpServletRequest request, - HttpServletResponse response) - throws ServletException, IOException + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + try { + handlePostRequest(request, response); + } catch (IOException ex) { + logger.warn("error in hook callback execution, sending internal server error", ex); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } + + private void handlePostRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { String strippedURI = HttpUtil.getStrippedURI(request); Matcher m = REGEX_URL.matcher(strippedURI); if (m.matches()) { - String repositoryId = getRepositoryName(request); + String id = getRepositoryId(request); String type = m.group(1); String challenge = request.getParameter(PARAM_CHALLENGE); @@ -204,7 +196,7 @@ public class HgHookCallbackServlet extends HttpServlet authenticate(request, credentials); } - hookCallback(response, repositoryId, type, challenge, node); + hookCallback(response, id, type, challenge, node); } else if (logger.isDebugEnabled()) { @@ -227,13 +219,6 @@ public class HgHookCallbackServlet extends HttpServlet } } - /** - * Method description - * - * - * @param request - * @param credentials - */ private void authenticate(HttpServletRequest request, String credentials) { try @@ -270,18 +255,7 @@ public class HgHookCallbackServlet extends HttpServlet } } - /** - * Method description - * - * - * @param response - * @param repositoryName - * @param node - * @param type - * - * @throws IOException - */ - private void fireHook(HttpServletResponse response, String repositoryName, + private void fireHook(HttpServletResponse response, String id, String node, RepositoryHookType type) throws IOException { @@ -294,11 +268,10 @@ public class HgHookCallbackServlet extends HttpServlet contextProvider.get().setPending(true); } - context = new HgHookContextProvider(handler, repositoryName, hookManager, + context = new HgHookContextProvider(handler, id, hookManager, node, type); - hookEventFacade.handle(HgRepositoryHandler.TYPE_NAME, - repositoryName).fireHookEvent(type, context); + hookEventFacade.handle(id).fireHookEvent(type, context); printMessages(response, context); } @@ -306,7 +279,7 @@ public class HgHookCallbackServlet extends HttpServlet { if (logger.isErrorEnabled()) { - logger.error("could not find repository {}", repositoryName); + logger.error("could not find repository with id {}", id); if (logger.isTraceEnabled()) { @@ -322,22 +295,7 @@ public class HgHookCallbackServlet extends HttpServlet } } - /** - * Method description - * - * - * @param response - * @param repositoryName - * @param typeName - * @param challenge - * @param node - * - * @throws IOException - */ - private void hookCallback(HttpServletResponse response, - String repositoryName, String typeName, String challenge, String node) - throws IOException - { + private void hookCallback(HttpServletResponse response, String id, String typeName, String challenge, String node) throws IOException { if (hookManager.isAcceptAble(challenge)) { RepositoryHookType type = null; @@ -353,7 +311,7 @@ public class HgHookCallbackServlet extends HttpServlet if (type != null) { - fireHook(response, repositoryName, node, type); + fireHook(response, id, node, type); } else { @@ -403,12 +361,12 @@ public class HgHookCallbackServlet extends HttpServlet * Method description * * - * @param resonse + * @param response * @param context * * @throws IOException */ - private void printMessages(HttpServletResponse resonse, + private void printMessages(HttpServletResponse response, HgHookContextProvider context) throws IOException { @@ -420,7 +378,7 @@ public class HgHookCallbackServlet extends HttpServlet try { - writer = resonse.getWriter(); + writer = response.getWriter(); printMessages(writer, msgs); } @@ -506,9 +464,9 @@ public class HgHookCallbackServlet extends HttpServlet * * @return */ - private String getRepositoryName(HttpServletRequest request) + private String getRepositoryId(HttpServletRequest request) { - String name = null; + String id = null; String path = request.getParameter(PARAM_REPOSITORYPATH); if (Util.isNotEmpty(path)) @@ -520,11 +478,11 @@ public class HgHookCallbackServlet extends HttpServlet */ try { - name = RepositoryUtil.getRepositoryName(handler, path); + id = RepositoryUtil.getRepositoryId(handler, path); } catch (IOException ex) { - logger.error("could not find name of repository", ex); + logger.error("could not find namespace and name of repository", ex); } } else if (logger.isWarnEnabled()) @@ -532,7 +490,7 @@ public class HgHookCallbackServlet extends HttpServlet logger.warn("no repository path parameter found"); } - return name; + return id; } //~--- fields --------------------------------------------------------------- diff --git a/scm-plugins/scm-hg-plugin/src/test/java/sonia/scm/repository/HgRepositoryHandlerTest.java b/scm-plugins/scm-hg-plugin/src/test/java/sonia/scm/repository/HgRepositoryHandlerTest.java index c14e5f1b61..bd14a63b56 100644 --- a/scm-plugins/scm-hg-plugin/src/test/java/sonia/scm/repository/HgRepositoryHandlerTest.java +++ b/scm-plugins/scm-hg-plugin/src/test/java/sonia/scm/repository/HgRepositoryHandlerTest.java @@ -1,19 +1,19 @@ /** * Copyright (c) 2010, Sebastian Sdorra * All rights reserved. - * + *

* Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + *

* 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. + * this list of conditions and the following disclaimer. * 2. 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. + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. * 3. Neither the name of SCM-Manager; nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * + * 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 @@ -24,43 +24,45 @@ * 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. - * + *

* http://bitbucket.org/sdorra/scm-manager - * */ - package sonia.scm.repository; //~--- non-JDK imports -------------------------------------------------------- +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; import sonia.scm.io.DefaultFileSystem; - -import static org.junit.Assert.*; - -//~--- JDK imports ------------------------------------------------------------ +import sonia.scm.store.ConfigurationStoreFactory; import java.io.File; -import sonia.scm.store.ConfigurationStoreFactory; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +//~--- JDK imports ------------------------------------------------------------ /** * * @author Sebastian Sdorra */ -public class HgRepositoryHandlerTest extends SimpleRepositoryHandlerTestBase -{ +@RunWith(MockitoJUnitRunner.class) +public class HgRepositoryHandlerTest extends SimpleRepositoryHandlerTestBase { + + @Mock + private ConfigurationStoreFactory factory; + + @Mock + private com.google.inject.Provider provider; - /** - * Method description - * - * - * @param directory - */ @Override - protected void checkDirectory(File directory) - { + protected void checkDirectory(File directory) { File hgDirectory = new File(directory, ".hg"); assertTrue(hgDirectory.exists()); @@ -73,22 +75,12 @@ public class HgRepositoryHandlerTest extends SimpleRepositoryHandlerTestBase assertTrue(hgrc.length() > 0); } - /** - * Method description - * - * - * @param factory - * @param directory - * - * @return - */ @Override protected RepositoryHandler createRepositoryHandler(ConfigurationStoreFactory factory, - File directory) - { + File directory) { HgRepositoryHandler handler = new HgRepositoryHandler(factory, - new DefaultFileSystem(), - new HgContextProvider()); + new DefaultFileSystem(), + new HgContextProvider()); handler.init(contextProvider); handler.getConfig().setRepositoryDirectory(directory); @@ -97,5 +89,21 @@ public class HgRepositoryHandlerTest extends SimpleRepositoryHandlerTestBase return handler; } + + @Test + public void getDirectory() { + HgRepositoryHandler repositoryHandler = new HgRepositoryHandler(factory, + new DefaultFileSystem(), provider); + + HgConfig hgConfig = new HgConfig(); + hgConfig.setRepositoryDirectory(new File("/path")); + hgConfig.setHgBinary("hg"); + hgConfig.setPythonBinary("python"); + repositoryHandler.setConfig(hgConfig); + + Repository repository = new Repository("id", "git", "Space", "Name"); + + File path = repositoryHandler.getDirectory(repository); + assertEquals("/path/id", path.getAbsolutePath()); + } } -//~--- non-JDK imports -------------------------------------------------------- diff --git a/scm-plugins/scm-hg-plugin/src/test/java/sonia/scm/repository/spi/IncomingOutgoingTestBase.java b/scm-plugins/scm-hg-plugin/src/test/java/sonia/scm/repository/spi/IncomingOutgoingTestBase.java index c45d0af2da..8dca8fdfe6 100644 --- a/scm-plugins/scm-hg-plugin/src/test/java/sonia/scm/repository/spi/IncomingOutgoingTestBase.java +++ b/scm-plugins/scm-hg-plugin/src/test/java/sonia/scm/repository/spi/IncomingOutgoingTestBase.java @@ -41,14 +41,11 @@ import com.aragost.javahg.Repository; import com.aragost.javahg.RepositoryConfiguration; import com.aragost.javahg.commands.AddCommand; import com.aragost.javahg.commands.CommitCommand; - import com.google.common.base.Charsets; import com.google.common.io.Files; - import org.junit.Before; import org.junit.Rule; import org.junit.rules.TemporaryFolder; - import sonia.scm.AbstractTestBase; import sonia.scm.repository.HgConfig; import sonia.scm.repository.HgContext; @@ -58,15 +55,15 @@ import sonia.scm.user.User; import sonia.scm.user.UserTestData; import sonia.scm.util.MockUtil; -import static org.junit.Assert.*; - -import static org.mockito.Mockito.*; - -//~--- JDK imports ------------------------------------------------------------ - import java.io.File; import java.io.IOException; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +//~--- JDK imports ------------------------------------------------------------ + /** * * @author Sebastian Sdorra @@ -90,10 +87,8 @@ public abstract class IncomingOutgoingTestBase extends AbstractTestBase incomingDirectory = tempFolder.newFolder("incoming"); outgoingDirectory = tempFolder.newFolder("outgoing"); - incomingRepository = new sonia.scm.repository.Repository("1", "hg", - "incoming"); - outgoingRepository = new sonia.scm.repository.Repository("2", "hg", - "outgoing"); + incomingRepository = new sonia.scm.repository.Repository("1", "hg", "space", "incoming"); + outgoingRepository = new sonia.scm.repository.Repository("2", "hg", "space", "outgoing"); incoming = Repository.create(createConfig(temp), incomingDirectory); outgoing = Repository.create(createConfig(temp), outgoingDirectory); diff --git a/scm-plugins/scm-hg-plugin/src/test/java/sonia/scm/web/HgHookCallbackServletTest.java b/scm-plugins/scm-hg-plugin/src/test/java/sonia/scm/web/HgHookCallbackServletTest.java new file mode 100644 index 0000000000..a586962bb8 --- /dev/null +++ b/scm-plugins/scm-hg-plugin/src/test/java/sonia/scm/web/HgHookCallbackServletTest.java @@ -0,0 +1,41 @@ +package sonia.scm.web; + +import org.junit.Test; +import sonia.scm.repository.HgConfig; +import sonia.scm.repository.HgRepositoryHandler; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.io.IOException; + +import static org.mockito.Matchers.anyInt; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static sonia.scm.web.HgHookCallbackServlet.PARAM_REPOSITORYPATH; + +public class HgHookCallbackServletTest { + + @Test + public void shouldExtractCorrectRepositoryId() throws ServletException, IOException { + HgRepositoryHandler handler = mock(HgRepositoryHandler.class); + HgHookCallbackServlet servlet = new HgHookCallbackServlet(null, handler, null, null); + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + HgConfig config = mock(HgConfig.class); + + when(request.getContextPath()).thenReturn("http://example.com/scm"); + when(request.getRequestURI()).thenReturn("http://example.com/scm/hook/hg/pretxnchangegroup"); + when(request.getParameter(PARAM_REPOSITORYPATH)).thenReturn("/tmp/hg/12345"); + + when(handler.getConfig()).thenReturn(config); + when(config.getRepositoryDirectory()).thenReturn(new File("/tmp/hg")); + + servlet.doPost(request, response); + + verify(response, never()).sendError(anyInt()); + } +} diff --git a/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/repository/SvnRepositoryHook.java b/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/repository/SvnRepositoryHook.java index 1de3b2aecb..00958174a4 100644 --- a/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/repository/SvnRepositoryHook.java +++ b/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/repository/SvnRepositoryHook.java @@ -37,7 +37,6 @@ package sonia.scm.repository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; @@ -45,21 +44,19 @@ import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.internal.io.fs.FSHook; import org.tmatesoft.svn.core.internal.io.fs.FSHookEvent; import org.tmatesoft.svn.core.internal.io.fs.FSHooks; - import sonia.scm.repository.spi.AbstractSvnHookChangesetProvider; import sonia.scm.repository.spi.HookEventFacade; import sonia.scm.repository.spi.SvnHookContextProvider; import sonia.scm.repository.spi.SvnPostReceiveHookChangesetProvier; import sonia.scm.repository.spi.SvnPreReceiveHookChangesetProvier; import sonia.scm.util.AssertUtil; -import sonia.scm.util.IOUtil; import sonia.scm.util.Util; -//~--- JDK imports ------------------------------------------------------------ - import java.io.File; import java.io.IOException; +//~--- JDK imports ------------------------------------------------------------ + /** * * @author Sebastian Sdorra @@ -166,12 +163,10 @@ public class SvnRepositoryHook implements FSHook { try { - String name = getRepositoryName(directory); - - name = IOUtil.trimSeperatorChars(name); + String id = getRepositoryId(directory); //J- - hookEventFacade.handle(SvnRepositoryHandler.TYPE_NAME, name) + hookEventFacade.handle(id) .fireHookEvent( changesetProvider.getType(), new SvnHookContextProvider(changesetProvider) @@ -202,11 +197,11 @@ public class SvnRepositoryHook implements FSHook * * @throws IOException */ - private String getRepositoryName(File directory) throws IOException + private String getRepositoryId(File directory) throws IOException { AssertUtil.assertIsNotNull(directory); - return RepositoryUtil.getRepositoryName(handler, directory); + return RepositoryUtil.getRepositoryId(handler, directory); } //~--- fields --------------------------------------------------------------- diff --git a/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/repository/spi/SvnRepositoryServiceResolver.java b/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/repository/spi/SvnRepositoryServiceResolver.java index c46c6722be..d56398083e 100644 --- a/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/repository/spi/SvnRepositoryServiceResolver.java +++ b/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/repository/spi/SvnRepositoryServiceResolver.java @@ -76,7 +76,7 @@ public class SvnRepositoryServiceResolver implements RepositoryServiceResolver * @return */ @Override - public SvnRepositoryServiceProvider reslove(Repository repository) + public SvnRepositoryServiceProvider resolve(Repository repository) { SvnRepositoryServiceProvider provider = null; diff --git a/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/web/SvnCollectionRenderer.java b/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/web/SvnCollectionRenderer.java index 0bfb6b4575..2808c2b384 100644 --- a/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/web/SvnCollectionRenderer.java +++ b/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/web/SvnCollectionRenderer.java @@ -57,9 +57,6 @@ import sonia.scm.repository.RepositoryProvider; import sonia.scm.template.Template; import sonia.scm.template.TemplateEngine; import sonia.scm.template.TemplateEngineFactory; -import sonia.scm.url.RepositoryUrlProvider; -import sonia.scm.url.UrlProvider; -import sonia.scm.url.UrlProviderFactory; import sonia.scm.util.HttpUtil; //~--- JDK imports ------------------------------------------------------------ @@ -182,24 +179,15 @@ public class SvnCollectionRenderer implements CollectionRenderer entries.add(new DirectoryEntry(resource, entry)); } - UrlProvider urlProvider = createUrlProvider(); - //J- return new RepositoryWrapper( - urlProvider.getRepositoryUrlProvider(), repositoryProvider.get(), resource, new DirectoryOrdering().immutableSortedCopy(entries.build()) ); //J+ } - - private UrlProvider createUrlProvider() { - String baseUrl = getBaseUrl(); - logger.trace("render subversion collection with base url: {}", baseUrl); - return UrlProviderFactory.createUrlProvider(baseUrl, UrlProviderFactory.TYPE_WUI); - } - + private String getBaseUrl() { return HttpUtil.getCompleteUrl(requestProvider.get()); } @@ -395,15 +383,12 @@ public class SvnCollectionRenderer implements CollectionRenderer * * * - * @param repositoryUrlProvider * @param repository * @param resource * @param entries */ - public RepositoryWrapper(RepositoryUrlProvider repositoryUrlProvider, - Repository repository, DAVResource resource, List entries) + public RepositoryWrapper(Repository repository, DAVResource resource, List entries) { - this.repositoryUrlProvider = repositoryUrlProvider; this.repository = repository; this.resource = resource; this.entries = entries; @@ -411,17 +396,6 @@ public class SvnCollectionRenderer implements CollectionRenderer //~--- get methods -------------------------------------------------------- - /** - * Method description - * - * - * @return - */ - public String getCommitViewLink() - { - return repositoryUrlProvider.getChangesetUrl(repository.getId(), 0, 20); - } - /** * Method description * @@ -455,18 +429,6 @@ public class SvnCollectionRenderer implements CollectionRenderer return repository; } - /** - * Method description - * - * - * @return - */ - public String getSourceViewLink() - { - return repositoryUrlProvider.getBrowseUrl(repository.getId(), - resource.getResourceURI().getPath(), null); - } - //~--- fields ------------------------------------------------------------- /** Field description */ @@ -475,9 +437,6 @@ public class SvnCollectionRenderer implements CollectionRenderer /** Field description */ private final Repository repository; - /** Field description */ - private final RepositoryUrlProvider repositoryUrlProvider; - /** Field description */ private final DAVResource resource; } diff --git a/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/web/SvnDAVServlet.java b/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/web/SvnDAVServlet.java index db22857595..c811179255 100644 --- a/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/web/SvnDAVServlet.java +++ b/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/web/SvnDAVServlet.java @@ -37,13 +37,10 @@ package sonia.scm.web; import com.google.inject.Inject; import com.google.inject.Singleton; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import org.tmatesoft.svn.core.internal.server.dav.DAVConfig; import org.tmatesoft.svn.core.internal.server.dav.DAVServlet; - import sonia.scm.repository.Repository; import sonia.scm.repository.RepositoryProvider; import sonia.scm.repository.RepositoryRequestListenerUtil; @@ -51,14 +48,13 @@ import sonia.scm.repository.SvnRepositoryHandler; import sonia.scm.util.AssertUtil; import sonia.scm.util.HttpUtil; -//~--- JDK imports ------------------------------------------------------------ - -import java.io.IOException; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +//~--- JDK imports ------------------------------------------------------------ /** * @@ -224,7 +220,7 @@ public class SvnDAVServlet extends DAVServlet pathInfo = pathInfo.substring(1); } - pathInfo = pathInfo.substring(repository.getName().length()); + pathInfo = pathInfo.substring(repository.getNamespace().length() + 1 + repository.getName().length()); } return pathInfo; @@ -249,7 +245,7 @@ public class SvnDAVServlet extends DAVServlet servletPath = servletPath.concat(HttpUtil.SEPARATOR_PATH); } - servletPath = servletPath.concat(repository.getName()); + servletPath = servletPath + repository.getNamespace() + "/" + repository.getName(); } return servletPath; diff --git a/scm-plugins/scm-svn-plugin/src/test/java/sonia/scm/repository/SvnRepositoryHandlerTest.java b/scm-plugins/scm-svn-plugin/src/test/java/sonia/scm/repository/SvnRepositoryHandlerTest.java index af80e27bcf..f2c53e413c 100644 --- a/scm-plugins/scm-svn-plugin/src/test/java/sonia/scm/repository/SvnRepositoryHandlerTest.java +++ b/scm-plugins/scm-svn-plugin/src/test/java/sonia/scm/repository/SvnRepositoryHandlerTest.java @@ -1,19 +1,19 @@ /** * Copyright (c) 2010, Sebastian Sdorra * All rights reserved. - * + *

* Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + *

* 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. + * this list of conditions and the following disclaimer. * 2. 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. + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. * 3. Neither the name of SCM-Manager; nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * + * 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 @@ -24,42 +24,56 @@ * 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. - * + *

* http://bitbucket.org/sdorra/scm-manager - * */ - package sonia.scm.repository; -//~--- non-JDK imports -------------------------------------------------------- +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; import sonia.scm.io.DefaultFileSystem; - -import static org.junit.Assert.*; - -//~--- JDK imports ------------------------------------------------------------ +import sonia.scm.repository.api.HookContextFactory; +import sonia.scm.repository.spi.HookEventFacade; +import sonia.scm.store.ConfigurationStore; +import sonia.scm.store.ConfigurationStoreFactory; import java.io.File; -import sonia.scm.store.ConfigurationStoreFactory; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +//~--- JDK imports ------------------------------------------------------------ /** * * @author Sebastian Sdorra */ -public class SvnRepositoryHandlerTest extends SimpleRepositoryHandlerTestBase -{ +@RunWith(MockitoJUnitRunner.class) +public class SvnRepositoryHandlerTest extends SimpleRepositoryHandlerTestBase { + + @Mock + private ConfigurationStoreFactory factory; + + @Mock + private ConfigurationStore store; + + @Mock + private com.google.inject.Provider repositoryManagerProvider; + + private HookContextFactory hookContextFactory = new HookContextFactory(mock(PreProcessorUtil.class)); + + private HookEventFacade facade = new HookEventFacade(repositoryManagerProvider, hookContextFactory); - /** - * Method description - * - * - * @param directory - */ @Override - protected void checkDirectory(File directory) - { + protected void checkDirectory(File directory) { File format = new File(directory, "format"); assertTrue(format.exists()); @@ -71,21 +85,11 @@ public class SvnRepositoryHandlerTest extends SimpleRepositoryHandlerTestBase assertTrue(db.isDirectory()); } - /** - * Method description - * - * - * @param factory - * @param directory - * - * @return - */ @Override protected RepositoryHandler createRepositoryHandler(ConfigurationStoreFactory factory, - File directory) - { + File directory) { SvnRepositoryHandler handler = new SvnRepositoryHandler(factory, - new DefaultFileSystem(), null); + new DefaultFileSystem(), null); handler.init(contextProvider); @@ -98,4 +102,20 @@ public class SvnRepositoryHandlerTest extends SimpleRepositoryHandlerTestBase return handler; } + + @Test + public void getDirectory() { + when(factory.getStore(any(), any())).thenReturn(store); + SvnRepositoryHandler repositoryHandler = new SvnRepositoryHandler(factory, + new DefaultFileSystem(), facade); + + SvnConfig svnConfig = new SvnConfig(); + svnConfig.setRepositoryDirectory(new File("/path")); + repositoryHandler.setConfig(svnConfig); + + Repository repository = new Repository("id", "svn", "Space", "Name"); + + File path = repositoryHandler.getDirectory(repository); + assertEquals("/path/id", path.getAbsolutePath()); + } } diff --git a/scm-test/src/main/java/sonia/scm/repository/DummyRepositoryHandler.java b/scm-test/src/main/java/sonia/scm/repository/DummyRepositoryHandler.java index 0a85231da0..870127b14e 100644 --- a/scm-test/src/main/java/sonia/scm/repository/DummyRepositoryHandler.java +++ b/scm-test/src/main/java/sonia/scm/repository/DummyRepositoryHandler.java @@ -1,19 +1,19 @@ /** * Copyright (c) 2010, Sebastian Sdorra * All rights reserved. - * + *

* Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + *

* 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. + * this list of conditions and the following disclaimer. * 2. 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. + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. * 3. Neither the name of SCM-Manager; nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * + * 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 @@ -24,113 +24,67 @@ * 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. - * + *

* http://bitbucket.org/sdorra/scm-manager - * */ - package sonia.scm.repository; //~--- non-JDK imports -------------------------------------------------------- import sonia.scm.Type; import sonia.scm.io.DefaultFileSystem; - -//~--- JDK imports ------------------------------------------------------------ +import sonia.scm.store.ConfigurationStoreFactory; import java.io.File; -import java.io.IOException; -import sonia.scm.store.ConfigurationStoreFactory; +import java.util.HashSet; +import java.util.Set; + +//~--- JDK imports ------------------------------------------------------------ /** * * @author Sebastian Sdorra */ public class DummyRepositoryHandler - extends AbstractSimpleRepositoryHandler -{ + extends AbstractSimpleRepositoryHandler { - /** Field description */ public static final String TYPE_DISPLAYNAME = "Dummy"; - /** Field description */ public static final String TYPE_NAME = "dummy"; - /** Field description */ public static final Type TYPE = new Type(TYPE_NAME, TYPE_DISPLAYNAME); - //~--- constructors --------------------------------------------------------- + private final Set existingRepoNames = new HashSet<>(); - /** - * Constructs ... - * - * - * @param storeFactory - */ - public DummyRepositoryHandler(ConfigurationStoreFactory storeFactory) - { + public DummyRepositoryHandler(ConfigurationStoreFactory storeFactory) { super(storeFactory, new DefaultFileSystem()); } - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ @Override - public Type getType() - { + public Type getType() { return TYPE; } - //~--- methods -------------------------------------------------------------- - /** - * Method description - * - * - * @param repository - * @param directory - * - * @throws IOException - * @throws RepositoryException - */ @Override - protected void create(Repository repository, File directory) - throws RepositoryException, IOException - { - - // do nothing + protected void create(Repository repository, File directory) throws RepositoryException { + String key = repository.getNamespace() + "/" + repository.getName(); + if (existingRepoNames.contains(key)) { + throw new RepositoryAlreadyExistsException("Repo exists"); + } else { + existingRepoNames.add(key); + } } - /** - * Method description - * - * - * @return - */ @Override - protected SimpleRepositoryConfig createInitialConfig() - { + protected SimpleRepositoryConfig createInitialConfig() { return new SimpleRepositoryConfig(); } - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ @Override - protected Class getConfigClass() - { + protected Class getConfigClass() { return SimpleRepositoryConfig.class; } } diff --git a/scm-test/src/main/java/sonia/scm/repository/RepositoryBuilder.java b/scm-test/src/main/java/sonia/scm/repository/RepositoryBuilder.java new file mode 100644 index 0000000000..9c8ceb4762 --- /dev/null +++ b/scm-test/src/main/java/sonia/scm/repository/RepositoryBuilder.java @@ -0,0 +1,49 @@ +package sonia.scm.repository; + +public class RepositoryBuilder { + + private String id = "id-" + ++nextID; + private String contact = "test@example.com"; + private String description = ""; + private String namespace = "test"; + private String name = "name"; + private String type = "git"; + + private static int nextID = 0; + + public RepositoryBuilder type(String type) { + this.type = type; + return this; + } + + public RepositoryBuilder contact(String contact) { + this.contact = contact; + return this; + } + + public RepositoryBuilder namespace(String namespace) { + this.namespace = namespace; + return this; + } + + public RepositoryBuilder name(String name) { + this.name = name; + return this; + } + + public RepositoryBuilder description(String description) { + this.description = description; + return this; + } + + public Repository build() { + Repository repository = new Repository(); + repository.setId(id); + repository.setType(type); + repository.setContact(contact); + repository.setNamespace(namespace); + repository.setName(name); + repository.setDescription(description); + return repository; + } +} diff --git a/scm-test/src/main/java/sonia/scm/repository/RepositoryTestData.java b/scm-test/src/main/java/sonia/scm/repository/RepositoryTestData.java index d5d443fe31..b81c39ca00 100644 --- a/scm-test/src/main/java/sonia/scm/repository/RepositoryTestData.java +++ b/scm-test/src/main/java/sonia/scm/repository/RepositoryTestData.java @@ -6,13 +6,13 @@ * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. + * this list of conditions and the following disclaimer. * 2. 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. + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. * 3. Neither the name of SCM-Manager; nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. + * 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 @@ -26,154 +26,68 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * http://bitbucket.org/sdorra/scm-manager - * */ - package sonia.scm.repository; -/** - * - * @author Sebastian Sdorra - */ -public final class RepositoryTestData -{ +public final class RepositoryTestData { - /** - * Constructs ... - * - */ - private RepositoryTestData() {} + private RepositoryTestData() { + } - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - public static Repository create42Puzzle() - { + public static Repository create42Puzzle() { return create42Puzzle(DummyRepositoryHandler.TYPE_NAME); } - /** - * Method description - * - * - * @param type - * - * @return - */ - public static Repository create42Puzzle(String type) - { - Repository repository = new Repository(); - - repository.setType(type); - repository.setContact("douglas.adams@hitchhiker.com"); - repository.setName("42Puzzle"); - repository.setDescription("The 42 Puzzle"); - - return repository; + public static Repository create42Puzzle(String type) { + return new RepositoryBuilder() + .type(type) + .contact("douglas.adams@hitchhiker.com") + .name("42Puzzle") + .description("The 42 Puzzle") + .build(); } - /** - * Method description - * - * - * @return - */ - public static Repository createHappyVerticalPeopleTransporter() - { + public static Repository createHappyVerticalPeopleTransporter() { return createHappyVerticalPeopleTransporter( DummyRepositoryHandler.TYPE_NAME); } - /** - * Method description - * - * - * - * @param type - * @return - */ - public static Repository createHappyVerticalPeopleTransporter(String type) - { - Repository happyVerticalPeopleTransporter = new Repository(); - - happyVerticalPeopleTransporter.setType(type); - happyVerticalPeopleTransporter.setContact( - "zaphod.beeblebrox@hitchhiker.com"); - happyVerticalPeopleTransporter.setName("happyVerticalPeopleTransporter"); - happyVerticalPeopleTransporter.setDescription( - "Happy Vertical People Transporter"); - - return happyVerticalPeopleTransporter; + public static Repository createHappyVerticalPeopleTransporter(String type) { + return new RepositoryBuilder() + .type(type) + .contact("zaphod.beeblebrox@hitchhiker.com") + .name("happyVerticalPeopleTransporter") + .description("Happy Vertical People Transporter") + .build(); } - /** - * Method description - * - * - * @return - */ - public static Repository createHeartOfGold() - { + public static Repository createHeartOfGold() { return createHeartOfGold(DummyRepositoryHandler.TYPE_NAME); } - /** - * Method description - * - * - * - * @param type - * @return - */ - public static Repository createHeartOfGold(String type) - { - Repository heartOfGold = new Repository(); - - heartOfGold.setType(type); - heartOfGold.setContact("zaphod.beeblebrox@hitchhiker.com"); - heartOfGold.setName("HeartOfGold"); - heartOfGold.setDescription( - "Heart of Gold is the first prototype ship to successfully utilise the revolutionary Infinite Improbability Drive"); - - return heartOfGold; + public static Repository createHeartOfGold(String type) { + return new RepositoryBuilder() + .type(type) + .contact("zaphod.beeblebrox@hitchhiker.com") + .name("HeartOfGold") + .description( + "Heart of Gold is the first prototype ship to successfully utilise the revolutionary Infinite Improbability Drive") + .build(); } - /** - * Method description - * - * - * @return - */ - public static Repository createRestaurantAtTheEndOfTheUniverse() - { + public static Repository createRestaurantAtTheEndOfTheUniverse() { return createRestaurantAtTheEndOfTheUniverse( DummyRepositoryHandler.TYPE_NAME); } - /** - * Method description - * - * - * @param type - * - * @return - */ - public static Repository createRestaurantAtTheEndOfTheUniverse(String type) - { - Repository repository = new Repository(); - - repository.setType(type); - repository.setContact("douglas.adams@hitchhiker.com"); - repository.setName("RestaurantAtTheEndOfTheUniverse"); - repository.setDescription("The Restaurant at the End of the Universe"); - - return repository; + public static Repository createRestaurantAtTheEndOfTheUniverse(String type) { + return new RepositoryBuilder() + .type(type) + .contact("douglas.adams@hitchhiker.com") + .name("RestaurantAtTheEndOfTheUniverse") + .description("The Restaurant at the End of the Universe") + .build(); } } diff --git a/scm-test/src/main/java/sonia/scm/repository/SimpleRepositoryHandlerTestBase.java b/scm-test/src/main/java/sonia/scm/repository/SimpleRepositoryHandlerTestBase.java index 19af367a1d..680ac83dd9 100644 --- a/scm-test/src/main/java/sonia/scm/repository/SimpleRepositoryHandlerTestBase.java +++ b/scm-test/src/main/java/sonia/scm/repository/SimpleRepositoryHandlerTestBase.java @@ -1,19 +1,19 @@ /** * Copyright (c) 2010, Sebastian Sdorra * All rights reserved. - * + *

* Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + *

* 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. + * this list of conditions and the following disclaimer. * 2. 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. + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. * 3. Neither the name of SCM-Manager; nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * + * 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 @@ -24,169 +24,88 @@ * 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. - * + *

* http://bitbucket.org/sdorra/scm-manager - * */ - package sonia.scm.repository; //~--- non-JDK imports -------------------------------------------------------- import org.junit.Test; - import sonia.scm.AbstractTestBase; +import sonia.scm.store.ConfigurationStoreFactory; import sonia.scm.store.InMemoryConfigurationStoreFactory; import sonia.scm.util.IOUtil; -import static org.junit.Assert.*; +import java.io.File; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; //~--- JDK imports ------------------------------------------------------------ -import java.io.File; -import java.io.IOException; -import sonia.scm.store.ConfigurationStoreFactory; - /** * * @author Sebastian Sdorra */ -public abstract class SimpleRepositoryHandlerTestBase extends AbstractTestBase -{ +public abstract class SimpleRepositoryHandlerTestBase extends AbstractTestBase { + - /** - * Method description - * - * - * @param directory - */ protected abstract void checkDirectory(File directory); - /** - * Method description - * - * - * @param factory - * @param directory - * - * @return - */ protected abstract RepositoryHandler createRepositoryHandler( - ConfigurationStoreFactory factory, File directory); + ConfigurationStoreFactory factory, File directory); - /** - * Method description - * - * - * @throws IOException - * @throws RepositoryException - */ @Test - public void testCreate() throws RepositoryException, IOException - { + public void testCreate() throws RepositoryException { createRepository(); } - /** - * Method description - * - * - * @throws IOException - * @throws RepositoryException - */ - @Test(expected = RepositoryAlreadyExistsException.class) - public void testCreateExisitingRepository() - throws RepositoryException, IOException - { - createRepository(); - createRepository(); - } - - /** - * Method description - * - * - * @throws IOException - * @throws RepositoryException - */ @Test - public void testCreateResourcePath() throws RepositoryException, IOException - { + public void testCreateResourcePath() throws RepositoryException { Repository repository = createRepository(); String path = handler.createResourcePath(repository); assertNotNull(path); assertTrue(path.trim().length() > 0); - assertTrue(path.contains(repository.getName())); + assertTrue(path.contains(repository.getId())); } - /** - * Method description - * - * - * @throws IOException - * @throws RepositoryException - */ @Test - public void testDelete() throws RepositoryException, IOException - { + public void testDelete() throws RepositoryException { Repository repository = createRepository(); handler.delete(repository); - File directory = new File(baseDirectory, repository.getName()); + File directory = new File(baseDirectory, repository.getId()); assertFalse(directory.exists()); } - /** - * Method description - * - * - * @throws Exception - */ @Override - protected void postSetUp() throws Exception - { + protected void postSetUp() { InMemoryConfigurationStoreFactory storeFactory = new InMemoryConfigurationStoreFactory(); baseDirectory = new File(contextProvider.getBaseDirectory(), "repositories"); IOUtil.mkdirs(baseDirectory); handler = createRepositoryHandler(storeFactory, baseDirectory); } - /** - * Method description - * - * - * @throws Exception - */ @Override - protected void preTearDown() throws Exception - { - if (handler != null) - { + protected void preTearDown() throws Exception { + if (handler != null) { handler.close(); } } - /** - * Method description - * - * - * @return - * - * @throws IOException - * @throws RepositoryException - */ - private Repository createRepository() throws RepositoryException, IOException - { + private Repository createRepository() throws RepositoryException { Repository repository = RepositoryTestData.createHeartOfGold(); handler.create(repository); - File directory = new File(baseDirectory, repository.getName()); + File directory = new File(baseDirectory, repository.getId()); assertTrue(directory.exists()); assertTrue(directory.isDirectory()); @@ -195,11 +114,7 @@ public abstract class SimpleRepositoryHandlerTestBase extends AbstractTestBase return repository; } - //~--- fields --------------------------------------------------------------- - - /** Field description */ protected File baseDirectory; - /** Field description */ private RepositoryHandler handler; } diff --git a/scm-webapp/pom.xml b/scm-webapp/pom.xml index 98c70ff82a..d02db4d203 100644 --- a/scm-webapp/pom.xml +++ b/scm-webapp/pom.xml @@ -566,7 +566,7 @@ e1 javascript:S3827 **.js - src/main/webapp/resources/extjs/**,src/main/webapp/resources/moment/**,src/main/webapp/resources/syntaxhighlighter/** + src/main/webapp** diff --git a/scm-webapp/src/main/java/sonia/scm/ManagerDaoAdapter.java b/scm-webapp/src/main/java/sonia/scm/ManagerDaoAdapter.java new file mode 100644 index 0000000000..b94ce934f6 --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/ManagerDaoAdapter.java @@ -0,0 +1,68 @@ +package sonia.scm; + +import com.github.sdorra.ssp.PermissionCheck; +import sonia.scm.util.AssertUtil; + +import java.util.function.Function; +import java.util.function.Supplier; + +public class ManagerDaoAdapter { + + private final GenericDAO dao; + private final Function notFoundException; + private final Function alreadyExistsException; + + public ManagerDaoAdapter(GenericDAO dao, Function notFoundException, Function alreadyExistsException) { + this.dao = dao; + this.notFoundException = notFoundException; + this.alreadyExistsException = alreadyExistsException; + } + + public void modify(T object, Function permissionCheck, AroundHandler beforeUpdate, AroundHandler afterUpdate) throws E { + T notModified = dao.get(object.getId()); + if (notModified != null) { + permissionCheck.apply(notModified).check(); + AssertUtil.assertIsValid(object); + + beforeUpdate.handle(notModified); + + object.setLastModified(System.currentTimeMillis()); + object.setCreationDate(notModified.getCreationDate()); + + dao.modify(object); + + afterUpdate.handle(notModified); + } else { + throw notFoundException.apply(object); + } + } + + public T create(T newObject, Supplier permissionCheck, AroundHandler beforeCreate, AroundHandler afterCreate) throws E { + permissionCheck.get().check(); + AssertUtil.assertIsValid(newObject); + if (dao.contains(newObject)) { + throw alreadyExistsException.apply(newObject); + } + newObject.setCreationDate(System.currentTimeMillis()); + beforeCreate.handle(newObject); + dao.add(newObject); + afterCreate.handle(newObject); + return newObject; + } + + public void delete(T toDelete, Supplier permissionCheck, AroundHandler beforeDelete, AroundHandler afterDelete) throws E { + permissionCheck.get().check(); + if (dao.contains(toDelete)) { + beforeDelete.handle(toDelete); + dao.delete(toDelete); + afterDelete.handle(toDelete); + } else { + throw notFoundException.apply(toDelete); + } + } + + @FunctionalInterface + public interface AroundHandler { + void handle(T notModified) throws E; + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/ScmContextListener.java b/scm-webapp/src/main/java/sonia/scm/ScmContextListener.java index 21ca876e41..1eaef333a1 100644 --- a/scm-webapp/src/main/java/sonia/scm/ScmContextListener.java +++ b/scm-webapp/src/main/java/sonia/scm/ScmContextListener.java @@ -39,14 +39,10 @@ import com.google.common.base.Throwables; import com.google.common.collect.Lists; import com.google.inject.Injector; import com.google.inject.Module; - import org.apache.shiro.guice.web.ShiroWebModule; - +import org.jboss.resteasy.plugins.guice.GuiceResteasyBootstrapServletContextListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - -import org.jboss.resteasy.plugins.guice.GuiceResteasyBootstrapServletContextListener; - import sonia.scm.api.v2.resources.MapperModule; import sonia.scm.cache.CacheManager; import sonia.scm.debug.DebugModule; @@ -61,14 +57,13 @@ import sonia.scm.upgrade.UpgradeManager; import sonia.scm.user.UserManager; import sonia.scm.util.IOUtil; -//~--- JDK imports ------------------------------------------------------------ - -import java.util.List; -import java.util.Set; -import java.util.Collections; - import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +//~--- JDK imports ------------------------------------------------------------ /** * @@ -140,7 +135,7 @@ public class ScmContextListener extends GuiceResteasyBootstrapServletContextList moduleList.add(new EagerSingletonModule()); moduleList.add(ShiroWebModule.guiceFilterModule()); moduleList.add(new WebElementModule(pluginLoader)); - moduleList.add(new ScmServletModule(context, pluginLoader, overrides)); + moduleList.add(new ScmServletModule(context, pluginLoader, overrides, pluginLoader.getExtensionProcessor())); moduleList.add( new ScmSecurityModule(context, pluginLoader.getExtensionProcessor()) ); diff --git a/scm-webapp/src/main/java/sonia/scm/ScmServletModule.java b/scm-webapp/src/main/java/sonia/scm/ScmServletModule.java index a09de33465..1d318ce1c8 100644 --- a/scm-webapp/src/main/java/sonia/scm/ScmServletModule.java +++ b/scm-webapp/src/main/java/sonia/scm/ScmServletModule.java @@ -38,14 +38,11 @@ package sonia.scm; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.inject.Provider; import com.google.inject.multibindings.Multibinder; -import com.google.inject.name.Names; import com.google.inject.servlet.RequestScoped; import com.google.inject.servlet.ServletModule; import com.google.inject.throwingproviders.ThrowingProviderBinder; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import sonia.scm.api.rest.ObjectMapperProvider; import sonia.scm.cache.CacheManager; import sonia.scm.cache.GuavaCacheManager; @@ -58,18 +55,10 @@ import sonia.scm.group.GroupManagerProvider; import sonia.scm.group.xml.XmlGroupDAO; import sonia.scm.io.DefaultFileSystem; import sonia.scm.io.FileSystem; -import sonia.scm.plugin.DefaultPluginLoader; -import sonia.scm.plugin.DefaultPluginManager; -import sonia.scm.plugin.PluginLoader; -import sonia.scm.plugin.PluginManager; -import sonia.scm.repository.DefaultRepositoryManager; -import sonia.scm.repository.DefaultRepositoryProvider; -import sonia.scm.repository.HealthCheckContextListener; -import sonia.scm.repository.Repository; -import sonia.scm.repository.RepositoryDAO; -import sonia.scm.repository.RepositoryManager; -import sonia.scm.repository.RepositoryManagerProvider; -import sonia.scm.repository.RepositoryProvider; +import sonia.scm.net.SSLContextProvider; +import sonia.scm.net.ahc.*; +import sonia.scm.plugin.*; +import sonia.scm.repository.*; import sonia.scm.repository.api.HookContextFactory; import sonia.scm.repository.api.RepositoryServiceFactory; import sonia.scm.repository.spi.HookEventFacade; @@ -78,28 +67,14 @@ import sonia.scm.resources.DefaultResourceManager; import sonia.scm.resources.DevelopmentResourceManager; import sonia.scm.resources.ResourceManager; import sonia.scm.resources.ScriptResourceServlet; -import sonia.scm.security.CipherHandler; -import sonia.scm.security.CipherUtil; -import sonia.scm.security.DefaultKeyGenerator; -import sonia.scm.security.DefaultSecuritySystem; -import sonia.scm.security.KeyGenerator; -import sonia.scm.security.SecuritySystem; -import sonia.scm.store.BlobStoreFactory; -import sonia.scm.store.ConfigurationEntryStoreFactory; -import sonia.scm.store.DataStoreFactory; -import sonia.scm.store.FileBlobStoreFactory; -import sonia.scm.store.JAXBConfigurationEntryStoreFactory; -import sonia.scm.store.JAXBDataStoreFactory; -import sonia.scm.store.JAXBConfigurationStoreFactory; +import sonia.scm.schedule.QuartzScheduler; +import sonia.scm.schedule.Scheduler; +import sonia.scm.security.*; +import sonia.scm.store.*; import sonia.scm.template.MustacheTemplateEngine; import sonia.scm.template.TemplateEngine; import sonia.scm.template.TemplateEngineFactory; import sonia.scm.template.TemplateServlet; -import sonia.scm.url.RestJsonUrlProvider; -import sonia.scm.url.RestXmlUrlProvider; -import sonia.scm.url.UrlProvider; -import sonia.scm.url.UrlProviderFactory; -import sonia.scm.url.WebUIUrlProvider; import sonia.scm.user.DefaultUserManager; import sonia.scm.user.UserDAO; import sonia.scm.user.UserManager; @@ -107,31 +82,17 @@ import sonia.scm.user.UserManagerProvider; import sonia.scm.user.xml.XmlUserDAO; import sonia.scm.util.DebugServlet; import sonia.scm.util.ScmConfigurationUtil; +import sonia.scm.web.UserAgentParser; import sonia.scm.web.cgi.CGIExecutorFactory; import sonia.scm.web.cgi.DefaultCGIExecutorFactory; import sonia.scm.web.filter.LoggingFilter; import sonia.scm.web.security.AdministrationContext; import sonia.scm.web.security.DefaultAdministrationContext; -//~--- JDK imports ------------------------------------------------------------ - - -import javax.servlet.ServletContext; -import sonia.scm.store.ConfigurationStoreFactory; - import javax.net.ssl.SSLContext; -import sonia.scm.net.SSLContextProvider; -import sonia.scm.net.ahc.AdvancedHttpClient; -import sonia.scm.net.ahc.ContentTransformer; -import sonia.scm.net.ahc.DefaultAdvancedHttpClient; -import sonia.scm.net.ahc.JsonContentTransformer; -import sonia.scm.net.ahc.XmlContentTransformer; -import sonia.scm.schedule.QuartzScheduler; -import sonia.scm.schedule.Scheduler; -import sonia.scm.security.ConfigurableLoginAttemptHandler; -import sonia.scm.security.LoginAttemptHandler; -import sonia.scm.security.AuthorizationChangedEventProducer; -import sonia.scm.web.UserAgentParser; +import javax.servlet.ServletContext; + +//~--- JDK imports ------------------------------------------------------------ /** * @@ -202,17 +163,18 @@ public class ScmServletModule extends ServletModule * Constructs ... * * - * * @param servletContext * @param pluginLoader * @param overrides + * @param extensionProcessor */ ScmServletModule(ServletContext servletContext, - DefaultPluginLoader pluginLoader, ClassOverrides overrides) + DefaultPluginLoader pluginLoader, ClassOverrides overrides, ExtensionProcessor extensionProcessor) { this.servletContext = servletContext; this.pluginLoader = pluginLoader; this.overrides = overrides; + this.extensionProcessor = extensionProcessor; } //~--- methods -------------------------------------------------------------- @@ -232,7 +194,9 @@ public class ScmServletModule extends ServletModule ScmConfiguration config = getScmConfiguration(); CipherUtil cu = CipherUtil.getInstance(); - + + bind(NamespaceStrategy.class).toProvider(NamespaceStrategyProvider.class); + // bind repository provider ThrowingProviderBinder.create(binder()).bind( RepositoryProvider.class, Repository.class).to( @@ -295,7 +259,6 @@ public class ScmServletModule extends ServletModule // bind sslcontext provider bind(SSLContext.class).toProvider(SSLContextProvider.class); - // bind ahc Multibinder transformers = Multibinder.newSetBinder(binder(), ContentTransformer.class); @@ -313,17 +276,6 @@ public class ScmServletModule extends ServletModule bind(ResourceManager.class, DefaultResourceManager.class); } - // bind url provider staff - bind(UrlProvider.class).annotatedWith( - Names.named(UrlProviderFactory.TYPE_RESTAPI_JSON)).toProvider( - RestJsonUrlProvider.class); - bind(UrlProvider.class).annotatedWith( - Names.named(UrlProviderFactory.TYPE_RESTAPI_XML)).toProvider( - RestXmlUrlProvider.class); - bind(UrlProvider.class).annotatedWith( - Names.named(UrlProviderFactory.TYPE_WUI)).toProvider( - WebUIUrlProvider.class); - // bind repository service factory bind(RepositoryServiceFactory.class); @@ -360,8 +312,11 @@ public class ScmServletModule extends ServletModule // bind events // bind(LastModifiedUpdateListener.class); + + } + /** * Method description * @@ -476,4 +431,6 @@ public class ScmServletModule extends ServletModule /** Field description */ private final ServletContext servletContext; + + private final ExtensionProcessor extensionProcessor; } diff --git a/scm-webapp/src/main/java/sonia/scm/api/rest/RepositoryAlreadyExistsExceptionMapper.java b/scm-webapp/src/main/java/sonia/scm/api/rest/RepositoryAlreadyExistsExceptionMapper.java new file mode 100644 index 0000000000..e69b9e98d6 --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/api/rest/RepositoryAlreadyExistsExceptionMapper.java @@ -0,0 +1,16 @@ +package sonia.scm.api.rest; + +import sonia.scm.repository.RepositoryAlreadyExistsException; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +@Provider +public class RepositoryAlreadyExistsExceptionMapper implements ExceptionMapper { + @Override + public Response toResponse(RepositoryAlreadyExistsException exception) { + return Response.status(Status.CONFLICT).build(); + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/api/rest/resources/AbstractManagerResource.java b/scm-webapp/src/main/java/sonia/scm/api/rest/resources/AbstractManagerResource.java index 4d9d9f997d..b8a3dfc45d 100644 --- a/scm-webapp/src/main/java/sonia/scm/api/rest/resources/AbstractManagerResource.java +++ b/scm-webapp/src/main/java/sonia/scm/api/rest/resources/AbstractManagerResource.java @@ -55,6 +55,11 @@ import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; +import java.beans.BeanInfo; +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Date; @@ -76,17 +81,15 @@ public abstract class AbstractManagerResource manager; + private final Class type; - /** - * Constructs ... - * - * - * @param manager - */ - public AbstractManagerResource(Manager manager) - { + protected int cacheMaxAge = 0; + protected boolean disableCache = false; + + public AbstractManagerResource(Manager manager, Class type) { this.manager = manager; + this.type = type; } //~--- methods -------------------------------------------------------------- @@ -159,7 +162,7 @@ public abstract class AbstractManagerResource createComparator(String sortby, boolean desc) + private Comparator createComparator(String sortBy, boolean desc) { + checkSortByField(sortBy); Comparator comparator; if (desc) { - comparator = new BeanReverseComparator(sortby); + comparator = new BeanReverseComparator(sortBy); } else { - comparator = new BeanComparator(sortby); + comparator = new BeanComparator(sortBy); } return comparator; } - /** - * Method description - * - * - * - * @param sortby - * @param desc - * @param start - * @param limit - * - * @return - */ - private Collection fetchItems(String sortby, boolean desc, int start, + private Collection fetchItems(String sortBy, boolean desc, int start, int limit) { AssertUtil.assertPositive(start); @@ -573,18 +556,18 @@ public abstract class AbstractManagerResource 0) { - if (Util.isEmpty(sortby)) + if (Util.isEmpty(sortBy)) { // replace with something useful - sortby = "id"; + sortBy = "id"; } - items = manager.getAll(createComparator(sortby, desc), start, limit); + items = manager.getAll(createComparator(sortBy, desc), start, limit); } - else if (Util.isNotEmpty(sortby)) + else if (Util.isNotEmpty(sortBy)) { - items = manager.getAll(createComparator(sortby, desc)); + items = manager.getAll(createComparator(sortBy, desc)); } else { @@ -594,17 +577,32 @@ public abstract class AbstractManagerResource fetchPage(String sortby, boolean desc, int pageNumber, + // We have to handle IntrospectionException here, because it's a checked exception + // It shouldn't occur really - so creating a new unchecked exception would be over-engineered here + @SuppressWarnings("squid:S00112") + private void checkSortByField(String sortBy) { + try { + BeanInfo info = Introspector.getBeanInfo(type); + PropertyDescriptor[] pds = info.getPropertyDescriptors(); + if (Arrays.stream(pds).noneMatch(p -> p.getName().equals(sortBy))) { + throw new IllegalArgumentException("sortBy"); + } + } catch (IntrospectionException e) { + throw new RuntimeException("error introspecting model type " + type.getName(), e); + } + } + + protected PageResult fetchPage(String sortBy, boolean desc, int pageNumber, int pageSize) { AssertUtil.assertPositive(pageNumber); AssertUtil.assertPositive(pageSize); - if (Util.isEmpty(sortby)) { + if (Util.isEmpty(sortBy)) { // replace with something useful - sortby = "id"; + sortBy = "id"; } - return manager.getPage(createComparator(sortby, desc), pageNumber, pageSize); + return manager.getPage(createComparator(sortBy, desc), pageNumber, pageSize); } //~--- get methods ---------------------------------------------------------- @@ -676,16 +674,4 @@ public abstract class AbstractManagerResource manager; } diff --git a/scm-webapp/src/main/java/sonia/scm/api/rest/resources/GroupResource.java b/scm-webapp/src/main/java/sonia/scm/api/rest/resources/GroupResource.java index 364a1b200e..b9701f7e38 100644 --- a/scm-webapp/src/main/java/sonia/scm/api/rest/resources/GroupResource.java +++ b/scm-webapp/src/main/java/sonia/scm/api/rest/resources/GroupResource.java @@ -41,18 +41,12 @@ import com.webcohesion.enunciate.metadata.rs.ResponseCode; import com.webcohesion.enunciate.metadata.rs.ResponseHeader; import com.webcohesion.enunciate.metadata.rs.StatusCodes; import com.webcohesion.enunciate.metadata.rs.TypeHint; - import org.apache.shiro.SecurityUtils; - import sonia.scm.group.Group; import sonia.scm.group.GroupException; import sonia.scm.group.GroupManager; import sonia.scm.security.Role; -//~--- JDK imports ------------------------------------------------------------ - -import java.util.Collection; - import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; @@ -69,6 +63,9 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; +import java.util.Collection; + +//~--- JDK imports ------------------------------------------------------------ /** * RESTful Web Service Resource to manage groups and their members. @@ -97,7 +94,7 @@ public class GroupResource @Inject public GroupResource(GroupManager groupManager) { - super(groupManager); + super(groupManager, Group.class); } //~--- methods -------------------------------------------------------------- diff --git a/scm-webapp/src/main/java/sonia/scm/api/rest/resources/RepositoryImportResource.java b/scm-webapp/src/main/java/sonia/scm/api/rest/resources/RepositoryImportResource.java index 0fe6f8df1d..a2be057bdf 100644 --- a/scm-webapp/src/main/java/sonia/scm/api/rest/resources/RepositoryImportResource.java +++ b/scm-webapp/src/main/java/sonia/scm/api/rest/resources/RepositoryImportResource.java @@ -40,12 +40,13 @@ import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.io.Files; import com.google.inject.Inject; - +import com.webcohesion.enunciate.metadata.rs.ResponseCode; +import com.webcohesion.enunciate.metadata.rs.ResponseHeader; +import com.webcohesion.enunciate.metadata.rs.StatusCodes; +import com.webcohesion.enunciate.metadata.rs.TypeHint; import org.apache.shiro.SecurityUtils; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import sonia.scm.NotSupportedFeatuerException; import sonia.scm.Type; import sonia.scm.api.rest.RestActionUploadResult; @@ -65,26 +66,6 @@ import sonia.scm.repository.api.UnbundleCommandBuilder; import sonia.scm.security.Role; import sonia.scm.util.IOUtil; -import static com.google.common.base.Preconditions.*; - -//~--- JDK imports ------------------------------------------------------------ - -import com.webcohesion.enunciate.metadata.rs.ResponseCode; -import com.webcohesion.enunciate.metadata.rs.ResponseHeader; -import com.webcohesion.enunciate.metadata.rs.StatusCodes; -import com.webcohesion.enunciate.metadata.rs.TypeHint; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import java.net.URI; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Set; - import javax.ws.rs.Consumes; import javax.ws.rs.DefaultValue; import javax.ws.rs.FormParam; @@ -100,10 +81,22 @@ import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Set; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +//~--- JDK imports ------------------------------------------------------------ /** * Rest resource for importing repositories. @@ -550,7 +543,8 @@ public class RepositoryImportResource try { - repository = new Repository(null, type, name); + // TODO #8783 +// repository = new Repository(null, type, name); manager.create(repository); } catch (RepositoryAlreadyExistsException ex) @@ -564,10 +558,6 @@ public class RepositoryImportResource { handleGenericCreationFailure(ex, type, name); } - catch (IOException ex) - { - handleGenericCreationFailure(ex, type, name); - } return repository; } @@ -716,10 +706,6 @@ public class RepositoryImportResource { manager.delete(repository); } - catch (IOException e) - { - logger.error("can not delete repository", e); - } catch (RepositoryException e) { logger.error("can not delete repository", e); @@ -753,7 +739,8 @@ public class RepositoryImportResource { for (String repositoryName : repositoryNames) { - Repository repository = manager.get(type, repositoryName); + // TODO #8783 + /*Repository repository = null; //manager.get(type, repositoryName); if (repository != null) { @@ -763,7 +750,7 @@ public class RepositoryImportResource { logger.warn("could not find imported repository {}", repositoryName); - } + }*/ } } } diff --git a/scm-webapp/src/main/java/sonia/scm/api/rest/resources/RepositoryResource.java b/scm-webapp/src/main/java/sonia/scm/api/rest/resources/RepositoryResource.java index 06345b9fdd..459a094914 100644 --- a/scm-webapp/src/main/java/sonia/scm/api/rest/resources/RepositoryResource.java +++ b/scm-webapp/src/main/java/sonia/scm/api/rest/resources/RepositoryResource.java @@ -42,13 +42,10 @@ import com.webcohesion.enunciate.metadata.rs.ResponseCode; import com.webcohesion.enunciate.metadata.rs.ResponseHeader; import com.webcohesion.enunciate.metadata.rs.StatusCodes; import com.webcohesion.enunciate.metadata.rs.TypeHint; - import org.apache.shiro.SecurityUtils; - +import org.apache.shiro.authz.AuthorizationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - -import sonia.scm.config.ScmConfiguration; import sonia.scm.repository.BlameResult; import sonia.scm.repository.Branches; import sonia.scm.repository.BrowserResult; @@ -76,13 +73,6 @@ import sonia.scm.util.HttpUtil; import sonia.scm.util.IOUtil; import sonia.scm.util.Util; -//~--- JDK imports ------------------------------------------------------------ - -import java.io.IOException; - -import java.util.ArrayList; -import java.util.Collection; - import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; @@ -101,7 +91,11 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.StreamingOutput; import javax.ws.rs.core.UriInfo; -import org.apache.shiro.authz.AuthorizationException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; + +//~--- JDK imports ------------------------------------------------------------ /** * Repository related RESTful Web Service Endpoint. @@ -125,19 +119,15 @@ public class RepositoryResource extends AbstractManagerResource unsortedRepositories = Collections2.transform( Collections2.filter( repositoryManager.getAll(), new RepositoryTypePredicate(type)) - , new RepositoryTransformFunction(uiUrlProvider, baseUrl) + , new RepositoryTransformFunction(baseUrl) ); List repositories = Ordering.from( @@ -149,43 +143,16 @@ public class RepositoryRootResource * * * @param repository - * @param uiUrlProvider * @param baseUrl */ - public RepositoryTemplateElement(Repository repository, - UrlProvider uiUrlProvider, String baseUrl) + public RepositoryTemplateElement(Repository repository, String baseUrl) { this.repository = repository; - this.urlProvider = uiUrlProvider; this.baseUrl = baseUrl; } //~--- get methods -------------------------------------------------------- - /** - * Method description - * - * - * @return - */ - public String getCommitUrl() - { - return urlProvider.getRepositoryUrlProvider().getChangesetUrl( - repository.getId(), 0, 20); - } - - /** - * Method description - * - * - * @return - */ - public String getDetailUrl() - { - return urlProvider.getRepositoryUrlProvider().getDetailUrl( - repository.getId()); - } - /** * Method description * @@ -208,18 +175,6 @@ public class RepositoryRootResource return repository; } - /** - * Method description - * - * - * @return - */ - public String getSourceUrl() - { - return urlProvider.getRepositoryUrlProvider().getBrowseUrl( - repository.getId(), null, null); - } - /** * Method description * @@ -239,8 +194,6 @@ public class RepositoryRootResource /** Field description */ private Repository repository; - /** Field description */ - private UrlProvider urlProvider; } @@ -284,20 +237,8 @@ public class RepositoryRootResource implements Function { - /** - * Constructs ... - * - * - * - * - * @param request - * @param repositoryManager - * @param urlProvider - * @param baseUrl - */ - public RepositoryTransformFunction(UrlProvider urlProvider, String baseUrl) + public RepositoryTransformFunction(String baseUrl) { - this.urlProvider = urlProvider; this.baseUrl = baseUrl; } @@ -314,15 +255,12 @@ public class RepositoryRootResource @Override public RepositoryTemplateElement apply(Repository repository) { - return new RepositoryTemplateElement(repository, urlProvider, baseUrl); + return new RepositoryTemplateElement(repository, baseUrl); } //~--- fields ------------------------------------------------------------- /** Field description */ private String baseUrl; - - /** Field description */ - private UrlProvider urlProvider; } } diff --git a/scm-webapp/src/main/java/sonia/scm/api/rest/resources/UserResource.java b/scm-webapp/src/main/java/sonia/scm/api/rest/resources/UserResource.java index 0aab581c3d..f9dc40f0fc 100644 --- a/scm-webapp/src/main/java/sonia/scm/api/rest/resources/UserResource.java +++ b/scm-webapp/src/main/java/sonia/scm/api/rest/resources/UserResource.java @@ -41,10 +41,8 @@ import com.webcohesion.enunciate.metadata.rs.ResponseCode; import com.webcohesion.enunciate.metadata.rs.ResponseHeader; import com.webcohesion.enunciate.metadata.rs.StatusCodes; import com.webcohesion.enunciate.metadata.rs.TypeHint; - import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.credential.PasswordService; - import sonia.scm.security.Role; import sonia.scm.user.User; import sonia.scm.user.UserException; @@ -52,11 +50,6 @@ import sonia.scm.user.UserManager; import sonia.scm.util.AssertUtil; import sonia.scm.util.Util; -//~--- JDK imports ------------------------------------------------------------ - -import java.util.Collection; - -import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; @@ -72,6 +65,9 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; +import java.util.Collection; + +//~--- JDK imports ------------------------------------------------------------ /** * RESTful Web Service Resource to manage users. @@ -101,7 +97,7 @@ public class UserResource extends AbstractManagerResource @Inject public UserResource(UserManager userManager, PasswordService passwordService) { - super(userManager); + super(userManager, User.class); this.passwordService = passwordService; } diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/BaseMapper.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/BaseMapper.java index f92d0d6e99..94d884c437 100644 --- a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/BaseMapper.java +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/BaseMapper.java @@ -3,25 +3,15 @@ package sonia.scm.api.v2.resources; import de.otto.edison.hal.HalRepresentation; import org.mapstruct.Mapping; import sonia.scm.ModelObject; -import sonia.scm.util.AssertUtil; import java.time.Instant; -import java.util.Optional; abstract class BaseMapper { - @Mapping(target = "attributes", ignore = true) // We do not map HAL attributes - public abstract D map(T user); + public abstract D map(T modelObject); Instant mapTime(Long epochMilli) { - AssertUtil.assertIsNotNull(epochMilli); - return Instant.ofEpochMilli(epochMilli); - } - - Optional mapOptionalTime(Long epochMilli) { - return Optional - .ofNullable(epochMilli) - .map(Instant::ofEpochMilli); + return epochMilli == null? null: Instant.ofEpochMilli(epochMilli); } } diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/BranchCollectionResource.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/BranchCollectionResource.java new file mode 100644 index 0000000000..d64016b475 --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/BranchCollectionResource.java @@ -0,0 +1,18 @@ +package sonia.scm.api.v2.resources; + +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; + +public class BranchCollectionResource { + @GET + @Path("") + public Response getAll(@DefaultValue("0") @QueryParam("page") int page, + @DefaultValue("10") @QueryParam("pageSize") int pageSize, + @QueryParam("sortBy") String sortBy, + @DefaultValue("false") @QueryParam("desc") boolean desc) { + throw new UnsupportedOperationException(); + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/BranchRootResource.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/BranchRootResource.java new file mode 100644 index 0000000000..ee50fdcd1e --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/BranchRootResource.java @@ -0,0 +1,20 @@ +package sonia.scm.api.v2.resources; + +import javax.inject.Inject; +import javax.inject.Provider; +import javax.ws.rs.Path; + +public class BranchRootResource { + + private final Provider branchCollectionResource; + + @Inject + public BranchRootResource(Provider branchCollectionResource) { + this.branchCollectionResource = branchCollectionResource; + } + + @Path("") + public BranchCollectionResource getBranchCollectionResource() { + return branchCollectionResource.get(); + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/ChangesetCollectionResource.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/ChangesetCollectionResource.java new file mode 100644 index 0000000000..d42494a270 --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/ChangesetCollectionResource.java @@ -0,0 +1,18 @@ +package sonia.scm.api.v2.resources; + +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; + +public class ChangesetCollectionResource { + @GET + @Path("") + public Response getAll(@DefaultValue("0") @QueryParam("page") int page, + @DefaultValue("10") @QueryParam("pageSize") int pageSize, + @QueryParam("sortBy") String sortBy, + @DefaultValue("false") @QueryParam("desc") boolean desc) { + throw new UnsupportedOperationException(); + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/ChangesetRootResource.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/ChangesetRootResource.java new file mode 100644 index 0000000000..1681a27cd4 --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/ChangesetRootResource.java @@ -0,0 +1,20 @@ +package sonia.scm.api.v2.resources; + +import javax.inject.Inject; +import javax.inject.Provider; +import javax.ws.rs.Path; + +public class ChangesetRootResource { + + private final Provider changesetCollectionResource; + + @Inject + public ChangesetRootResource(Provider changesetCollectionResource) { + this.changesetCollectionResource = changesetCollectionResource; + } + + @Path("") + public ChangesetCollectionResource getChangesetCollectionResource() { + return changesetCollectionResource.get(); + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/ResourceManagerAdapter.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/CollectionResourceManagerAdapter.java similarity index 59% rename from scm-webapp/src/main/java/sonia/scm/api/v2/resources/ResourceManagerAdapter.java rename to scm-webapp/src/main/java/sonia/scm/api/v2/resources/CollectionResourceManagerAdapter.java index c2aab1a058..3169088331 100644 --- a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/ResourceManagerAdapter.java +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/CollectionResourceManagerAdapter.java @@ -8,7 +8,6 @@ import sonia.scm.api.rest.resources.AbstractManagerResource; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.Response; -import java.io.IOException; import java.net.URI; import java.util.Collection; import java.util.function.Function; @@ -17,50 +16,23 @@ import java.util.function.Supplier; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; /** - * Adapter from resource http endpoints to managers. + * Adapter from resource http endpoints to managers, for Collection resources (e.g. {@code /users}). * * Provides common CRUD operations and DTO to Model Object mapping to keep Resources more DRY. * * @param The type of the model object, eg. {@link sonia.scm.user.User}. * @param The corresponding transport object, eg. {@link UserDto}. * @param The exception type for the model object, eg. {@link sonia.scm.user.UserException}. + * + * @see SingleResourceManagerAdapter */ @SuppressWarnings("squid:S00119") // "MODEL_OBJECT" is much more meaningful than "M", right? -class ResourceManagerAdapter extends AbstractManagerResource { - ResourceManagerAdapter(Manager manager) { - super(manager); - } - - /** - * Reads the model object for the given id, transforms it to a dto and returns a corresponding http response. - * This handles all corner cases, eg. no matching object for the id or missing privileges. - */ - Response get(String id, Function mapToDto) { - MODEL_OBJECT modelObject = manager.get(id); - if (modelObject == null) { - return Response.status(Response.Status.NOT_FOUND).build(); - } - DTO dto = mapToDto.apply(modelObject); - return Response.ok(dto).build(); - } - - /** - * Update the model object for the given id according to the given function and returns a corresponding http response. - * This handles all corner cases, eg. no matching object for the id or missing privileges. - */ - public Response update(String id, Function applyChanges) { - MODEL_OBJECT existingModelObject = manager.get(id); - if (existingModelObject == null) { - return Response.status(Response.Status.NOT_FOUND).build(); - } - MODEL_OBJECT changedModelObject = applyChanges.apply(existingModelObject); - if (!id.equals(changedModelObject.getId())) { - return Response.status(BAD_REQUEST).entity("illegal change of id").build(); - } - return update(id, changedModelObject); + CollectionResourceManagerAdapter(Manager manager, Class type) { + super(manager, type); } /** @@ -76,13 +48,13 @@ class ResourceManagerAdapter modelObjectSupplier, Function uriCreator) throws IOException, EXCEPTION { + public Response create(DTO dto, Supplier modelObjectSupplier, Function uriCreator) throws EXCEPTION { if (dto == null) { return Response.status(BAD_REQUEST).build(); } MODEL_OBJECT modelObject = modelObjectSupplier.get(); - manager.create(modelObject); - return Response.created(URI.create(uriCreator.apply(modelObject))).build(); + MODEL_OBJECT created = manager.create(modelObject); + return Response.created(URI.create(uriCreator.apply(created))).build(); } @Override diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/GroupCollectionResource.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/GroupCollectionResource.java index 12a3cd58f1..d806d3cee7 100644 --- a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/GroupCollectionResource.java +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/GroupCollectionResource.java @@ -18,38 +18,35 @@ import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; import java.io.IOException; -import static sonia.scm.api.v2.resources.ResourceLinks.group; public class GroupCollectionResource { private static final int DEFAULT_PAGE_SIZE = 10; private final GroupDtoToGroupMapper dtoToGroupMapper; private final GroupCollectionToDtoMapper groupCollectionToDtoMapper; + private final ResourceLinks resourceLinks; - private final ResourceManagerAdapter adapter; + private final IdResourceManagerAdapter adapter; @Inject - public GroupCollectionResource(GroupManager manager, GroupDtoToGroupMapper dtoToGroupMapper, GroupCollectionToDtoMapper groupCollectionToDtoMapper) { + public GroupCollectionResource(GroupManager manager, GroupDtoToGroupMapper dtoToGroupMapper, GroupCollectionToDtoMapper groupCollectionToDtoMapper, ResourceLinks resourceLinks) { this.dtoToGroupMapper = dtoToGroupMapper; this.groupCollectionToDtoMapper = groupCollectionToDtoMapper; - this.adapter = new ResourceManagerAdapter<>(manager); + this.resourceLinks = resourceLinks; + this.adapter = new IdResourceManagerAdapter<>(manager, Group.class); } /** * Returns all groups for a given page number with a given page size (default page size is {@value DEFAULT_PAGE_SIZE}). - * + * * Note: This method requires "group" privilege. * - * @param request the current request * @param page the number of the requested page * @param pageSize the page size (default page size is {@value DEFAULT_PAGE_SIZE}) - * @param sortBy sort parameter + * @param sortBy sort parameter (if empty - undefined sorting) * @param desc sort direction desc or aesc */ @GET @@ -58,14 +55,14 @@ public class GroupCollectionResource { @TypeHint(GroupDto[].class) @StatusCodes({ @ResponseCode(code = 200, condition = "success"), + @ResponseCode(code = 400, condition = "\"sortBy\" field unknown"), @ResponseCode(code = 401, condition = "not authenticated / invalid credentials"), @ResponseCode(code = 403, condition = "not authorized, the current user does not have the \"group\" privilege"), @ResponseCode(code = 500, condition = "internal server error") }) - public Response getAll(@Context Request request, - @DefaultValue("0") @QueryParam("page") int page, + public Response getAll(@DefaultValue("0") @QueryParam("page") int page, @DefaultValue("" + DEFAULT_PAGE_SIZE) @QueryParam("pageSize") int pageSize, - @QueryParam("sortby") String sortBy, + @QueryParam("sortBy") String sortBy, @DefaultValue("false") @QueryParam("desc") boolean desc) { return adapter.getAll(page, pageSize, sortBy, desc, @@ -89,9 +86,9 @@ public class GroupCollectionResource { }) @TypeHint(TypeHint.NO_CONTENT.class) @ResponseHeaders(@ResponseHeader(name = "Location", description = "uri to the created group")) - public Response create(@Context UriInfo uriInfo, GroupDto groupDto) throws IOException, GroupException { + public Response create(GroupDto groupDto) throws IOException, GroupException { return adapter.create(groupDto, () -> dtoToGroupMapper.map(groupDto), - group -> group(uriInfo).self(group.getName())); + group -> resourceLinks.group().self(group.getName())); } } diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/GroupCollectionToDtoMapper.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/GroupCollectionToDtoMapper.java index 7b09d91a9f..415f04bfaf 100644 --- a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/GroupCollectionToDtoMapper.java +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/GroupCollectionToDtoMapper.java @@ -5,26 +5,24 @@ import sonia.scm.group.GroupPermissions; import javax.inject.Inject; -import static sonia.scm.api.v2.resources.ResourceLinks.groupCollection; - public class GroupCollectionToDtoMapper extends BasicCollectionToDtoMapper { - private final UriInfoStore uriInfoStore; + private final ResourceLinks resourceLinks; @Inject - public GroupCollectionToDtoMapper(GroupToGroupDtoMapper groupToDtoMapper, UriInfoStore uriInfoStore) { + public GroupCollectionToDtoMapper(GroupToGroupDtoMapper groupToDtoMapper, ResourceLinks resourceLinks) { super("groups", groupToDtoMapper); - this.uriInfoStore = uriInfoStore; + this.resourceLinks = resourceLinks; } @Override String createCreateLink() { - return groupCollection(uriInfoStore.get()).create(); + return resourceLinks.groupCollection().create(); } @Override String createSelfLink() { - return groupCollection(uriInfoStore.get()).self(); + return resourceLinks.groupCollection().self(); } @Override diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/GroupDto.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/GroupDto.java index 081ae817ae..3944be81b8 100644 --- a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/GroupDto.java +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/GroupDto.java @@ -10,15 +10,14 @@ import lombok.Setter; import java.time.Instant; import java.util.List; import java.util.Map; -import java.util.Optional; @Getter @Setter @NoArgsConstructor public class GroupDto extends HalRepresentation { private Instant creationDate; private String description; - @JsonInclude(JsonInclude.Include.NON_EMPTY) - private Optional lastModified; + @JsonInclude(JsonInclude.Include.NON_NULL) + private Instant lastModified; private String name; private String type; private Map properties; diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/GroupResource.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/GroupResource.java index f8c7a3852c..c9f066790b 100644 --- a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/GroupResource.java +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/GroupResource.java @@ -9,24 +9,27 @@ import sonia.scm.group.GroupManager; import sonia.scm.web.VndMediaType; import javax.inject.Inject; -import javax.ws.rs.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Request; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; public class GroupResource { private final GroupToGroupDtoMapper groupToGroupDtoMapper; private final GroupDtoToGroupMapper dtoToGroupMapper; - private final ResourceManagerAdapter adapter; + private final IdResourceManagerAdapter adapter; @Inject public GroupResource(GroupManager manager, GroupToGroupDtoMapper groupToGroupDtoMapper, GroupDtoToGroupMapper groupDtoToGroupMapper) { this.groupToGroupDtoMapper = groupToGroupDtoMapper; this.dtoToGroupMapper = groupDtoToGroupMapper; - this.adapter = new ResourceManagerAdapter<>(manager); + this.adapter = new IdResourceManagerAdapter<>(manager, Group.class); } /** @@ -34,7 +37,6 @@ public class GroupResource { * * Note: This method requires "group" privilege. * - * @param request the current request * @param id the id/name of the group * */ @@ -49,7 +51,7 @@ public class GroupResource { @ResponseCode(code = 404, condition = "not found, no group with the specified id/name available"), @ResponseCode(code = 500, condition = "internal server error") }) - public Response get(@Context Request request, @Context UriInfo uriInfo, @PathParam("id") String id) { + public Response get(@PathParam("id") String id) { return adapter.get(id, groupToGroupDtoMapper::map); } @@ -87,13 +89,14 @@ public class GroupResource { @Consumes(VndMediaType.GROUP) @StatusCodes({ @ResponseCode(code = 204, condition = "update success"), + @ResponseCode(code = 400, condition = "Invalid body, e.g. illegal change of id/group name"), @ResponseCode(code = 401, condition = "not authenticated / invalid credentials"), @ResponseCode(code = 403, condition = "not authorized, the current user does not have the \"group\" privilege"), @ResponseCode(code = 404, condition = "not found, no group with the specified id/name available"), @ResponseCode(code = 500, condition = "internal server error") }) @TypeHint(TypeHint.NO_CONTENT.class) - public Response update(@Context UriInfo uriInfo, @PathParam("id") String name, GroupDto groupDto) { + public Response update(@PathParam("id") String name, GroupDto groupDto) { return adapter.update(name, existing -> dtoToGroupMapper.map(groupDto)); } } diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/GroupToGroupDtoMapper.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/GroupToGroupDtoMapper.java index 57008f6313..d03fc94387 100644 --- a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/GroupToGroupDtoMapper.java +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/GroupToGroupDtoMapper.java @@ -13,8 +13,6 @@ import java.util.stream.Collectors; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.linkingTo; -import static sonia.scm.api.v2.resources.ResourceLinks.group; -import static sonia.scm.api.v2.resources.ResourceLinks.user; // Mapstruct does not support parameterized (i.e. non-default) constructors. Thus, we need to use field injection. @SuppressWarnings("squid:S3306") @@ -22,16 +20,16 @@ import static sonia.scm.api.v2.resources.ResourceLinks.user; public abstract class GroupToGroupDtoMapper extends BaseMapper { @Inject - private UriInfoStore uriInfoStore; + private ResourceLinks resourceLinks; @AfterMapping void appendLinks(Group group, @MappingTarget GroupDto target) { - Links.Builder linksBuilder = linkingTo().self(group(uriInfoStore.get()).self(target.getName())); + Links.Builder linksBuilder = linkingTo().self(resourceLinks.group().self(target.getName())); if (GroupPermissions.delete(group).isPermitted()) { - linksBuilder.single(link("delete", group(uriInfoStore.get()).delete(target.getName()))); + linksBuilder.single(link("delete", resourceLinks.group().delete(target.getName()))); } if (GroupPermissions.modify(group).isPermitted()) { - linksBuilder.single(link("update", group(uriInfoStore.get()).update(target.getName()))); + linksBuilder.single(link("update", resourceLinks.group().update(target.getName()))); } target.add(linksBuilder.build()); } @@ -43,7 +41,7 @@ public abstract class GroupToGroupDtoMapper extends BaseMapper } private MemberDto createMember(String name) { - Links.Builder linksBuilder = linkingTo().self(user(uriInfoStore.get()).self(name)); + Links.Builder linksBuilder = linkingTo().self(resourceLinks.user().self(name)); MemberDto memberDto = new MemberDto(name); memberDto.add(linksBuilder.build()); return memberDto; diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/HealthCheckFailureDto.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/HealthCheckFailureDto.java new file mode 100644 index 0000000000..21d98c257c --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/HealthCheckFailureDto.java @@ -0,0 +1,11 @@ +package sonia.scm.api.v2.resources; + +import lombok.Getter; +import lombok.Setter; + +@Getter @Setter +public class HealthCheckFailureDto { + private String description; + private String summary; + private String url; +} diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/IdResourceManagerAdapter.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/IdResourceManagerAdapter.java new file mode 100644 index 0000000000..ded4bff309 --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/IdResourceManagerAdapter.java @@ -0,0 +1,66 @@ +package sonia.scm.api.v2.resources; + +import de.otto.edison.hal.HalRepresentation; +import sonia.scm.Manager; +import sonia.scm.ModelObject; +import sonia.scm.PageResult; + +import javax.ws.rs.core.Response; +import java.io.IOException; +import java.util.Optional; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; + +/** + * Facade for {@link SingleResourceManagerAdapter} and {@link CollectionResourceManagerAdapter} + * for model objects handled by a single id. + */ +@SuppressWarnings("squid:S00119") // "MODEL_OBJECT" is much more meaningful than "M", right? +class IdResourceManagerAdapter { + + private final Manager manager; + + private final SingleResourceManagerAdapter singleAdapter; + private final CollectionResourceManagerAdapter collectionAdapter; + + IdResourceManagerAdapter(Manager manager, Class type) { + this.manager = manager; + singleAdapter = new SingleResourceManagerAdapter<>(manager, type); + collectionAdapter = new CollectionResourceManagerAdapter<>(manager, type); + } + + Response get(String id, Function mapToDto) { + return singleAdapter.get(loadBy(id), mapToDto); + } + + public Response update(String id, Function applyChanges) { + return singleAdapter.update( + loadBy(id), + applyChanges, + idStaysTheSame(id) + ); + } + + public Response getAll(int page, int pageSize, String sortBy, boolean desc, Function, CollectionDto> mapToDto) { + return collectionAdapter.getAll(page, pageSize, sortBy, desc, mapToDto); + } + + public Response create(DTO dto, Supplier modelObjectSupplier, Function uriCreator) throws IOException, EXCEPTION { + return collectionAdapter.create(dto, modelObjectSupplier, uriCreator); + } + + public Response delete(String id) { + return singleAdapter.delete(id); + } + + private Supplier> loadBy(String id) { + return () -> Optional.ofNullable(manager.get(id)); + } + + private Predicate idStaysTheSame(String id) { + return changed -> changed.getId().equals(id); + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/MapperModule.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/MapperModule.java index fec2a677b5..8e22755fe0 100644 --- a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/MapperModule.java +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/MapperModule.java @@ -15,6 +15,9 @@ public class MapperModule extends AbstractModule { bind(GroupToGroupDtoMapper.class).to(Mappers.getMapper(GroupToGroupDtoMapper.class).getClass()); bind(GroupCollectionToDtoMapper.class); + bind(RepositoryToRepositoryDtoMapper.class).to(Mappers.getMapper(RepositoryToRepositoryDtoMapper.class).getClass()); + bind(RepositoryDtoToRepositoryMapper.class).to(Mappers.getMapper(RepositoryDtoToRepositoryMapper.class).getClass()); + bind(UriInfoStore.class).in(ServletScopes.REQUEST); } } diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/PermissionCollectionResource.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/PermissionCollectionResource.java new file mode 100644 index 0000000000..6c4b52c16d --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/PermissionCollectionResource.java @@ -0,0 +1,18 @@ +package sonia.scm.api.v2.resources; + +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; + +public class PermissionCollectionResource { + @GET + @Path("") + public Response getAll(@DefaultValue("0") @QueryParam("page") int page, + @DefaultValue("10") @QueryParam("pageSize") int pageSize, + @QueryParam("sortBy") String sortBy, + @DefaultValue("false") @QueryParam("desc") boolean desc) { + throw new UnsupportedOperationException(); + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/PermissionRootResource.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/PermissionRootResource.java new file mode 100644 index 0000000000..cd1e970e43 --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/PermissionRootResource.java @@ -0,0 +1,20 @@ +package sonia.scm.api.v2.resources; + +import javax.inject.Inject; +import javax.inject.Provider; +import javax.ws.rs.Path; + +public class PermissionRootResource { + + private final Provider permissionCollectionResource; + + @Inject + public PermissionRootResource(Provider permissionCollectionResource) { + this.permissionCollectionResource = permissionCollectionResource; + } + + @Path("") + public PermissionCollectionResource getPermissionCollectionResource() { + return permissionCollectionResource.get(); + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/RepositoryCollectionResource.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/RepositoryCollectionResource.java new file mode 100644 index 0000000000..7112e7113b --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/RepositoryCollectionResource.java @@ -0,0 +1,94 @@ +package sonia.scm.api.v2.resources; + +import com.webcohesion.enunciate.metadata.rs.ResponseCode; +import com.webcohesion.enunciate.metadata.rs.ResponseHeader; +import com.webcohesion.enunciate.metadata.rs.ResponseHeaders; +import com.webcohesion.enunciate.metadata.rs.StatusCodes; +import com.webcohesion.enunciate.metadata.rs.TypeHint; +import sonia.scm.repository.Repository; +import sonia.scm.repository.RepositoryException; +import sonia.scm.repository.RepositoryManager; +import sonia.scm.web.VndMediaType; + +import javax.inject.Inject; +import javax.ws.rs.Consumes; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; + +public class RepositoryCollectionResource { + + private static final int DEFAULT_PAGE_SIZE = 10; + + private final CollectionResourceManagerAdapter adapter; + private final RepositoryCollectionToDtoMapper repositoryCollectionToDtoMapper; + private final RepositoryDtoToRepositoryMapper dtoToRepositoryMapper; + private final ResourceLinks resourceLinks; + + @Inject + public RepositoryCollectionResource(RepositoryManager manager, RepositoryCollectionToDtoMapper repositoryCollectionToDtoMapper, RepositoryDtoToRepositoryMapper dtoToRepositoryMapper, ResourceLinks resourceLinks) { + this.adapter = new CollectionResourceManagerAdapter<>(manager, Repository.class); + this.repositoryCollectionToDtoMapper = repositoryCollectionToDtoMapper; + this.dtoToRepositoryMapper = dtoToRepositoryMapper; + this.resourceLinks = resourceLinks; + } + + /** + * Returns all repositories for a given page number with a given page size (default page size is {@value DEFAULT_PAGE_SIZE}). + * + * Note: This method requires "repository" privilege. + * + * @param page the number of the requested page + * @param pageSize the page size (default page size is {@value DEFAULT_PAGE_SIZE}) + * @param sortBy sort parameter (if empty - undefined sorting) + * @param desc sort direction desc or asc + */ + @GET + @Path("") + @Produces(VndMediaType.REPOSITORY_COLLECTION) + @TypeHint(RepositoryDto[].class) + @StatusCodes({ + @ResponseCode(code = 200, condition = "success"), + @ResponseCode(code = 401, condition = "not authenticated / invalid credentials"), + @ResponseCode(code = 403, condition = "not authorized, the current user does not have the \"repository\" privilege"), + @ResponseCode(code = 500, condition = "internal server error") + }) + public Response getAll(@DefaultValue("0") @QueryParam("page") int page, + @DefaultValue("" + DEFAULT_PAGE_SIZE) @QueryParam("pageSize") int pageSize, + @QueryParam("sortBy") String sortBy, + @DefaultValue("false") @QueryParam("desc") boolean desc) { + return adapter.getAll(page, pageSize, sortBy, desc, + pageResult -> repositoryCollectionToDtoMapper.map(page, pageSize, pageResult)); + } + + /** + * Creates a new repository. + * + * Note: This method requires "repository" privilege. The namespace of the given repository will + * be ignored and set by the configured namespace strategy. + * + * @param repositoryDto The repository to be created. + * @return A response with the link to the new repository (if created successfully). + */ + @POST + @Path("") + @Consumes(VndMediaType.REPOSITORY) + @StatusCodes({ + @ResponseCode(code = 201, condition = "create success"), + @ResponseCode(code = 401, condition = "not authenticated / invalid credentials"), + @ResponseCode(code = 403, condition = "not authorized, the current user does not have the \"repository\" privilege"), + @ResponseCode(code = 409, condition = "conflict, a repository with this name already exists"), + @ResponseCode(code = 500, condition = "internal server error") + }) + @TypeHint(TypeHint.NO_CONTENT.class) + @ResponseHeaders(@ResponseHeader(name = "Location", description = "uri to the created repository")) + public Response create(RepositoryDto repositoryDto) throws RepositoryException { + return adapter.create(repositoryDto, + () -> dtoToRepositoryMapper.map(repositoryDto, null), + repository -> resourceLinks.repository().self(repository.getNamespace(), repository.getName())); + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/RepositoryCollectionToDtoMapper.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/RepositoryCollectionToDtoMapper.java new file mode 100644 index 0000000000..a1cf0218e4 --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/RepositoryCollectionToDtoMapper.java @@ -0,0 +1,34 @@ +package sonia.scm.api.v2.resources; + +import sonia.scm.repository.Repository; +import sonia.scm.repository.RepositoryPermissions; + +import javax.inject.Inject; + +// Mapstruct does not support parameterized (i.e. non-default) constructors. Thus, we need to use field injection. +@SuppressWarnings("squid:S3306") +public class RepositoryCollectionToDtoMapper extends BasicCollectionToDtoMapper { + + private final ResourceLinks resourceLinks; + + @Inject + public RepositoryCollectionToDtoMapper(RepositoryToRepositoryDtoMapper repositoryToDtoMapper, ResourceLinks resourceLinks) { + super("repositories", repositoryToDtoMapper); + this.resourceLinks = resourceLinks; + } + + @Override + String createCreateLink() { + return resourceLinks.repositoryCollection().create(); + } + + @Override + String createSelfLink() { + return resourceLinks.repositoryCollection().self(); + } + + @Override + boolean isCreatePermitted() { + return RepositoryPermissions.create().isPermitted(); + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/RepositoryDto.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/RepositoryDto.java new file mode 100644 index 0000000000..bcc8e16ebb --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/RepositoryDto.java @@ -0,0 +1,33 @@ +package sonia.scm.api.v2.resources; + +import com.fasterxml.jackson.annotation.JsonInclude; +import de.otto.edison.hal.HalRepresentation; +import de.otto.edison.hal.Links; +import lombok.Getter; +import lombok.Setter; + +import java.time.Instant; +import java.util.List; +import java.util.Map; + +@Getter @Setter +public class RepositoryDto extends HalRepresentation { + + private String contact; + private Instant creationDate; + private String description; + private List healthCheckFailures; + @JsonInclude(JsonInclude.Include.NON_NULL) + private Instant lastModified; + private String namespace; + private String name; + private boolean archived = false; + private String type; + protected Map properties; + + @Override + @SuppressWarnings("squid:S1185") // We want to have this method available in this package + protected HalRepresentation add(Links links) { + return super.add(links); + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/RepositoryDtoToRepositoryMapper.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/RepositoryDtoToRepositoryMapper.java new file mode 100644 index 0000000000..2c02bb8180 --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/RepositoryDtoToRepositoryMapper.java @@ -0,0 +1,25 @@ +package sonia.scm.api.v2.resources; + +import org.mapstruct.AfterMapping; +import org.mapstruct.Context; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.MappingTarget; +import sonia.scm.repository.Repository; + +@Mapper +public abstract class RepositoryDtoToRepositoryMapper { + + @Mapping(target = "creationDate", ignore = true) + @Mapping(target = "lastModified", ignore = true) + @Mapping(target = "id", ignore = true) + @Mapping(target = "publicReadable", ignore = true) + @Mapping(target = "healthCheckFailures", ignore = true) + @Mapping(target = "permissions", ignore = true) + public abstract Repository map(RepositoryDto repositoryDto, @Context String id); + + @AfterMapping + void updateId(@MappingTarget Repository repository, @Context String id) { + repository.setId(id); + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/RepositoryResource.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/RepositoryResource.java new file mode 100644 index 0000000000..5972508c78 --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/RepositoryResource.java @@ -0,0 +1,164 @@ +package sonia.scm.api.v2.resources; + +import com.webcohesion.enunciate.metadata.rs.ResponseCode; +import com.webcohesion.enunciate.metadata.rs.StatusCodes; +import com.webcohesion.enunciate.metadata.rs.TypeHint; +import sonia.scm.repository.Repository; +import sonia.scm.repository.RepositoryException; +import sonia.scm.repository.RepositoryManager; +import sonia.scm.web.VndMediaType; + +import javax.inject.Inject; +import javax.inject.Provider; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.function.Supplier; + +public class RepositoryResource { + + private final RepositoryToRepositoryDtoMapper repositoryToDtoMapper; + private final RepositoryDtoToRepositoryMapper dtoToRepositoryMapper; + + private final RepositoryManager manager; + private final SingleResourceManagerAdapter adapter; + private final Provider tagRootResource; + private final Provider branchRootResource; + private final Provider changesetRootResource; + private final Provider sourceRootResource; + private final Provider permissionRootResource; + + @Inject + public RepositoryResource( + RepositoryToRepositoryDtoMapper repositoryToDtoMapper, + RepositoryDtoToRepositoryMapper dtoToRepositoryMapper, RepositoryManager manager, + Provider tagRootResource, + Provider branchRootResource, + Provider changesetRootResource, + Provider sourceRootResource, Provider permissionRootResource) { + this.dtoToRepositoryMapper = dtoToRepositoryMapper; + this.manager = manager; + this.repositoryToDtoMapper = repositoryToDtoMapper; + this.adapter = new SingleResourceManagerAdapter<>(manager, Repository.class); + this.tagRootResource = tagRootResource; + this.branchRootResource = branchRootResource; + this.changesetRootResource = changesetRootResource; + this.sourceRootResource = sourceRootResource; + this.permissionRootResource = permissionRootResource; + } + + /** + * Returns a repository. + * + * Note: This method requires "repository" privilege. + * + * @param namespace the namespace of the repository + * @param name the name of the repository + * + */ + @GET + @Path("") + @Produces(VndMediaType.REPOSITORY) + @TypeHint(RepositoryDto.class) + @StatusCodes({ + @ResponseCode(code = 200, condition = "success"), + @ResponseCode(code = 401, condition = "not authenticated / invalid credentials"), + @ResponseCode(code = 403, condition = "not authorized, the current user has no privileges to read the repository"), + @ResponseCode(code = 404, condition = "not found, no repository with the specified name available in the namespace"), + @ResponseCode(code = 500, condition = "internal server error") + }) + public Response get(@PathParam("namespace") String namespace, @PathParam("name") String name) { + return adapter.get(loadBy(namespace, name), repositoryToDtoMapper::map); + } + + /** + * Deletes a repository. + * + * Note: This method requires "repository" privilege. + * + * @param namespace the namespace of the repository to delete + * @param name the name of the repository to delete + * + */ + @DELETE + @Path("") + @StatusCodes({ + @ResponseCode(code = 204, condition = "delete success or nothing to delete"), + @ResponseCode(code = 401, condition = "not authenticated / invalid credentials"), + @ResponseCode(code = 403, condition = "not authorized, the current user does not have the \"repository\" privilege"), + @ResponseCode(code = 500, condition = "internal server error") + }) + @TypeHint(TypeHint.NO_CONTENT.class) + public Response delete(@PathParam("namespace") String namespace, @PathParam("name") String name) { + return adapter.delete(loadBy(namespace, name)); + } + + /** + * Modifies the given repository. + * + * Note: This method requires "repository" privilege. + * + * @param namespace the namespace of the repository to be modified + * @param name the name of the repository to be modified + * @param repositoryDto repository object to modify + */ + @PUT + @Path("") + @Consumes(VndMediaType.REPOSITORY) + @StatusCodes({ + @ResponseCode(code = 204, condition = "update success"), + @ResponseCode(code = 400, condition = "Invalid body, e.g. illegal change of namespace or name"), + @ResponseCode(code = 401, condition = "not authenticated / invalid credentials"), + @ResponseCode(code = 403, condition = "not authorized, the current user does not have the \"repository\" privilege"), + @ResponseCode(code = 404, condition = "not found, no repository with the specified namespace and name available"), + @ResponseCode(code = 500, condition = "internal server error") + }) + @TypeHint(TypeHint.NO_CONTENT.class) + public Response update(@PathParam("namespace") String namespace, @PathParam("name") String name, RepositoryDto repositoryDto) { + return adapter.update( + loadBy(namespace, name), + existing -> dtoToRepositoryMapper.map(repositoryDto, existing.getId()), + nameAndNamespaceStaysTheSame(namespace, name) + ); + } + + @Path("tags/") + public TagRootResource tags() { + return tagRootResource.get(); + } + + @Path("branches/") + public BranchRootResource branches() { + return branchRootResource.get(); + } + + @Path("changesets/") + public ChangesetRootResource changesets() { + return changesetRootResource.get(); + } + + @Path("sources/") + public SourceRootResource sources() { + return sourceRootResource.get(); + } + + @Path("permissions/") + public PermissionRootResource permissions() { + return permissionRootResource.get(); + } + + private Supplier> loadBy(String namespace, String name) { + return () -> manager.getByNamespace(namespace, name); + } + + private Predicate nameAndNamespaceStaysTheSame(String namespace, String name) { + return changed -> changed.getName().equals(name) && changed.getNamespace().equals(namespace); + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/RepositoryRootResource.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/RepositoryRootResource.java new file mode 100644 index 0000000000..a7a6365c37 --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/RepositoryRootResource.java @@ -0,0 +1,32 @@ +package sonia.scm.api.v2.resources; + +import javax.inject.Inject; +import javax.inject.Provider; +import javax.ws.rs.Path; + +/** + * RESTful Web Service Resource to manage repositories. + */ +@Path(RepositoryRootResource.REPOSITORIES_PATH_V2) +public class RepositoryRootResource { + static final String REPOSITORIES_PATH_V2 = "v2/repositories/"; + + private final Provider repositoryResource; + private final Provider repositoryCollectionResource; + + @Inject + public RepositoryRootResource(Provider repositoryResource, Provider repositoryCollectionResource) { + this.repositoryResource = repositoryResource; + this.repositoryCollectionResource = repositoryCollectionResource; + } + + @Path("{namespace}/{name}") + public RepositoryResource getRepositoryResource() { + return repositoryResource.get(); + } + + @Path("") + public RepositoryCollectionResource getRepositoryCollectionResource() { + return repositoryCollectionResource.get(); + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/RepositoryToRepositoryDtoMapper.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/RepositoryToRepositoryDtoMapper.java new file mode 100644 index 0000000000..2f13723d39 --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/RepositoryToRepositoryDtoMapper.java @@ -0,0 +1,41 @@ +package sonia.scm.api.v2.resources; + +import com.google.inject.Inject; +import de.otto.edison.hal.Links; +import org.mapstruct.AfterMapping; +import org.mapstruct.Mapper; +import org.mapstruct.MappingTarget; +import sonia.scm.repository.HealthCheckFailure; +import sonia.scm.repository.Repository; +import sonia.scm.repository.RepositoryPermissions; + +import static de.otto.edison.hal.Link.link; +import static de.otto.edison.hal.Links.linkingTo; + +// Mapstruct does not support parameterized (i.e. non-default) constructors. Thus, we need to use field injection. +@SuppressWarnings("squid:S3306") +@Mapper +public abstract class RepositoryToRepositoryDtoMapper extends BaseMapper { + + @Inject + private ResourceLinks resourceLinks; + + abstract HealthCheckFailureDto toDto(HealthCheckFailure failure); + + @AfterMapping + void appendLinks(Repository repository, @MappingTarget RepositoryDto target) { + Links.Builder linksBuilder = linkingTo().self(resourceLinks.repository().self(target.getNamespace(), target.getName())); + if (RepositoryPermissions.delete(repository).isPermitted()) { + linksBuilder.single(link("delete", resourceLinks.repository().delete(target.getNamespace(), target.getName()))); + } + if (RepositoryPermissions.modify(repository).isPermitted()) { + linksBuilder.single(link("update", resourceLinks.repository().update(target.getNamespace(), target.getName()))); + linksBuilder.single(link("permissions", resourceLinks.permissionCollection().self(target.getNamespace(), target.getName()))); + } + linksBuilder.single(link("tags", resourceLinks.tagCollection().self(target.getNamespace(), target.getName()))); + linksBuilder.single(link("branches", resourceLinks.branchCollection().self(target.getNamespace(), target.getName()))); + linksBuilder.single(link("changesets", resourceLinks.changesetCollection().self(target.getNamespace(), target.getName()))); + linksBuilder.single(link("sources", resourceLinks.sourceCollection().self(target.getNamespace(), target.getName()))); + target.add(linksBuilder.build()); + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/ResourceLinks.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/ResourceLinks.java index 351c9c7f55..8f6f1eaae3 100644 --- a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/ResourceLinks.java +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/ResourceLinks.java @@ -1,20 +1,26 @@ package sonia.scm.api.v2.resources; +import javax.inject.Inject; import javax.ws.rs.core.UriInfo; class ResourceLinks { - private ResourceLinks() { + private final UriInfoStore uriInfoStore; + + @Inject + ResourceLinks(UriInfoStore uriInfoStore) { + this.uriInfoStore = uriInfoStore; } - static GroupLinks group(UriInfo uriInfo) { - return new GroupLinks(uriInfo); + + GroupLinks group() { + return new GroupLinks(uriInfoStore.get()); } static class GroupLinks { private final LinkBuilder groupLinkBuilder; - private GroupLinks(UriInfo uriInfo) { + GroupLinks(UriInfo uriInfo) { groupLinkBuilder = new LinkBuilder(uriInfo, GroupRootResource.class, GroupResource.class); } @@ -31,14 +37,14 @@ class ResourceLinks { } } - static GroupCollectionLinks groupCollection(UriInfo uriInfo) { - return new GroupCollectionLinks(uriInfo); + GroupCollectionLinks groupCollection() { + return new GroupCollectionLinks(uriInfoStore.get()); } static class GroupCollectionLinks { private final LinkBuilder collectionLinkBuilder; - private GroupCollectionLinks(UriInfo uriInfo) { + GroupCollectionLinks(UriInfo uriInfo) { collectionLinkBuilder = new LinkBuilder(uriInfo, GroupRootResource.class, GroupCollectionResource.class); } @@ -51,14 +57,14 @@ class ResourceLinks { } } - static UserLinks user(UriInfo uriInfo) { - return new UserLinks(uriInfo); + UserLinks user() { + return new UserLinks(uriInfoStore.get()); } static class UserLinks { private final LinkBuilder userLinkBuilder; - private UserLinks(UriInfo uriInfo) { + UserLinks(UriInfo uriInfo) { userLinkBuilder = new LinkBuilder(uriInfo, UserRootResource.class, UserResource.class); } @@ -75,14 +81,14 @@ class ResourceLinks { } } - static UserCollectionLinks userCollection(UriInfo uriInfo) { - return new UserCollectionLinks(uriInfo); + UserCollectionLinks userCollection() { + return new UserCollectionLinks(uriInfoStore.get()); } static class UserCollectionLinks { private final LinkBuilder collectionLinkBuilder; - private UserCollectionLinks(UriInfo uriInfo) { + UserCollectionLinks(UriInfo uriInfo) { collectionLinkBuilder = new LinkBuilder(uriInfo, UserRootResource.class, UserCollectionResource.class); } @@ -94,4 +100,128 @@ class ResourceLinks { return collectionLinkBuilder.method("getUserCollectionResource").parameters().method("create").parameters().href(); } } + + public RepositoryLinks repository() { + return new RepositoryLinks(uriInfoStore.get()); + } + + static class RepositoryLinks { + private final LinkBuilder repositoryLinkBuilder; + + RepositoryLinks(UriInfo uriInfo) { + repositoryLinkBuilder = new LinkBuilder(uriInfo, RepositoryRootResource.class, RepositoryResource.class); + } + + String self(String namespace, String name) { + return repositoryLinkBuilder.method("getRepositoryResource").parameters(namespace, name).method("get").parameters().href(); + } + + String delete(String namespace, String name) { + return repositoryLinkBuilder.method("getRepositoryResource").parameters(namespace, name).method("delete").parameters().href(); + } + + String update(String namespace, String name) { + return repositoryLinkBuilder.method("getRepositoryResource").parameters(namespace, name).method("update").parameters().href(); + } + } + + RepositoryCollectionLinks repositoryCollection() { + return new RepositoryCollectionLinks(uriInfoStore.get()); + } + + static class RepositoryCollectionLinks { + private final LinkBuilder collectionLinkBuilder; + + RepositoryCollectionLinks(UriInfo uriInfo) { + collectionLinkBuilder = new LinkBuilder(uriInfo, RepositoryRootResource.class, RepositoryCollectionResource.class); + } + + String self() { + return collectionLinkBuilder.method("getRepositoryCollectionResource").parameters().method("getAll").parameters().href(); + } + + String create() { + return collectionLinkBuilder.method("getRepositoryCollectionResource").parameters().method("create").parameters().href(); + } + } + + public TagCollectionLinks tagCollection() { + return new TagCollectionLinks(uriInfoStore.get()); + } + + static class TagCollectionLinks { + private final LinkBuilder tagLinkBuilder; + + TagCollectionLinks(UriInfo uriInfo) { + tagLinkBuilder = new LinkBuilder(uriInfo, RepositoryRootResource.class, RepositoryResource.class, TagRootResource.class, TagCollectionResource.class); + } + + String self(String namespace, String name) { + return tagLinkBuilder.method("getRepositoryResource").parameters(namespace, name).method("tags").parameters().method("getTagCollectionResource").parameters().method("getAll").parameters().href(); + } + } + + public BranchCollectionLinks branchCollection() { + return new BranchCollectionLinks(uriInfoStore.get()); + } + + static class BranchCollectionLinks { + private final LinkBuilder branchLinkBuilder; + + BranchCollectionLinks(UriInfo uriInfo) { + branchLinkBuilder = new LinkBuilder(uriInfo, RepositoryRootResource.class, RepositoryResource.class, BranchRootResource.class, BranchCollectionResource.class); + } + + String self(String namespace, String name) { + return branchLinkBuilder.method("getRepositoryResource").parameters(namespace, name).method("branches").parameters().method("getBranchCollectionResource").parameters().method("getAll").parameters().href(); + } + } + + public ChangesetCollectionLinks changesetCollection() { + return new ChangesetCollectionLinks(uriInfoStore.get()); + } + + static class ChangesetCollectionLinks { + private final LinkBuilder changesetLinkBuilder; + + ChangesetCollectionLinks(UriInfo uriInfo) { + changesetLinkBuilder = new LinkBuilder(uriInfo, RepositoryRootResource.class, RepositoryResource.class, ChangesetRootResource.class, ChangesetCollectionResource.class); + } + + String self(String namespace, String name) { + return changesetLinkBuilder.method("getRepositoryResource").parameters(namespace, name).method("changesets").parameters().method("getChangesetCollectionResource").parameters().method("getAll").parameters().href(); + } + } + + public SourceCollectionLinks sourceCollection() { + return new SourceCollectionLinks(uriInfoStore.get()); + } + + static class SourceCollectionLinks { + private final LinkBuilder sourceLinkBuilder; + + SourceCollectionLinks(UriInfo uriInfo) { + sourceLinkBuilder = new LinkBuilder(uriInfo, RepositoryRootResource.class, RepositoryResource.class, SourceRootResource.class, SourceCollectionResource.class); + } + + String self(String namespace, String name) { + return sourceLinkBuilder.method("getRepositoryResource").parameters(namespace, name).method("sources").parameters().method("getSourceCollectionResource").parameters().method("getAll").parameters().href(); + } + } + + public PermissionCollectionLinks permissionCollection() { + return new PermissionCollectionLinks(uriInfoStore.get()); + } + + static class PermissionCollectionLinks { + private final LinkBuilder permissionLinkBuilder; + + PermissionCollectionLinks(UriInfo uriInfo) { + permissionLinkBuilder = new LinkBuilder(uriInfo, RepositoryRootResource.class, RepositoryResource.class, PermissionRootResource.class, PermissionCollectionResource.class); + } + + String self(String namespace, String name) { + return permissionLinkBuilder.method("getRepositoryResource").parameters(namespace, name).method("permissions").parameters().method("getPermissionCollectionResource").parameters().method("getAll").parameters().href(); + } + } } diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/SingleResourceManagerAdapter.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/SingleResourceManagerAdapter.java new file mode 100644 index 0000000000..7f8b115dee --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/SingleResourceManagerAdapter.java @@ -0,0 +1,87 @@ +package sonia.scm.api.v2.resources; + +import de.otto.edison.hal.HalRepresentation; +import sonia.scm.Manager; +import sonia.scm.ModelObject; +import sonia.scm.api.rest.resources.AbstractManagerResource; + +import javax.ws.rs.core.GenericEntity; +import javax.ws.rs.core.Response; +import java.util.Collection; +import java.util.Optional; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; + +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; + +/** + * Adapter from resource http endpoints to managers, for Single resources (e.g. {@code /user/name}). + * + * Provides common CRUD operations and DTO to Model Object mapping to keep Resources more DRY. + * + * @param The type of the model object, eg. {@link sonia.scm.user.User}. + * @param The corresponding transport object, eg. {@link UserDto}. + * @param The exception type for the model object, eg. {@link sonia.scm.user.UserException}. + * + * @see CollectionResourceManagerAdapter + */ +@SuppressWarnings("squid:S00119") // "MODEL_OBJECT" is much more meaningful than "M", right? +class SingleResourceManagerAdapter extends AbstractManagerResource { + + SingleResourceManagerAdapter(Manager manager, Class type) { + super(manager, type); + } + + /** + * Reads the model object for the given id, transforms it to a dto and returns a corresponding http response. + * This handles all corner cases, eg. no matching object for the id or missing privileges. + */ + Response get(Supplier> reader, Function mapToDto) { + return reader.get() + .map(mapToDto) + .map(Response::ok) + .map(Response.ResponseBuilder::build) + .orElse(Response.status(Response.Status.NOT_FOUND).build()); + } + + /** + * Update the model object for the given id according to the given function and returns a corresponding http response. + * This handles all corner cases, eg. no matching object for the id or missing privileges. + */ + public Response update(Supplier> reader, Function applyChanges, Predicate hasSameKey) { + Optional existingModelObject = reader.get(); + if (!existingModelObject.isPresent()) { + return Response.status(Response.Status.NOT_FOUND).build(); + } + MODEL_OBJECT changedModelObject = applyChanges.apply(existingModelObject.get()); + if (!hasSameKey.test(changedModelObject)) { + return Response.status(BAD_REQUEST).entity("illegal change of id").build(); + } + return update(getId(existingModelObject.get()), changedModelObject); + } + + public Response delete(Supplier> reader) { + return reader.get() + .map(MODEL_OBJECT::getId) + .map(this::delete) + .orElse(null); + } + + @Override + protected GenericEntity> createGenericEntity(Collection modelObjects) { + throw new UnsupportedOperationException(); + } + + @Override + protected String getId(MODEL_OBJECT item) { + return item.getId(); + } + + @Override + protected String getPathPart() { + throw new UnsupportedOperationException(); + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/SourceCollectionResource.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/SourceCollectionResource.java new file mode 100644 index 0000000000..d3f00a0b51 --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/SourceCollectionResource.java @@ -0,0 +1,18 @@ +package sonia.scm.api.v2.resources; + +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; + +public class SourceCollectionResource { + @GET + @Path("") + public Response getAll(@DefaultValue("0") @QueryParam("page") int page, + @DefaultValue("10") @QueryParam("pageSize") int pageSize, + @QueryParam("sortBy") String sortBy, + @DefaultValue("false") @QueryParam("desc") boolean desc) { + throw new UnsupportedOperationException(); + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/SourceRootResource.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/SourceRootResource.java new file mode 100644 index 0000000000..f58cbb6dff --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/SourceRootResource.java @@ -0,0 +1,20 @@ +package sonia.scm.api.v2.resources; + +import javax.inject.Inject; +import javax.inject.Provider; +import javax.ws.rs.Path; + +public class SourceRootResource { + + private final Provider sourceCollectionResource; + + @Inject + public SourceRootResource(Provider sourceCollectionResource) { + this.sourceCollectionResource = sourceCollectionResource; + } + + @Path("") + public SourceCollectionResource getSourceCollectionResource() { + return sourceCollectionResource.get(); + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/TagCollectionResource.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/TagCollectionResource.java new file mode 100644 index 0000000000..3dbba0cb0e --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/TagCollectionResource.java @@ -0,0 +1,18 @@ +package sonia.scm.api.v2.resources; + +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; + +public class TagCollectionResource { + @GET + @Path("") + public Response getAll(@DefaultValue("0") @QueryParam("page") int page, + @DefaultValue("10") @QueryParam("pageSize") int pageSize, + @QueryParam("sortBy") String sortBy, + @DefaultValue("false") @QueryParam("desc") boolean desc) { + throw new UnsupportedOperationException(); + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/TagRootResource.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/TagRootResource.java new file mode 100644 index 0000000000..29a2a922ca --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/TagRootResource.java @@ -0,0 +1,20 @@ +package sonia.scm.api.v2.resources; + +import javax.inject.Inject; +import javax.inject.Provider; +import javax.ws.rs.Path; + +public class TagRootResource { + + private final Provider tagCollectionResource; + + @Inject + public TagRootResource(Provider tagCollectionResource) { + this.tagCollectionResource = tagCollectionResource; + } + + @Path("") + public TagCollectionResource getTagCollectionResource() { + return tagCollectionResource.get(); + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/UserCollectionResource.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/UserCollectionResource.java index da1cd6e2f1..578361424c 100644 --- a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/UserCollectionResource.java +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/UserCollectionResource.java @@ -18,28 +18,25 @@ import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; import java.io.IOException; -import static sonia.scm.api.v2.resources.ResourceLinks.user; - public class UserCollectionResource { private static final int DEFAULT_PAGE_SIZE = 10; private final UserDtoToUserMapper dtoToUserMapper; private final UserCollectionToDtoMapper userCollectionToDtoMapper; + private final ResourceLinks resourceLinks; - private final ResourceManagerAdapter adapter; + private final IdResourceManagerAdapter adapter; @Inject public UserCollectionResource(UserManager manager, UserDtoToUserMapper dtoToUserMapper, - UserCollectionToDtoMapper userCollectionToDtoMapper) { + UserCollectionToDtoMapper userCollectionToDtoMapper, ResourceLinks resourceLinks) { this.dtoToUserMapper = dtoToUserMapper; this.userCollectionToDtoMapper = userCollectionToDtoMapper; - this.adapter = new ResourceManagerAdapter<>(manager); + this.adapter = new IdResourceManagerAdapter<>(manager, User.class); + this.resourceLinks = resourceLinks; } /** @@ -47,10 +44,9 @@ public class UserCollectionResource { * * Note: This method requires "user" privilege. * - * @param request the current request * @param page the number of the requested page * @param pageSize the page size (default page size is {@value DEFAULT_PAGE_SIZE}) - * @param sortBy sort parameter + * @param sortBy sort parameter (if empty - undefined sorting) * @param desc sort direction desc or asc */ @GET @@ -59,14 +55,14 @@ public class UserCollectionResource { @TypeHint(UserDto[].class) @StatusCodes({ @ResponseCode(code = 200, condition = "success"), + @ResponseCode(code = 400, condition = "\"sortBy\" field unknown"), @ResponseCode(code = 401, condition = "not authenticated / invalid credentials"), @ResponseCode(code = 403, condition = "not authorized, the current user does not have the \"user\" privilege"), @ResponseCode(code = 500, condition = "internal server error") }) - public Response getAll(@Context Request request, - @DefaultValue("0") @QueryParam("page") int page, + public Response getAll(@DefaultValue("0") @QueryParam("page") int page, @DefaultValue("" + DEFAULT_PAGE_SIZE) @QueryParam("pageSize") int pageSize, - @QueryParam("sortby") String sortBy, + @QueryParam("sortBy") String sortBy, @DefaultValue("false") @QueryParam("desc") boolean desc) { return adapter.getAll(page, pageSize, sortBy, desc, pageResult -> userCollectionToDtoMapper.map(page, pageSize, pageResult)); @@ -92,9 +88,9 @@ public class UserCollectionResource { }) @TypeHint(TypeHint.NO_CONTENT.class) @ResponseHeaders(@ResponseHeader(name = "Location", description = "uri to the created user")) - public Response create(@Context UriInfo uriInfo, UserDto userDto) throws IOException, UserException { + public Response create(UserDto userDto) throws IOException, UserException { return adapter.create(userDto, () -> dtoToUserMapper.map(userDto, ""), - user -> user(uriInfo).self(user.getName())); + user -> resourceLinks.user().self(user.getName())); } } diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/UserCollectionToDtoMapper.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/UserCollectionToDtoMapper.java index 34f26332f1..db2a9afc9f 100644 --- a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/UserCollectionToDtoMapper.java +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/UserCollectionToDtoMapper.java @@ -5,28 +5,26 @@ import sonia.scm.user.UserPermissions; import javax.inject.Inject; -import static sonia.scm.api.v2.resources.ResourceLinks.userCollection; - // Mapstruct does not support parameterized (i.e. non-default) constructors. Thus, we need to use field injection. @SuppressWarnings("squid:S3306") public class UserCollectionToDtoMapper extends BasicCollectionToDtoMapper { - private final UriInfoStore uriInfoStore; + private final ResourceLinks resourceLinks; @Inject - public UserCollectionToDtoMapper(UserToUserDtoMapper userToDtoMapper, UriInfoStore uriInfoStore) { + public UserCollectionToDtoMapper(UserToUserDtoMapper userToDtoMapper, ResourceLinks resourceLinks) { super("users", userToDtoMapper); - this.uriInfoStore = uriInfoStore; + this.resourceLinks = resourceLinks; } @Override String createCreateLink() { - return userCollection(uriInfoStore.get()).create(); + return resourceLinks.userCollection().create(); } @Override String createSelfLink() { - return userCollection(uriInfoStore.get()).self(); + return resourceLinks.userCollection().self(); } @Override diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/UserDto.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/UserDto.java index d87f4a74f1..cf7bf90504 100644 --- a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/UserDto.java +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/UserDto.java @@ -9,7 +9,6 @@ import lombok.Setter; import java.time.Instant; import java.util.Map; -import java.util.Optional; @NoArgsConstructor @Getter @Setter public class UserDto extends HalRepresentation { @@ -17,8 +16,8 @@ public class UserDto extends HalRepresentation { private boolean admin; private Instant creationDate; private String displayName; - @JsonInclude(JsonInclude.Include.NON_EMPTY) - private Optional lastModified; + @JsonInclude(JsonInclude.Include.NON_NULL) + private Instant lastModified; private String mail; private String name; private String password; diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/UserResource.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/UserResource.java index f1d9596b3e..2dc070d815 100644 --- a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/UserResource.java +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/UserResource.java @@ -16,23 +16,20 @@ import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; public class UserResource { private final UserDtoToUserMapper dtoToUserMapper; private final UserToUserDtoMapper userToDtoMapper; - private final ResourceManagerAdapter adapter; + private final IdResourceManagerAdapter adapter; @Inject public UserResource(UserDtoToUserMapper dtoToUserMapper, UserToUserDtoMapper userToDtoMapper, UserManager manager) { this.dtoToUserMapper = dtoToUserMapper; this.userToDtoMapper = userToDtoMapper; - this.adapter = new ResourceManagerAdapter<>(manager); + this.adapter = new IdResourceManagerAdapter<>(manager, User.class); } /** @@ -40,7 +37,6 @@ public class UserResource { * * Note: This method requires "user" privilege. * - * @param request the current request * @param id the id/name of the user * */ @@ -55,7 +51,7 @@ public class UserResource { @ResponseCode(code = 404, condition = "not found, no user with the specified id/name available"), @ResponseCode(code = 500, condition = "internal server error") }) - public Response get(@Context Request request, @Context UriInfo uriInfo, @PathParam("id") String id) { + public Response get(@PathParam("id") String id) { return adapter.get(id, userToDtoMapper::map); } @@ -93,13 +89,14 @@ public class UserResource { @Consumes(VndMediaType.USER) @StatusCodes({ @ResponseCode(code = 204, condition = "update success"), + @ResponseCode(code = 400, condition = "Invalid body, e.g. illegal change of id/user name"), @ResponseCode(code = 401, condition = "not authenticated / invalid credentials"), @ResponseCode(code = 403, condition = "not authorized, the current user does not have the \"user\" privilege"), @ResponseCode(code = 404, condition = "not found, no user with the specified id/name available"), @ResponseCode(code = 500, condition = "internal server error") }) @TypeHint(TypeHint.NO_CONTENT.class) - public Response update(@Context UriInfo uriInfo, @PathParam("id") String name, UserDto userDto) { + public Response update(@PathParam("id") String name, UserDto userDto) { return adapter.update(name, existing -> dtoToUserMapper.map(userDto, existing.getPassword())); } } diff --git a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/UserToUserDtoMapper.java b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/UserToUserDtoMapper.java index 194c44acaa..85973bab75 100644 --- a/scm-webapp/src/main/java/sonia/scm/api/v2/resources/UserToUserDtoMapper.java +++ b/scm-webapp/src/main/java/sonia/scm/api/v2/resources/UserToUserDtoMapper.java @@ -12,7 +12,6 @@ import javax.inject.Inject; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.linkingTo; -import static sonia.scm.api.v2.resources.ResourceLinks.user; // Mapstruct does not support parameterized (i.e. non-default) constructors. Thus, we need to use field injection. @SuppressWarnings("squid:S3306") @@ -20,7 +19,7 @@ import static sonia.scm.api.v2.resources.ResourceLinks.user; public abstract class UserToUserDtoMapper extends BaseMapper { @Inject - private UriInfoStore uriInfoStore; + private ResourceLinks resourceLinks; @AfterMapping void removePassword(@MappingTarget UserDto target) { @@ -29,13 +28,14 @@ public abstract class UserToUserDtoMapper extends BaseMapper { @AfterMapping void appendLinks(User user, @MappingTarget UserDto target) { - Links.Builder linksBuilder = linkingTo().self(user(uriInfoStore.get()).self(target.getName())); + Links.Builder linksBuilder = linkingTo().self(resourceLinks.user().self(target.getName())); if (UserPermissions.delete(user).isPermitted()) { - linksBuilder.single(link("delete", user(uriInfoStore.get()).delete(target.getName()))); + linksBuilder.single(link("delete", resourceLinks.user().delete(target.getName()))); } if (UserPermissions.modify(user).isPermitted()) { - linksBuilder.single(link("update", user(uriInfoStore.get()).update(target.getName()))); + linksBuilder.single(link("update", resourceLinks.user().update(target.getName()))); } target.add(linksBuilder.build()); } + } diff --git a/scm-webapp/src/main/java/sonia/scm/group/DefaultGroupManager.java b/scm-webapp/src/main/java/sonia/scm/group/DefaultGroupManager.java index b4e9df2430..4f39fd3196 100644 --- a/scm-webapp/src/main/java/sonia/scm/group/DefaultGroupManager.java +++ b/scm-webapp/src/main/java/sonia/scm/group/DefaultGroupManager.java @@ -43,6 +43,7 @@ import com.google.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sonia.scm.HandlerEventType; +import sonia.scm.ManagerDaoAdapter; import sonia.scm.SCMContextProvider; import sonia.scm.TransformFilter; import sonia.scm.search.SearchRequest; @@ -51,7 +52,12 @@ import sonia.scm.util.CollectionAppender; import sonia.scm.util.Util; import java.io.IOException; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedList; +import java.util.List; //~--- JDK imports ------------------------------------------------------------ @@ -79,6 +85,10 @@ public class DefaultGroupManager extends AbstractGroupManager public DefaultGroupManager(GroupDAO groupDAO) { this.groupDAO = groupDAO; + this.managerDaoAdapter = new ManagerDaoAdapter<>( + groupDAO, + GroupNotFoundException::new, + GroupAlreadyExistsException::new); } //~--- methods -------------------------------------------------------------- @@ -96,78 +106,34 @@ public class DefaultGroupManager extends AbstractGroupManager // do nothing } - /** - * Method description - * - * - * @param group - * - * @throws GroupException - * @throws IOException - */ @Override - public void create(Group group) throws GroupException, IOException - { + public Group create(Group group) throws GroupException { String type = group.getType(); - - if (Util.isEmpty(type)) - { + if (Util.isEmpty(type)) { group.setType(groupDAO.getType()); } - String name = group.getName(); - - if (logger.isInfoEnabled()) - { - logger.info("create group {} of type {}", name, - group.getType()); - } - - GroupPermissions.create().check(); - - if (groupDAO.contains(name)) - { - throw new GroupAlreadyExistsException(name.concat(" group already exists")); - } + logger.info("create group {} of type {}", group.getName(), group.getType()); removeDuplicateMembers(group); - group.setCreationDate(System.currentTimeMillis()); - fireEvent(HandlerEventType.BEFORE_CREATE, group); - groupDAO.add(group); - fireEvent(HandlerEventType.CREATE, group); + + return managerDaoAdapter.create( + group, + GroupPermissions::create, + newGroup -> fireEvent(HandlerEventType.BEFORE_CREATE, newGroup), + newGroup -> fireEvent(HandlerEventType.CREATE, newGroup) + ); } - /** - * Method description - * - * - * @param group - * - * @throws GroupException - * @throws IOException - */ @Override - public void delete(Group group) throws GroupException, IOException - { - if (logger.isInfoEnabled()) - { - logger.info("delete group {} of type {}", group.getName(), - group.getType()); - } - - String name = group.getName(); - GroupPermissions.delete().check(name); - - if (groupDAO.contains(name)) - { - fireEvent(HandlerEventType.BEFORE_DELETE, group); - groupDAO.delete(group); - fireEvent(HandlerEventType.DELETE, group); - } - else - { - throw new GroupNotFoundException("user does not exists"); - } + public void delete(Group group) throws GroupException { + logger.info("delete group {} of type {}", group.getName(), group.getType()); + managerDaoAdapter.delete( + group, + () -> GroupPermissions.delete(group.getName()), + toDelete -> fireEvent(HandlerEventType.BEFORE_DELETE, toDelete), + toDelete -> fireEvent(HandlerEventType.DELETE, toDelete) + ); } /** @@ -189,31 +155,18 @@ public class DefaultGroupManager extends AbstractGroupManager * @throws IOException */ @Override - public void modify(Group group) throws GroupException, IOException - { - if (logger.isInfoEnabled()) - { - logger.info("modify group {} of type {}", group.getName(), - group.getType()); - } + public void modify(Group group) throws GroupException { + logger.info("modify group {} of type {}", group.getName(), group.getType()); - String name = group.getName(); - GroupPermissions.modify().check(name); - - Group notModified = groupDAO.get(name); - if (notModified != null) - { - removeDuplicateMembers(group); - fireEvent(HandlerEventType.BEFORE_MODIFY, group, notModified); - group.setLastModified(System.currentTimeMillis()); - group.setCreationDate(notModified.getCreationDate()); - groupDAO.modify(group); - fireEvent(HandlerEventType.MODIFY, group, notModified); - } - else - { - throw new GroupNotFoundException("group does not exists"); - } + managerDaoAdapter.modify( + group, + GroupPermissions::modify, + notModified -> { + removeDuplicateMembers(group); + fireEvent(HandlerEventType.BEFORE_MODIFY, group, notModified); + }, + notModified -> fireEvent(HandlerEventType.MODIFY, group, notModified) + ); } /** @@ -226,7 +179,7 @@ public class DefaultGroupManager extends AbstractGroupManager * @throws IOException */ @Override - public void refresh(Group group) throws GroupException, IOException + public void refresh(Group group) throws GroupException { String name = group.getName(); if (logger.isInfoEnabled()) @@ -239,7 +192,7 @@ public class DefaultGroupManager extends AbstractGroupManager if (fresh == null) { - throw new GroupNotFoundException("group does not exists"); + throw new GroupNotFoundException(group); } fresh.copyProperties(group); @@ -452,4 +405,5 @@ public class DefaultGroupManager extends AbstractGroupManager /** Field description */ private GroupDAO groupDAO; + private final ManagerDaoAdapter managerDaoAdapter; } diff --git a/scm-webapp/src/main/java/sonia/scm/repository/DefaultNamespaceStrategy.java b/scm-webapp/src/main/java/sonia/scm/repository/DefaultNamespaceStrategy.java new file mode 100644 index 0000000000..9cf2c8ab20 --- /dev/null +++ b/scm-webapp/src/main/java/sonia/scm/repository/DefaultNamespaceStrategy.java @@ -0,0 +1,17 @@ +package sonia.scm.repository; + +import org.apache.shiro.SecurityUtils; +import sonia.scm.plugin.Extension; + +/** + * The DefaultNamespaceStrategy returns the username of the currently logged in user as namespace. + * @since 2.0.0 + */ +@Extension +public class DefaultNamespaceStrategy implements NamespaceStrategy { + + @Override + public String getNamespace() { + return SecurityUtils.getSubject().getPrincipal().toString(); + } +} diff --git a/scm-webapp/src/main/java/sonia/scm/repository/DefaultRepositoryManager.java b/scm-webapp/src/main/java/sonia/scm/repository/DefaultRepositoryManager.java index 8ddb02d9ca..ad6de93b0a 100644 --- a/scm-webapp/src/main/java/sonia/scm/repository/DefaultRepositoryManager.java +++ b/scm-webapp/src/main/java/sonia/scm/repository/DefaultRepositoryManager.java @@ -1,19 +1,19 @@ /** * Copyright (c) 2010, Sebastian Sdorra * All rights reserved. - * + *

* Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + *

* 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. + * this list of conditions and the following disclaimer. * 2. 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. + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. * 3. Neither the name of SCM-Manager; nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * + * 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 @@ -24,13 +24,11 @@ * 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. - * + *

* http://bitbucket.org/sdorra/scm-manager - * */ - package sonia.scm.repository; //~--- non-JDK imports -------------------------------------------------------- @@ -41,15 +39,13 @@ import com.google.common.collect.Lists; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.inject.Inject; import com.google.inject.Singleton; - import org.apache.shiro.concurrent.SubjectAwareExecutorService; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import sonia.scm.ArgumentIsInvalidException; import sonia.scm.ConfigurationException; import sonia.scm.HandlerEventType; +import sonia.scm.ManagerDaoAdapter; import sonia.scm.SCMContextProvider; import sonia.scm.Type; import sonia.scm.config.ScmConfiguration; @@ -60,10 +56,8 @@ import sonia.scm.util.HttpUtil; import sonia.scm.util.IOUtil; import sonia.scm.util.Util; -//~--- JDK imports ------------------------------------------------------------ - +import javax.servlet.http.HttpServletRequest; import java.io.IOException; - import java.util.Collection; import java.util.Collections; import java.util.Comparator; @@ -76,7 +70,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; -import javax.servlet.http.HttpServletRequest; +//~--- JDK imports ------------------------------------------------------------ /** * Default implementation of {@link RepositoryManager}. @@ -84,310 +78,170 @@ import javax.servlet.http.HttpServletRequest; * @author Sebastian Sdorra */ @Singleton -public class DefaultRepositoryManager extends AbstractRepositoryManager -{ +public class DefaultRepositoryManager extends AbstractRepositoryManager { - /** Field description */ private static final String THREAD_NAME = "Hook-%s"; - - /** Field description */ private static final Logger logger = LoggerFactory.getLogger(DefaultRepositoryManager.class); + private final ScmConfiguration configuration; + private final ExecutorService executorService; + private final Map handlerMap; + private final KeyGenerator keyGenerator; + private final RepositoryDAO repositoryDAO; + private final Set types; + private RepositoryMatcher repositoryMatcher; + private NamespaceStrategy namespaceStrategy; + private final ManagerDaoAdapter managerDaoAdapter; - //~--- constructors --------------------------------------------------------- - /** - * Constructs ... - * - * @param configuration - * @param contextProvider - * @param keyGenerator - * @param repositoryDAO - * @param handlerSet - * @param repositoryMatcher - */ @Inject public DefaultRepositoryManager(ScmConfiguration configuration, - SCMContextProvider contextProvider, KeyGenerator keyGenerator, - RepositoryDAO repositoryDAO, Set handlerSet, - RepositoryMatcher repositoryMatcher) - { + SCMContextProvider contextProvider, KeyGenerator keyGenerator, + RepositoryDAO repositoryDAO, Set handlerSet, + RepositoryMatcher repositoryMatcher, + NamespaceStrategy namespaceStrategy) { this.configuration = configuration; this.keyGenerator = keyGenerator; this.repositoryDAO = repositoryDAO; this.repositoryMatcher = repositoryMatcher; + this.namespaceStrategy = namespaceStrategy; - //J- ThreadFactory factory = new ThreadFactoryBuilder() .setNameFormat(THREAD_NAME).build(); this.executorService = new SubjectAwareExecutorService( Executors.newCachedThreadPool(factory) ); - //J+ handlerMap = new HashMap<>(); types = new HashSet<>(); - for (RepositoryHandler handler : handlerSet) - { + for (RepositoryHandler handler : handlerSet) { addHandler(contextProvider, handler); } + managerDaoAdapter = new ManagerDaoAdapter<>( + repositoryDAO, + RepositoryNotFoundException::new, + RepositoryAlreadyExistsException::create); } - //~--- methods -------------------------------------------------------------- - /** - * Method description - * - * - * @throws IOException - */ @Override - public void close() throws IOException - { + public void close() { executorService.shutdown(); - for (RepositoryHandler handler : handlerMap.values()) - { + for (RepositoryHandler handler : handlerMap.values()) { IOUtil.close(handler); } } - /** - * Method description - * - * - * @param repository - * @param initRepository - * - * @throws IOException - * @throws RepositoryException - */ - public void create(Repository repository, boolean initRepository) - throws RepositoryException, IOException - { - logger.info("create repository {} of type {}", repository.getName(), - repository.getType()); - - RepositoryPermissions.create().check(); - AssertUtil.assertIsValid(repository); - - if (repositoryDAO.contains(repository)) - { - throw RepositoryAlreadyExistsException.create(repository); - } + @Override + public Repository create(Repository repository) throws RepositoryException { + return create(repository, true); + } + public Repository create(Repository repository, boolean initRepository) throws RepositoryException { repository.setId(keyGenerator.createKey()); - repository.setCreationDate(System.currentTimeMillis()); + repository.setNamespace(namespaceStrategy.getNamespace()); - if (initRepository) - { - getHandler(repository).create(repository); - } + logger.info("create repository {} of type {} in namespace {}", repository.getName(), repository.getType(), repository.getNamespace()); - fireEvent(HandlerEventType.BEFORE_CREATE, repository); - repositoryDAO.add(repository); - fireEvent(HandlerEventType.CREATE, repository); + return managerDaoAdapter.create( + repository, + RepositoryPermissions::create, + newRepository -> { + if (initRepository) { + getHandler(newRepository).create(newRepository); + } + fireEvent(HandlerEventType.BEFORE_CREATE, newRepository); + }, + newRepository -> fireEvent(HandlerEventType.CREATE, newRepository) + ); } - /** - * Method description - * - * - * @param repository - * - * @throws IOException - * @throws RepositoryException - */ @Override - public void create(Repository repository) - throws RepositoryException, IOException - { - create(repository, true); + public void delete(Repository repository) throws RepositoryException { + logger.info("delete repository {} of type {}", repository.getName(), repository.getType()); + managerDaoAdapter.delete( + repository, + () -> RepositoryPermissions.delete(repository), + this::preDelete, + toDelete -> fireEvent(HandlerEventType.DELETE, toDelete) + ); } - /** - * Method description - * - * - * @param repository - * - * @throws IOException - * @throws RepositoryException - */ - @Override - public void delete(Repository repository) - throws RepositoryException, IOException - { - if (logger.isInfoEnabled()) - { - logger.info("delete repository {} of type {}", repository.getName(), - repository.getType()); - } - - RepositoryPermissions.delete(repository).check(); - - if (configuration.isEnableRepositoryArchive() &&!repository.isArchived()) - { - throw new RepositoryIsNotArchivedException( - "Repository could not deleted, because it is not archived."); - } - - if (repositoryDAO.contains(repository)) - { - fireEvent(HandlerEventType.BEFORE_DELETE, repository); - getHandler(repository).delete(repository); - repositoryDAO.delete(repository); - fireEvent(HandlerEventType.DELETE, repository); - } - else - { - throw new RepositoryNotFoundException( - "repository ".concat(repository.getName()).concat(" not found")); + private void preDelete(Repository toDelete) throws RepositoryException { + if (configuration.isEnableRepositoryArchive() && !toDelete.isArchived()) { + throw new RepositoryIsNotArchivedException("Repository could not deleted, because it is not archived."); } + fireEvent(HandlerEventType.BEFORE_DELETE, toDelete); + getHandler(toDelete).delete(toDelete); } - /** - * Method description - * - * - * @param repository - * - * @throws IOException - * @throws RepositoryException - */ @Override public void importRepository(Repository repository) - throws RepositoryException, IOException - { + throws RepositoryException, IOException { create(repository, false); } - /** - * Method description - * - * - * @param context - */ @Override - public void init(SCMContextProvider context) {} - - /** - * Method description - * - * - * @param repository - * - * @throws IOException - * @throws RepositoryException - */ - @Override - public void modify(Repository repository) - throws RepositoryException, IOException - { - if (logger.isInfoEnabled()) - { - logger.info("modify repository {} of type {}", repository.getName(), - repository.getType()); - } - - AssertUtil.assertIsValid(repository); - - Repository oldRepository = repositoryDAO.get(repository.getType(), - repository.getName()); - - if (oldRepository != null) - { - RepositoryPermissions.modify(oldRepository).check(); - fireEvent(HandlerEventType.BEFORE_MODIFY, repository, oldRepository); - repository.setLastModified(System.currentTimeMillis()); - getHandler(repository).modify(repository); - repositoryDAO.modify(repository); - fireEvent(HandlerEventType.MODIFY, repository, oldRepository); - } - else - { - throw new RepositoryNotFoundException( - "repository ".concat(repository.getName()).concat(" not found")); - } + public void init(SCMContextProvider context) { + } + + @Override + public void modify(Repository repository) throws RepositoryException { + logger.info("modify repository {} of type {}", repository.getName(), repository.getType()); + + managerDaoAdapter.modify( + repository, + RepositoryPermissions::modify, + notModified -> { + fireEvent(HandlerEventType.BEFORE_MODIFY, repository, notModified); + getHandler(repository).modify(repository); + }, + notModified -> fireEvent(HandlerEventType.MODIFY, repository, notModified) + ); } - /** - * Method description - * - * - * @param repository - * - * @throws IOException - * @throws RepositoryException - */ @Override public void refresh(Repository repository) - throws RepositoryException, IOException - { + throws RepositoryException { AssertUtil.assertIsNotNull(repository); RepositoryPermissions.read(repository).check(); - Repository fresh = repositoryDAO.get(repository.getType(), - repository.getName()); + Repository fresh = repositoryDAO.get(repository.getNamespaceAndName()); - if (fresh != null) - { + if (fresh != null) { fresh.copyProperties(repository); - } - else - { - throw new RepositoryNotFoundException( - "repository ".concat(repository.getName()).concat(" not found")); + } else { + throw new RepositoryNotFoundException(repository); } } - //~--- get methods ---------------------------------------------------------- - /** - * Method description - * - * - * @param id - * - * @return - */ @Override - public Repository get(String id) - { + public Repository get(String id) { AssertUtil.assertIsNotEmpty(id); RepositoryPermissions.read(id).check(); Repository repository = repositoryDAO.get(id); - if (repository != null) - { + if (repository != null) { repository = repository.clone(); } return repository; } - /** - * Method description - * - * - * @param type - * @param name - * - * @return - */ @Override - public Repository get(String type, String name) - { - AssertUtil.assertIsNotEmpty(type); - AssertUtil.assertIsNotEmpty(name); + public Repository get(NamespaceAndName namespaceAndName) { + AssertUtil.assertIsNotNull(namespaceAndName); + AssertUtil.assertIsNotEmpty(namespaceAndName.getNamespace()); + AssertUtil.assertIsNotEmpty(namespaceAndName.getName()); - Repository repository = repositoryDAO.get(type, name); + Repository repository = repositoryDAO.get(namespaceAndName); - if (repository != null) - { + if (repository != null) { RepositoryPermissions.read(repository).check(); repository = repository.clone(); } @@ -395,114 +249,62 @@ public class DefaultRepositoryManager extends AbstractRepositoryManager return repository; } - /** - * Method description - * - * - * - * @param comparator - * @return - */ @Override - public Collection getAll(Comparator comparator) - { + public Collection getAll(Comparator comparator) { List repositories = Lists.newArrayList(); PermissionActionCheck check = RepositoryPermissions.read(); - for (Repository repository : repositoryDAO.getAll()) - { + for (Repository repository : repositoryDAO.getAll()) { if (handlerMap.containsKey(repository.getType()) - && check.isPermitted(repository)) - { + && check.isPermitted(repository)) { Repository r = repository.clone(); repositories.add(r); } } - if (comparator != null) - { + if (comparator != null) { Collections.sort(repositories, comparator); } return repositories; } - /** - * Method description - * - * - * @return - */ @Override - public Collection getAll() - { + public Collection getAll() { return getAll(null); } - /** - * Method description - * - * - * - * @param comparator - * @param start - * @param limit - * - * @return - */ + @Override public Collection getAll(Comparator comparator, - int start, int limit) - { + int start, int limit) { final PermissionActionCheck check = RepositoryPermissions.read(); return Util.createSubCollection(repositoryDAO.getAll(), comparator, - new CollectionAppender() - { - @Override - public void append(Collection collection, Repository item) - { - if (check.isPermitted(item)) - { - collection.add(item.clone()); + new CollectionAppender() { + @Override + public void append(Collection collection, Repository item) { + if (check.isPermitted(item)) { + collection.add(item.clone()); + } } - } - }, start, limit); + }, start, limit); } - /** - * Method description - * - * - * @param start - * @param limit - * - * @return - */ @Override - public Collection getAll(int start, int limit) - { + public Collection getAll(int start, int limit) { return getAll(null, start, limit); } - /** - * Method description - * - * - * @return - */ @Override - public Collection getConfiguredTypes() - { + public Collection getConfiguredTypes() { List validTypes = Lists.newArrayList(); - for (RepositoryHandler handler : handlerMap.values()) - { - if (handler.isConfigured()) - { + for (RepositoryHandler handler : handlerMap.values()) { + if (handler.isConfigured()) { validTypes.add(handler.getType()); } } @@ -510,41 +312,40 @@ public class DefaultRepositoryManager extends AbstractRepositoryManager return validTypes; } - /** - * Method description - * - * - * @param request - * - * @return - */ @Override - public Repository getFromRequest(HttpServletRequest request) - { + public Repository getFromRequest(HttpServletRequest request) { AssertUtil.assertIsNotNull(request); return getFromUri(HttpUtil.getStrippedURI(request)); } - /** - * Method description - * - * - * @param type - * @param uri - * - * @return - */ @Override - public Repository getFromTypeAndUri(String type, String uri) - { - if (Strings.isNullOrEmpty(type)) - { + public Repository getFromUri(String uri) { + AssertUtil.assertIsNotEmpty(uri); + + if (uri.startsWith(HttpUtil.SEPARATOR_PATH)) { + uri = uri.substring(1); + } + + int typeSeparator = uri.indexOf(HttpUtil.SEPARATOR_PATH); + Repository repository = null; + + if (typeSeparator > 0) { + String type = uri.substring(0, typeSeparator); + + uri = uri.substring(typeSeparator + 1); + repository = getFromTypeAndUri(type, uri); + } + + return repository; + } + + private Repository getFromTypeAndUri(String type, String uri) { + if (Strings.isNullOrEmpty(type)) { throw new ArgumentIsInvalidException("argument type is required"); } - if (Strings.isNullOrEmpty(uri)) - { + if (Strings.isNullOrEmpty(uri)) { throw new ArgumentIsInvalidException("argument uri is required"); } @@ -553,16 +354,13 @@ public class DefaultRepositoryManager extends AbstractRepositoryManager Repository repository = null; - if (handlerMap.containsKey(type)) - { + if (handlerMap.containsKey(type)) { Collection repositories = repositoryDAO.getAll(); PermissionActionCheck check = RepositoryPermissions.read(); - for (Repository r : repositories) - { - if (repositoryMatcher.matches(r, type, uri)) - { + for (Repository r : repositories) { + if (repositoryMatcher.matches(r, type, uri)) { check.check(r); repository = r.clone(); @@ -571,8 +369,7 @@ public class DefaultRepositoryManager extends AbstractRepositoryManager } } - if ((repository == null) && logger.isDebugEnabled()) - { + if ((repository == null) && logger.isDebugEnabled()) { logger.debug("could not find repository with type {} and uri {}", type, uri); } @@ -580,103 +377,35 @@ public class DefaultRepositoryManager extends AbstractRepositoryManager return repository; } - /** - * Method description - * - * - * @param uri - * - * @return - */ @Override - public Repository getFromUri(String uri) - { - AssertUtil.assertIsNotEmpty(uri); - - if (uri.startsWith(HttpUtil.SEPARATOR_PATH)) - { - uri = uri.substring(1); - } - - int typeSeperator = uri.indexOf(HttpUtil.SEPARATOR_PATH); - Repository repository = null; - - if (typeSeperator > 0) - { - String type = uri.substring(0, typeSeperator); - - uri = uri.substring(typeSeperator + 1); - repository = getFromTypeAndUri(type, uri); - } - - return repository; - } - - /** - * Method description - * - * - * @param type - * - * @return - */ - @Override - public RepositoryHandler getHandler(String type) - { + public RepositoryHandler getHandler(String type) { return handlerMap.get(type); } - /** - * Method description - * - * - * @return - */ @Override - public Long getLastModified() - { + public Long getLastModified() { return repositoryDAO.getLastModified(); } - /** - * Method description - * - * - * @return - */ @Override - public Collection getTypes() - { + public Collection getTypes() { return types; } - //~--- methods -------------------------------------------------------------- - - /** - * Method description - * - * - * - * @param contextProvider - * @param handler - */ private void addHandler(SCMContextProvider contextProvider, - RepositoryHandler handler) - { + RepositoryHandler handler) { AssertUtil.assertIsNotNull(handler); Type type = handler.getType(); AssertUtil.assertIsNotNull(type); - if (handlerMap.containsKey(type.getName())) - { + if (handlerMap.containsKey(type.getName())) { throw new ConfigurationException( type.getName().concat("allready registered")); } - if (logger.isInfoEnabled()) - { + if (logger.isInfoEnabled()) { logger.info("added RepositoryHandler {} for type {}", handler.getClass(), type); } @@ -686,58 +415,18 @@ public class DefaultRepositoryManager extends AbstractRepositoryManager types.add(type); } - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @param repository - * - * @return - * - * - * @throws RepositoryException - */ private RepositoryHandler getHandler(Repository repository) - throws RepositoryException - { + throws RepositoryException { String type = repository.getType(); RepositoryHandler handler = handlerMap.get(type); - if (handler == null) - { + if (handler == null) { throw new RepositoryHandlerNotFoundException( "could not find handler for ".concat(type)); - } - else if (!handler.isConfigured()) - { + } else if (!handler.isConfigured()) { throw new RepositoryException("handler is not configured"); } return handler; } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private final ScmConfiguration configuration; - - /** Field description */ - private final ExecutorService executorService; - - /** Field description */ - private final Map handlerMap; - - /** Field description */ - private final KeyGenerator keyGenerator; - - /** Field description */ - private final RepositoryDAO repositoryDAO; - - /** Field description */ - private final Set types; - - /** Field description */ - private RepositoryMatcher repositoryMatcher; } diff --git a/scm-webapp/src/main/java/sonia/scm/repository/LastModifiedUpdateListener.java b/scm-webapp/src/main/java/sonia/scm/repository/LastModifiedUpdateListener.java index f8afe61200..a84324cd60 100644 --- a/scm-webapp/src/main/java/sonia/scm/repository/LastModifiedUpdateListener.java +++ b/scm-webapp/src/main/java/sonia/scm/repository/LastModifiedUpdateListener.java @@ -33,12 +33,10 @@ package sonia.scm.repository; //~--- non-JDK imports -------------------------------------------------------- -import com.google.common.eventbus.Subscribe; +import com.github.legman.Subscribe; import com.google.inject.Inject; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import sonia.scm.EagerSingleton; import sonia.scm.plugin.Extension; import sonia.scm.web.security.AdministrationContext; @@ -46,8 +44,6 @@ import sonia.scm.web.security.PrivilegedAction; //~--- JDK imports ------------------------------------------------------------ -import java.io.IOException; - /** * * @author Sebastian Sdorra @@ -154,7 +150,7 @@ public final class LastModifiedUpdateListener { repositoryManager.modify(dbr); } - catch (RepositoryException | IOException ex) + catch (RepositoryException ex) { logger.error("could not modify repository", ex); } diff --git a/scm-webapp/src/main/java/sonia/scm/repository/RepositoryMatcher.java b/scm-webapp/src/main/java/sonia/scm/repository/RepositoryMatcher.java index d0ad30e84f..8cb3871047 100644 --- a/scm-webapp/src/main/java/sonia/scm/repository/RepositoryMatcher.java +++ b/scm-webapp/src/main/java/sonia/scm/repository/RepositoryMatcher.java @@ -32,14 +32,15 @@ package sonia.scm.repository; -import com.google.common.collect.Maps; -import java.util.Map; -import java.util.Set; -import javax.inject.Inject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import sonia.scm.util.HttpUtil; -import sonia.scm.util.Util; + import com.google.common.collect.Maps; + import org.slf4j.Logger; + import org.slf4j.LoggerFactory; + import sonia.scm.util.HttpUtil; + import sonia.scm.util.Util; + + import javax.inject.Inject; + import java.util.Map; + import java.util.Set; /** * RepositoryMatcher is able to check if a repository matches the requested path. @@ -83,9 +84,24 @@ public final class RepositoryMatcher { } private boolean isPathMatching(Repository repository, String path) { - return getPathMatcherForType(repository.getType()).isPathMatching(repository, path); + + String namespace = extractNamespace(path); + String remainingPath = path.substring(namespace.length() + 1); + + return getPathMatcherForType(repository.getType()).isPathMatching(repository, remainingPath); } - + + private String extractNamespace(String path) { + if (path.startsWith(HttpUtil.SEPARATOR_PATH)) { + path = path.substring(1); + } + int namespaceSeparator = path.indexOf(HttpUtil.SEPARATOR_PATH); + if (namespaceSeparator > 0) { + return path.substring(0, namespaceSeparator); + } + throw new IllegalArgumentException("no namespace in path " + path); + } + private RepositoryPathMatcher getPathMatcherForType(String type) { RepositoryPathMatcher pathMatcher = pathMatchers.get(type); if (pathMatcher == null) { diff --git a/scm-webapp/src/main/java/sonia/scm/security/AuthorizationChangedEventProducer.java b/scm-webapp/src/main/java/sonia/scm/security/AuthorizationChangedEventProducer.java index c21ec17d18..5a954bb1e7 100644 --- a/scm-webapp/src/main/java/sonia/scm/security/AuthorizationChangedEventProducer.java +++ b/scm-webapp/src/main/java/sonia/scm/security/AuthorizationChangedEventProducer.java @@ -30,8 +30,8 @@ */ package sonia.scm.security; +import com.github.legman.Subscribe; import com.google.common.annotations.VisibleForTesting; -import com.google.common.eventbus.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sonia.scm.EagerSingleton; diff --git a/scm-webapp/src/main/java/sonia/scm/url/RestJsonUrlProvider.java b/scm-webapp/src/main/java/sonia/scm/url/RestJsonUrlProvider.java deleted file mode 100644 index 7be05d9f39..0000000000 --- a/scm-webapp/src/main/java/sonia/scm/url/RestJsonUrlProvider.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -import com.google.inject.Inject; -import com.google.inject.Provider; - -import sonia.scm.config.ScmConfiguration; - -/** - * - * @author Sebastian Sdorra - */ -public class RestJsonUrlProvider implements Provider -{ - - /** - * Constructs ... - * - * - * @param configuration - */ - @Inject - public RestJsonUrlProvider(ScmConfiguration configuration) - { - this.configuration = configuration; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - @Override - public UrlProvider get() - { - return UrlProviderFactory.createUrlProvider(configuration.getBaseUrl(), - UrlProviderFactory.TYPE_RESTAPI_JSON); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private ScmConfiguration configuration; -} diff --git a/scm-webapp/src/main/java/sonia/scm/url/RestXmlUrlProvider.java b/scm-webapp/src/main/java/sonia/scm/url/RestXmlUrlProvider.java deleted file mode 100644 index a4e8d8f1f2..0000000000 --- a/scm-webapp/src/main/java/sonia/scm/url/RestXmlUrlProvider.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -import com.google.inject.Inject; -import com.google.inject.Provider; - -import sonia.scm.config.ScmConfiguration; - -/** - * - * @author Sebastian Sdorra - */ -public class RestXmlUrlProvider implements Provider -{ - - /** - * Constructs ... - * - * - * @param configuration - */ - @Inject - public RestXmlUrlProvider(ScmConfiguration configuration) - { - this.configuration = configuration; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - @Override - public UrlProvider get() - { - return UrlProviderFactory.createUrlProvider(configuration.getBaseUrl(), - UrlProviderFactory.TYPE_RESTAPI_XML); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private ScmConfiguration configuration; -} diff --git a/scm-webapp/src/main/java/sonia/scm/url/WebUIUrlProvider.java b/scm-webapp/src/main/java/sonia/scm/url/WebUIUrlProvider.java deleted file mode 100644 index a71b3cd6d7..0000000000 --- a/scm-webapp/src/main/java/sonia/scm/url/WebUIUrlProvider.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright (c) 2010, Sebastian Sdorra - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of SCM-Manager; 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 REGENTS 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. - * - * http://bitbucket.org/sdorra/scm-manager - * - */ - - - -package sonia.scm.url; - -//~--- non-JDK imports -------------------------------------------------------- - -import com.google.inject.Inject; -import com.google.inject.Provider; - -import sonia.scm.config.ScmConfiguration; - -/** - * - * @author Sebastian Sdorra - */ -public class WebUIUrlProvider implements Provider -{ - - /** - * Constructs ... - * - * - * @param configuration - */ - @Inject - public WebUIUrlProvider(ScmConfiguration configuration) - { - this.configuration = configuration; - } - - //~--- get methods ---------------------------------------------------------- - - /** - * Method description - * - * - * @return - */ - @Override - public UrlProvider get() - { - return UrlProviderFactory.createUrlProvider(configuration.getBaseUrl(), - UrlProviderFactory.TYPE_WUI); - } - - //~--- fields --------------------------------------------------------------- - - /** Field description */ - private ScmConfiguration configuration; -} diff --git a/scm-webapp/src/main/java/sonia/scm/user/DefaultUserManager.java b/scm-webapp/src/main/java/sonia/scm/user/DefaultUserManager.java index 72ead40c58..c59ec40d4f 100644 --- a/scm-webapp/src/main/java/sonia/scm/user/DefaultUserManager.java +++ b/scm-webapp/src/main/java/sonia/scm/user/DefaultUserManager.java @@ -41,11 +41,11 @@ import com.google.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sonia.scm.HandlerEventType; +import sonia.scm.ManagerDaoAdapter; import sonia.scm.SCMContextProvider; import sonia.scm.TransformFilter; import sonia.scm.search.SearchRequest; import sonia.scm.search.SearchUtil; -import sonia.scm.util.AssertUtil; import sonia.scm.util.CollectionAppender; import sonia.scm.util.IOUtil; import sonia.scm.util.Util; @@ -96,6 +96,10 @@ public class DefaultUserManager extends AbstractUserManager public DefaultUserManager(UserDAO userDAO) { this.userDAO = userDAO; + this.managerDaoAdapter = new ManagerDaoAdapter<>( + userDAO, + UserNotFoundException::new, + UserAlreadyExistsException::new); } //~--- methods -------------------------------------------------------------- @@ -137,64 +141,31 @@ public class DefaultUserManager extends AbstractUserManager * @throws UserException */ @Override - public void create(User user) throws UserException, IOException - { + public User create(User user) throws UserException { String type = user.getType(); - - if (Util.isEmpty(type)) - { + if (Util.isEmpty(type)) { user.setType(userDAO.getType()); } - if (logger.isInfoEnabled()) - { - logger.info("create user {} of type {}", user.getName(), user.getType()); - } + logger.info("create user {} of type {}", user.getName(), user.getType()); - UserPermissions.create().check(); - - if (userDAO.contains(user.getName())) - { - throw new UserAlreadyExistsException(user.getName().concat(" user already exists")); - } - - AssertUtil.assertIsValid(user); - user.setCreationDate(System.currentTimeMillis()); - fireEvent(HandlerEventType.BEFORE_CREATE, user); - userDAO.add(user); - fireEvent(HandlerEventType.CREATE, user); + return managerDaoAdapter.create( + user, + UserPermissions::create, + newUser -> fireEvent(HandlerEventType.BEFORE_CREATE, newUser), + newUser -> fireEvent(HandlerEventType.CREATE, newUser) + ); } - /** - * Method description - * - * - * @param user - * - * @throws IOException - * @throws UserException - */ @Override - public void delete(User user) throws UserException, IOException - { - if (logger.isInfoEnabled()) - { - logger.info("delete user {} of type {}", user.getName(), user.getType()); - } - - String name = user.getName(); - UserPermissions.delete(name).check(); - - if (userDAO.contains(name)) - { - fireEvent(HandlerEventType.BEFORE_DELETE, user); - userDAO.delete(user); - fireEvent(HandlerEventType.DELETE, user); - } - else - { - throw new UserNotFoundException("user does not exists"); - } + public void delete(User user) throws UserException { + logger.info("delete user {} of type {}", user.getName(), user.getType()); + managerDaoAdapter.delete( + user, + () -> UserPermissions.delete(user.getName()), + toDelete -> fireEvent(HandlerEventType.BEFORE_DELETE, toDelete), + toDelete -> fireEvent(HandlerEventType.DELETE, toDelete) + ); } /** @@ -224,29 +195,15 @@ public class DefaultUserManager extends AbstractUserManager * @throws UserException */ @Override - public void modify(User user) throws UserException, IOException + public void modify(User user) throws UserException { - String name = user.getName(); - if (logger.isInfoEnabled()) - { - logger.info("modify user {} of type {}", user.getName(), user.getType()); - } - - UserPermissions.modify(user).check(); - User notModified = userDAO.get(name); - if (notModified != null) - { - AssertUtil.assertIsValid(user); - fireEvent(HandlerEventType.BEFORE_MODIFY, user, notModified); - user.setLastModified(System.currentTimeMillis()); - user.setCreationDate(notModified.getCreationDate()); - userDAO.modify(user); - fireEvent(HandlerEventType.MODIFY, user, notModified); - } - else - { - throw new UserNotFoundException("user does not exists"); - } + logger.info("modify user {} of type {}", user.getName(), user.getType()); + + managerDaoAdapter.modify( + user, + UserPermissions::modify, + notModified -> fireEvent(HandlerEventType.BEFORE_MODIFY, user, notModified), + notModified -> fireEvent(HandlerEventType.MODIFY, user, notModified)); } /** @@ -259,7 +216,7 @@ public class DefaultUserManager extends AbstractUserManager * @throws UserException */ @Override - public void refresh(User user) throws UserException, IOException + public void refresh(User user) throws UserException { if (logger.isInfoEnabled()) { @@ -271,7 +228,7 @@ public class DefaultUserManager extends AbstractUserManager if (fresh == null) { - throw new UserNotFoundException("user does not exists"); + throw new UserNotFoundException(user); } fresh.copyProperties(user); @@ -496,6 +453,6 @@ public class DefaultUserManager extends AbstractUserManager //~--- fields --------------------------------------------------------------- - /** Field description */ private final UserDAO userDAO; + private final ManagerDaoAdapter managerDaoAdapter; } diff --git a/scm-webapp/src/main/resources/logback.default.xml b/scm-webapp/src/main/resources/logback.default.xml index e2ed890525..33e914d04d 100644 --- a/scm-webapp/src/main/resources/logback.default.xml +++ b/scm-webapp/src/main/resources/logback.default.xml @@ -99,4 +99,4 @@ - \ No newline at end of file + diff --git a/scm-webapp/src/main/resources/templates/repository-root.mustache b/scm-webapp/src/main/resources/templates/repository-root.mustache index 0263f5356e..7e5cd5951e 100644 --- a/scm-webapp/src/main/resources/templates/repository-root.mustache +++ b/scm-webapp/src/main/resources/templates/repository-root.mustache @@ -93,7 +93,7 @@

diff --git a/scm-webapp/src/test/java/sonia/scm/api/rest/resources/AbstractManagerResourceTest.java b/scm-webapp/src/test/java/sonia/scm/api/rest/resources/AbstractManagerResourceTest.java new file mode 100644 index 0000000000..b3e931188a --- /dev/null +++ b/scm-webapp/src/test/java/sonia/scm/api/rest/resources/AbstractManagerResourceTest.java @@ -0,0 +1,137 @@ +package sonia.scm.api.rest.resources; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import sonia.scm.Manager; +import sonia.scm.ModelObject; + +import javax.ws.rs.core.GenericEntity; +import javax.ws.rs.core.Request; +import java.util.Collection; +import java.util.Comparator; + +import static java.util.Collections.emptyList; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class AbstractManagerResourceTest { + + @Mock + private Manager manager; + @Mock + private Request request; + @Captor + private ArgumentCaptor> comparatorCaptor; + + private AbstractManagerResource abstractManagerResource; + + @Before + public void captureComparator() { + when(manager.getAll(comparatorCaptor.capture(), eq(0), eq(1))).thenReturn(emptyList()); + abstractManagerResource = new SimpleManagerResource(); + } + + @Test + public void shouldAcceptDefaultSortByParameter() { + abstractManagerResource.getAll(request, 0, 1, null, true); + + Comparator comparator = comparatorCaptor.getValue(); + assertTrue(comparator.compare(new Simple("1", null), new Simple("2", null)) > 0); + } + + @Test + public void shouldAcceptValidSortByParameter() { + abstractManagerResource.getAll(request, 0, 1, "data", true); + + Comparator comparator = comparatorCaptor.getValue(); + assertTrue(comparator.compare(new Simple("", "1"), new Simple("", "2")) > 0); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldFailForIllegalSortByParameter() { + abstractManagerResource.getAll(request, 0, 1, "x", true); + } + + + private class SimpleManagerResource extends AbstractManagerResource { + + { + disableCache = true; + } + + private SimpleManagerResource() { + super(AbstractManagerResourceTest.this.manager, Simple.class); + } + + @Override + protected GenericEntity> createGenericEntity(Collection items) { + return null; + } + + @Override + protected String getId(Simple item) { + return null; + } + + @Override + protected String getPathPart() { + return null; + } + } + + public static class Simple implements ModelObject { + + private String id; + private String data; + + Simple(String id, String data) { + this.id = id; + this.data = data; + } + + public String getData() { + return data; + } + + @Override + public String getId() { + return id; + } + + @Override + public void setLastModified(Long timestamp) { + + } + + @Override + public Long getCreationDate() { + return null; + } + + @Override + public void setCreationDate(Long timestamp) { + + } + + @Override + public Long getLastModified() { + return null; + } + + @Override + public String getType() { + return null; + } + @Override + public boolean isValid() { + return false; + } + } +} diff --git a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/GroupCollectionToDtoMapperTest.java b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/GroupCollectionToDtoMapperTest.java index 2d9cc3ba70..5b457ce4e9 100644 --- a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/GroupCollectionToDtoMapperTest.java +++ b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/GroupCollectionToDtoMapperTest.java @@ -30,11 +30,12 @@ public class GroupCollectionToDtoMapperTest { private final UriInfo uriInfo = mock(UriInfo.class); private final UriInfoStore uriInfoStore = new UriInfoStore(); + private final ResourceLinks resourceLinks = new ResourceLinks(uriInfoStore); private final GroupToGroupDtoMapper groupToDtoMapper = mock(GroupToGroupDtoMapper.class); private final Subject subject = mock(Subject.class); private final ThreadState subjectThreadState = new SubjectThreadState(subject); - private final GroupCollectionToDtoMapper mapper = new GroupCollectionToDtoMapper(groupToDtoMapper, uriInfoStore); + private final GroupCollectionToDtoMapper mapper = new GroupCollectionToDtoMapper(groupToDtoMapper, resourceLinks); private URI expectedBaseUri; diff --git a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/GroupRootResourceTest.java b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/GroupRootResourceTest.java index 2b4cedb4fc..3302d6ef6e 100644 --- a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/GroupRootResourceTest.java +++ b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/GroupRootResourceTest.java @@ -20,7 +20,6 @@ import sonia.scm.group.GroupManager; import sonia.scm.web.VndMediaType; import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.UriInfo; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; @@ -28,7 +27,9 @@ import java.net.URL; import java.util.Collections; import static java.util.Collections.singletonList; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doNothing; @@ -47,10 +48,7 @@ public class GroupRootResourceTest { private Dispatcher dispatcher = MockDispatcherFactory.createDispatcher(); - @Mock - private UriInfo uriInfo; - @Mock - private UriInfoStore uriInfoStore; + private final ResourceLinks resourceLinks = ResourceLinksMock.createMock(URI.create("/")); @Mock private GroupManager groupManager; @@ -64,21 +62,19 @@ public class GroupRootResourceTest { @Before public void prepareEnvironment() throws IOException, GroupException { initMocks(this); - doNothing().when(groupManager).create(groupCaptor.capture()); + when(groupManager.create(groupCaptor.capture())).thenAnswer(invocation -> invocation.getArguments()[0]); + doNothing().when(groupManager).modify(groupCaptor.capture()); Group group = createDummyGroup(); when(groupManager.getPage(any(), eq(0), eq(10))).thenReturn(new PageResult<>(singletonList(group), 1)); when(groupManager.get("admin")).thenReturn(group); - GroupCollectionToDtoMapper groupCollectionToDtoMapper = new GroupCollectionToDtoMapper(groupToDtoMapper, uriInfoStore); - GroupCollectionResource groupCollectionResource = new GroupCollectionResource(groupManager, dtoToGroupMapper, groupCollectionToDtoMapper); + GroupCollectionToDtoMapper groupCollectionToDtoMapper = new GroupCollectionToDtoMapper(groupToDtoMapper, resourceLinks); + GroupCollectionResource groupCollectionResource = new GroupCollectionResource(groupManager, dtoToGroupMapper, groupCollectionToDtoMapper, resourceLinks); GroupResource groupResource = new GroupResource(groupManager, groupToDtoMapper, dtoToGroupMapper); GroupRootResource groupRootResource = new GroupRootResource(MockProvider.of(groupCollectionResource), MockProvider.of(groupResource)); dispatcher.getRegistry().addSingletonResource(groupRootResource); - - when(uriInfo.getBaseUri()).thenReturn(URI.create("/")); - when(uriInfoStore.get()).thenReturn(uriInfo); } @Test @@ -108,6 +104,74 @@ public class GroupRootResourceTest { assertTrue(response.getContentAsString().contains("\"name\":\"user\"")); } + @Test + public void shouldUpdateGroup() throws URISyntaxException, IOException { + URL url = Resources.getResource("sonia/scm/api/v2/group-test-update.json"); + byte[] groupJson = Resources.toByteArray(url); + + Group group = createDummyGroup(); + when(groupManager.get("admin")).thenReturn(group); + Group updatedGroup = createDummyGroup(); + updatedGroup.setDescription("Updated description"); + + MockHttpRequest request = MockHttpRequest + .put("/" + GroupRootResource.GROUPS_PATH_V2 + "admin") + .contentType(VndMediaType.GROUP) + .content(groupJson); + + MockHttpResponse response = new MockHttpResponse(); + + dispatcher.invoke(request, response); + Group capturedGroup = groupCaptor.getValue(); + + assertEquals(HttpServletResponse.SC_NO_CONTENT, response.getStatus()); + + assertEquals("Updated description", capturedGroup.getDescription()); + } + + @Test + public void updateShouldFailOnNonexistentGroup() throws URISyntaxException, IOException { + URL url = Resources.getResource("sonia/scm/api/v2/group-test-update.json"); + byte[] groupJson = Resources.toByteArray(url); + + Group updatedGroup = createDummyGroup(); + updatedGroup.setDescription("Updated description"); + + MockHttpRequest request = MockHttpRequest + .put("/" + GroupRootResource.GROUPS_PATH_V2 + "idontexist") + .contentType(VndMediaType.GROUP) + .content(groupJson); + + MockHttpResponse response = new MockHttpResponse(); + + dispatcher.invoke(request, response); + + assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus()); + } + + @Test + public void shouldDeleteGroup() throws URISyntaxException { + Group group = createDummyGroup(); + when(groupManager.get("admin")).thenReturn(group); + + MockHttpRequest request = MockHttpRequest.delete("/" + GroupRootResource.GROUPS_PATH_V2 + "admin"); + MockHttpResponse response = new MockHttpResponse(); + + dispatcher.invoke(request, response); + + assertEquals(HttpServletResponse.SC_NO_CONTENT, response.getStatus()); + } + + @Test + public void shouldNotFailOnDeletingNonexistentGroup() throws URISyntaxException { + MockHttpRequest request = MockHttpRequest.delete("/" + GroupRootResource.GROUPS_PATH_V2 + "idontexist"); + MockHttpResponse response = new MockHttpResponse(); + + dispatcher.invoke(request, response); + + assertEquals(HttpServletResponse.SC_NO_CONTENT, response.getStatus()); + } + @Test public void shouldCreateNewGroupWithMembers() throws URISyntaxException, IOException { URL url = Resources.getResource("sonia/scm/api/v2/group-test-create.json"); diff --git a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/GroupToGroupDtoMapperTest.java b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/GroupToGroupDtoMapperTest.java index 1a4c574182..e519a9c3e5 100644 --- a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/GroupToGroupDtoMapperTest.java +++ b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/GroupToGroupDtoMapperTest.java @@ -8,10 +8,8 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; -import org.mockito.Mock; import sonia.scm.group.Group; -import javax.ws.rs.core.UriInfo; import java.net.URI; import java.net.URISyntaxException; import java.util.stream.IntStream; @@ -24,10 +22,9 @@ import static org.mockito.MockitoAnnotations.initMocks; public class GroupToGroupDtoMapperTest { - @Mock - private UriInfo uriInfo; - @Mock - private UriInfoStore uriInfoStore; + private final URI baseUri = URI.create("http://example.com/base/"); + @SuppressWarnings("unused") // Is injected + private final ResourceLinks resourceLinks = ResourceLinksMock.createMock(baseUri); @InjectMocks private GroupToGroupDtoMapperImpl mapper; @@ -40,10 +37,7 @@ public class GroupToGroupDtoMapperTest { @Before public void init() throws URISyntaxException { initMocks(this); - URI baseUri = new URI("http://example.com/base/"); expectedBaseUri = baseUri.resolve(GroupRootResource.GROUPS_PATH_V2 + "/"); - when(uriInfo.getBaseUri()).thenReturn(baseUri); - when(uriInfoStore.get()).thenReturn(uriInfo); subjectThreadState.bind(); ThreadContext.bind(subject); } diff --git a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/MapperModuleTest.java b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/MapperModuleTest.java new file mode 100644 index 0000000000..a792d40e76 --- /dev/null +++ b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/MapperModuleTest.java @@ -0,0 +1,33 @@ +package sonia.scm.api.v2.resources; + +import com.google.inject.binder.AnnotatedBindingBuilder; +import org.junit.Test; +import org.mockito.ArgumentCaptor; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class MapperModuleTest { + + @Test + public void shouldBindToClassesWithDefaultConstructorOnly() { + AnnotatedBindingBuilder binding = mock(AnnotatedBindingBuilder.class); + ArgumentCaptor captor = ArgumentCaptor.forClass(Class.class); + when(binding.to(captor.capture())).thenReturn(null); + new MapperModule() { + @Override + protected AnnotatedBindingBuilder bind(Class clazz) { + return binding; + } + }.configure(); + captor.getAllValues().forEach(this::verifyClassCanBeInstantiated); + } + + private T verifyClassCanBeInstantiated(Class c) { + try { + return c.getConstructor().newInstance(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/RepositoryRootResourceTest.java b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/RepositoryRootResourceTest.java new file mode 100644 index 0000000000..24a11fbf09 --- /dev/null +++ b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/RepositoryRootResourceTest.java @@ -0,0 +1,237 @@ +package sonia.scm.api.v2.resources; + +import com.github.sdorra.shiro.ShiroRule; +import com.github.sdorra.shiro.SubjectAware; +import com.google.common.io.Resources; +import org.jboss.resteasy.core.Dispatcher; +import org.jboss.resteasy.mock.MockDispatcherFactory; +import org.jboss.resteasy.mock.MockHttpRequest; +import org.jboss.resteasy.mock.MockHttpResponse; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import sonia.scm.PageResult; +import sonia.scm.repository.Repository; +import sonia.scm.repository.RepositoryException; +import sonia.scm.repository.RepositoryManager; +import sonia.scm.web.VndMediaType; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; + +import static java.util.Collections.singletonList; +import static java.util.Optional.empty; +import static java.util.Optional.of; +import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; +import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; +import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT; +import static javax.servlet.http.HttpServletResponse.SC_OK; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +@SubjectAware( + username = "trillian", + password = "secret", + configuration = "classpath:sonia/scm/repository/shiro.ini" +) +public class RepositoryRootResourceTest { + + private final Dispatcher dispatcher = MockDispatcherFactory.createDispatcher(); + + @Rule + public ShiroRule shiro = new ShiroRule(); + + @Mock + private RepositoryManager repositoryManager; + + private final URI baseUri = URI.create("/"); + private final ResourceLinks resourceLinks = ResourceLinksMock.createMock(baseUri); + + @InjectMocks + private RepositoryToRepositoryDtoMapperImpl repositoryToDtoMapper; + @InjectMocks + private RepositoryDtoToRepositoryMapperImpl dtoToRepositoryMapper; + + @Before + public void prepareEnvironment() { + initMocks(this); + RepositoryResource repositoryResource = new RepositoryResource(repositoryToDtoMapper, dtoToRepositoryMapper, repositoryManager, null, null, null, null, null); + RepositoryCollectionToDtoMapper repositoryCollectionToDtoMapper = new RepositoryCollectionToDtoMapper(repositoryToDtoMapper, resourceLinks); + RepositoryCollectionResource repositoryCollectionResource = new RepositoryCollectionResource(repositoryManager, repositoryCollectionToDtoMapper, dtoToRepositoryMapper, resourceLinks); + RepositoryRootResource repositoryRootResource = new RepositoryRootResource(MockProvider.of(repositoryResource), MockProvider.of(repositoryCollectionResource)); + dispatcher.getRegistry().addSingletonResource(repositoryRootResource); + } + + @Test + public void shouldFailForNotExistingRepository() throws URISyntaxException { + when(repositoryManager.getByNamespace(anyString(), anyString())).thenReturn(empty()); + mockRepository("space", "repo"); + + MockHttpRequest request = MockHttpRequest.get("/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/other"); + MockHttpResponse response = new MockHttpResponse(); + + dispatcher.invoke(request, response); + + assertEquals(SC_NOT_FOUND, response.getStatus()); + } + + @Test + public void shouldFindExistingRepository() throws URISyntaxException { + mockRepository("space", "repo"); + + MockHttpRequest request = MockHttpRequest.get("/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo"); + MockHttpResponse response = new MockHttpResponse(); + + dispatcher.invoke(request, response); + + assertEquals(SC_OK, response.getStatus()); + assertTrue(response.getContentAsString().contains("\"name\":\"repo\"")); + } + + @Test + public void shouldMapProperties() throws URISyntaxException { + Repository repository = mockRepository("space", "repo"); + repository.setProperty("testKey", "testValue"); + + MockHttpRequest request = MockHttpRequest.get("/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo"); + MockHttpResponse response = new MockHttpResponse(); + + dispatcher.invoke(request, response); + + assertTrue(response.getContentAsString().contains("\"testKey\":\"testValue\"")); + } + + @Test + public void shouldGetAll() throws URISyntaxException { + PageResult singletonPageResult = createSingletonPageResult(mockRepository("space", "repo")); + when(repositoryManager.getPage(any(), eq(0), eq(10))).thenReturn(singletonPageResult); + + MockHttpRequest request = MockHttpRequest.get("/" + RepositoryRootResource.REPOSITORIES_PATH_V2); + MockHttpResponse response = new MockHttpResponse(); + + dispatcher.invoke(request, response); + + assertEquals(SC_OK, response.getStatus()); + assertTrue(response.getContentAsString().contains("\"name\":\"repo\"")); + } + + @Test + public void shouldHandleUpdateForNotExistingRepository() throws URISyntaxException, IOException { + URL url = Resources.getResource("sonia/scm/api/v2/repository-test-update.json"); + byte[] repository = Resources.toByteArray(url); + when(repositoryManager.getByNamespace(anyString(), anyString())).thenReturn(empty()); + + MockHttpRequest request = MockHttpRequest + .put("/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo") + .contentType(VndMediaType.REPOSITORY) + .content(repository); + MockHttpResponse response = new MockHttpResponse(); + + dispatcher.invoke(request, response); + + assertEquals(SC_NOT_FOUND, response.getStatus()); + } + + @Test + public void shouldHandleUpdateForExistingRepository() throws Exception { + mockRepository("space", "repo"); + + URL url = Resources.getResource("sonia/scm/api/v2/repository-test-update.json"); + byte[] repository = Resources.toByteArray(url); + + MockHttpRequest request = MockHttpRequest + .put("/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo") + .contentType(VndMediaType.REPOSITORY) + .content(repository); + MockHttpResponse response = new MockHttpResponse(); + + dispatcher.invoke(request, response); + + assertEquals(SC_NO_CONTENT, response.getStatus()); + verify(repositoryManager).modify(anyObject()); + } + + @Test + public void shouldHandleUpdateForExistingRepositoryForChangedNamespace() throws Exception { + mockRepository("wrong", "repo"); + + URL url = Resources.getResource("sonia/scm/api/v2/repository-test-update.json"); + byte[] repository = Resources.toByteArray(url); + + MockHttpRequest request = MockHttpRequest + .put("/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + "wrong/repo") + .contentType(VndMediaType.REPOSITORY) + .content(repository); + MockHttpResponse response = new MockHttpResponse(); + + dispatcher.invoke(request, response); + + assertEquals(SC_BAD_REQUEST, response.getStatus()); + verify(repositoryManager, never()).modify(anyObject()); + } + + @Test + public void shouldHandleDeleteForExistingRepository() throws Exception { + mockRepository("space", "repo"); + + MockHttpRequest request = MockHttpRequest.delete("/" + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo"); + MockHttpResponse response = new MockHttpResponse(); + + dispatcher.invoke(request, response); + + assertEquals(SC_NO_CONTENT, response.getStatus()); + verify(repositoryManager).delete(anyObject()); + } + + @Test + public void shouldCreateNewRepositoryInCorrectNamespace() throws URISyntaxException, IOException, RepositoryException { + when(repositoryManager.create(any())).thenAnswer(invocation -> { + Repository repository = (Repository) invocation.getArguments()[0]; + repository.setNamespace("otherspace"); + return repository; + }); + + URL url = Resources.getResource("sonia/scm/api/v2/repository-test-update.json"); + byte[] repositoryJson = Resources.toByteArray(url); + + MockHttpRequest request = MockHttpRequest + .post("/" + RepositoryRootResource.REPOSITORIES_PATH_V2) + .contentType(VndMediaType.REPOSITORY) + .content(repositoryJson); + MockHttpResponse response = new MockHttpResponse(); + + dispatcher.invoke(request, response); + + assertEquals(HttpServletResponse.SC_CREATED, response.getStatus()); + assertEquals("/v2/repositories/otherspace/repo", response.getOutputHeaders().get("Location").get(0).toString()); + verify(repositoryManager).create(any(Repository.class)); + } + + private PageResult createSingletonPageResult(Repository repository) { + return new PageResult<>(singletonList(repository), 0); + } + + private Repository mockRepository(String namespace, String name) { + Repository repository = new Repository(); + repository.setNamespace(namespace); + repository.setName(name); + String id = namespace + "-" + name; + repository.setId(id); + when(repositoryManager.getByNamespace(namespace, name)).thenReturn(of(repository)); + when(repositoryManager.get(id)).thenReturn(repository); + return repository; + } +} diff --git a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/RepositoryToRepositoryDtoMapperTest.java b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/RepositoryToRepositoryDtoMapperTest.java new file mode 100644 index 0000000000..ad6ff3cae7 --- /dev/null +++ b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/RepositoryToRepositoryDtoMapperTest.java @@ -0,0 +1,159 @@ +package sonia.scm.api.v2.resources; + +import com.github.sdorra.shiro.ShiroRule; +import com.github.sdorra.shiro.SubjectAware; +import org.apache.shiro.util.ThreadContext; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.mockito.InjectMocks; +import sonia.scm.repository.HealthCheckFailure; +import sonia.scm.repository.Permission; +import sonia.scm.repository.PermissionType; +import sonia.scm.repository.Repository; + +import java.net.URI; + +import static java.util.Collections.singletonList; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.mockito.MockitoAnnotations.initMocks; + +@SubjectAware( + username = "trillian", + password = "secret", + configuration = "classpath:sonia/scm/repository/shiro.ini" +) +public class RepositoryToRepositoryDtoMapperTest { + + @Rule + public final ShiroRule rule = new ShiroRule(); + + private final URI baseUri = URI.create("http://example.com/base/"); + @SuppressWarnings("unused") // Is injected + private final ResourceLinks resourceLinks = ResourceLinksMock.createMock(baseUri); + + @InjectMocks + private RepositoryToRepositoryDtoMapperImpl mapper; + + @Before + public void init() { + initMocks(this); + } + + @After + public void cleanup() { + ThreadContext.unbindSubject(); + } + + @Test + public void shouldMapSimpleProperties() { + RepositoryDto dto = mapper.map(createTestRepository()); + assertEquals("testspace", dto.getNamespace()); + assertEquals("test", dto.getName()); + assertEquals("description", dto.getDescription()); + assertEquals("git", dto.getType()); + assertEquals("none@example.com", dto.getContact()); + } + + @Test + public void shouldMapPropertiesProperty() { + Repository repository = createTestRepository(); + repository.setProperty("testKey", "testValue"); + + RepositoryDto dto = mapper.map(repository); + + assertEquals("testValue", dto.getProperties().get("testKey")); + } + + @Test + @SubjectAware(username = "unpriv") + public void shouldCreateLinksForUnprivilegedUser() { + RepositoryDto dto = mapper.map(createTestRepository()); + assertEquals( + "http://example.com/base/v2/repositories/testspace/test", + dto.getLinks().getLinkBy("self").get().getHref()); + assertFalse(dto.getLinks().getLinkBy("update").isPresent()); + assertFalse(dto.getLinks().getLinkBy("delete").isPresent()); + assertFalse(dto.getLinks().getLinkBy("permissions").isPresent()); + } + + @Test + public void shouldCreateDeleteLink() { + RepositoryDto dto = mapper.map(createTestRepository()); + assertEquals( + "http://example.com/base/v2/repositories/testspace/test", + dto.getLinks().getLinkBy("delete").get().getHref()); + } + + @Test + public void shouldCreateUpdateLink() { + RepositoryDto dto = mapper.map(createTestRepository()); + assertEquals( + "http://example.com/base/v2/repositories/testspace/test", + dto.getLinks().getLinkBy("update").get().getHref()); + } + + @Test + public void shouldMapHealthCheck() { + RepositoryDto dto = mapper.map(createTestRepository()); + assertEquals(1, dto.getHealthCheckFailures().size()); + assertEquals("summary", dto.getHealthCheckFailures().get(0).getSummary()); + } + + @Test + public void shouldCreateTagsLink() { + RepositoryDto dto = mapper.map(createTestRepository()); + assertEquals( + "http://example.com/base/v2/repositories/testspace/test/tags/", + dto.getLinks().getLinkBy("tags").get().getHref()); + } + + @Test + public void shouldCreateBranchesLink() { + RepositoryDto dto = mapper.map(createTestRepository()); + assertEquals( + "http://example.com/base/v2/repositories/testspace/test/branches/", + dto.getLinks().getLinkBy("branches").get().getHref()); + } + + @Test + public void shouldCreateChangesetsLink() { + RepositoryDto dto = mapper.map(createTestRepository()); + assertEquals( + "http://example.com/base/v2/repositories/testspace/test/changesets/", + dto.getLinks().getLinkBy("changesets").get().getHref()); + } + + @Test + public void shouldCreateSourcesLink() { + RepositoryDto dto = mapper.map(createTestRepository()); + assertEquals( + "http://example.com/base/v2/repositories/testspace/test/sources/", + dto.getLinks().getLinkBy("sources").get().getHref()); + } + + @Test + public void shouldCreatePermissionsLink() { + RepositoryDto dto = mapper.map(createTestRepository()); + assertEquals( + "http://example.com/base/v2/repositories/testspace/test/permissions/", + dto.getLinks().getLinkBy("permissions").get().getHref()); + } + + private Repository createTestRepository() { + Repository repository = new Repository(); + repository.setNamespace("testspace"); + repository.setName("test"); + repository.setDescription("description"); + repository.setType("git"); + repository.setContact("none@example.com"); + repository.setId("1"); + repository.setCreationDate(System.currentTimeMillis()); + repository.setHealthCheckFailures(singletonList(new HealthCheckFailure("1", "summary", "url", "failure"))); + repository.setPermissions(singletonList(new Permission("permission", PermissionType.READ))); + + return repository; + } +} diff --git a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/ResourceLinksMock.java b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/ResourceLinksMock.java new file mode 100644 index 0000000000..b35bc3820c --- /dev/null +++ b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/ResourceLinksMock.java @@ -0,0 +1,29 @@ +package sonia.scm.api.v2.resources; + +import javax.ws.rs.core.UriInfo; +import java.net.URI; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ResourceLinksMock { + public static ResourceLinks createMock(URI baseUri) { + ResourceLinks resourceLinks = mock(ResourceLinks.class); + + UriInfo uriInfo = mock(UriInfo.class); + when(uriInfo.getBaseUri()).thenReturn(baseUri); + + when(resourceLinks.user()).thenReturn(new ResourceLinks.UserLinks(uriInfo)); + when(resourceLinks.userCollection()).thenReturn(new ResourceLinks.UserCollectionLinks(uriInfo)); + when(resourceLinks.group()).thenReturn(new ResourceLinks.GroupLinks(uriInfo)); + when(resourceLinks.groupCollection()).thenReturn(new ResourceLinks.GroupCollectionLinks(uriInfo)); + when(resourceLinks.repository()).thenReturn(new ResourceLinks.RepositoryLinks(uriInfo)); + when(resourceLinks.repositoryCollection()).thenReturn(new ResourceLinks.RepositoryCollectionLinks(uriInfo)); + when(resourceLinks.tagCollection()).thenReturn(new ResourceLinks.TagCollectionLinks(uriInfo)); + when(resourceLinks.branchCollection()).thenReturn(new ResourceLinks.BranchCollectionLinks(uriInfo)); + when(resourceLinks.changesetCollection()).thenReturn(new ResourceLinks.ChangesetCollectionLinks(uriInfo)); + when(resourceLinks.sourceCollection()).thenReturn(new ResourceLinks.SourceCollectionLinks(uriInfo)); + when(resourceLinks.permissionCollection()).thenReturn(new ResourceLinks.PermissionCollectionLinks(uriInfo)); + return resourceLinks; + } +} diff --git a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/ResourceLinksTest.java b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/ResourceLinksTest.java index 3eb43e8fc3..c4bc5c73cd 100644 --- a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/ResourceLinksTest.java +++ b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/ResourceLinksTest.java @@ -2,85 +2,140 @@ package sonia.scm.api.v2.resources; import org.junit.Before; import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; import javax.ws.rs.core.UriInfo; import java.net.URI; import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import static sonia.scm.api.v2.resources.ResourceLinks.group; -import static sonia.scm.api.v2.resources.ResourceLinks.user; -import static sonia.scm.api.v2.resources.ResourceLinks.userCollection; +import static org.mockito.MockitoAnnotations.initMocks; public class ResourceLinksTest { private static final String BASE_URL = "http://example.com/"; - private UriInfo uriInfo = mock(UriInfo.class); + @Mock + private UriInfoStore uriInfoStore; + @Mock + private UriInfo uriInfo; + + @InjectMocks + private ResourceLinks resourceLinks; @Test public void shouldCreateCorrectUserSelfUrl() { - String url = user(uriInfo).self("ich"); + String url = resourceLinks.user().self("ich"); assertEquals(BASE_URL + UserRootResource.USERS_PATH_V2 + "ich", url); } @Test public void shouldCreateCorrectUserDeleteUrl() { - String url = user(uriInfo).delete("ich"); + String url = resourceLinks.user().delete("ich"); assertEquals(BASE_URL + UserRootResource.USERS_PATH_V2 + "ich", url); } @Test public void shouldCreateCorrectUserUpdateUrl() { - String url = user(uriInfo).update("ich"); + String url = resourceLinks.user().update("ich"); assertEquals(BASE_URL + UserRootResource.USERS_PATH_V2 + "ich", url); } @Test public void shouldCreateCorrectUserCreateUrl() { - String url = userCollection(uriInfo).create(); + String url = resourceLinks.userCollection().create(); assertEquals(BASE_URL + UserRootResource.USERS_PATH_V2, url); } @Test public void shouldCreateCorrectUserCollectionUrl() { - String url = userCollection(uriInfo).self(); + String url = resourceLinks.userCollection().self(); assertEquals(BASE_URL + UserRootResource.USERS_PATH_V2, url); } @Test public void shouldCreateCorrectGroupSelfUrl() { - String url = group(uriInfo).self("nobodies"); + String url = resourceLinks.group().self("nobodies"); assertEquals(BASE_URL + GroupRootResource.GROUPS_PATH_V2 + "nobodies", url); } @Test public void shouldCreateCorrectGroupDeleteUrl() { - String url = group(uriInfo).delete("nobodies"); + String url = resourceLinks.group().delete("nobodies"); assertEquals(BASE_URL + GroupRootResource.GROUPS_PATH_V2 + "nobodies", url); } @Test public void shouldCreateCorrectGroupUpdateUrl() { - String url = group(uriInfo).update("nobodies"); + String url = resourceLinks.group().update("nobodies"); assertEquals(BASE_URL + GroupRootResource.GROUPS_PATH_V2 + "nobodies", url); } @Test public void shouldCreateCorrectGroupCreateUrl() { - String url = ResourceLinks.groupCollection(uriInfo).create(); + String url = resourceLinks.groupCollection().create(); assertEquals(BASE_URL + GroupRootResource.GROUPS_PATH_V2, url); } @Test public void shouldCreateCorrectGroupCollectionUrl() { - String url = ResourceLinks.groupCollection(uriInfo).self(); + String url = resourceLinks.groupCollection().self(); assertEquals(BASE_URL + GroupRootResource.GROUPS_PATH_V2, url); } + @Test + public void shouldCreateCorrectRepositorySelfUrl() { + String url = resourceLinks.repository().self("space", "repo"); + assertEquals(BASE_URL + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo", url); + } + + @Test + public void shouldCreateCorrectRepositoryDeleteUrl() { + String url = resourceLinks.repository().delete("space", "repo"); + assertEquals(BASE_URL + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo", url); + } + + @Test + public void shouldCreateCorrectRepositoryUpdateUrl() { + String url = resourceLinks.repository().update("space", "repo"); + assertEquals(BASE_URL + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo", url); + } + + @Test + public void shouldCreateCorrectTagCollectionUrl() { + String url = resourceLinks.tagCollection().self("space", "repo"); + assertEquals(BASE_URL + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo/tags/", url); + } + + @Test + public void shouldCreateCorrectBranchCollectionUrl() { + String url = resourceLinks.branchCollection().self("space", "repo"); + assertEquals(BASE_URL + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo/branches/", url); + } + + @Test + public void shouldCreateCorrectChangesetCollectionUrl() { + String url = resourceLinks.changesetCollection().self("space", "repo"); + assertEquals(BASE_URL + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo/changesets/", url); + } + + @Test + public void shouldCreateCorrectSourceCollectionUrl() { + String url = resourceLinks.sourceCollection().self("space", "repo"); + assertEquals(BASE_URL + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo/sources/", url); + } + + @Test + public void shouldCreateCorrectPermissionCollectionUrl() { + String url = resourceLinks.sourceCollection().self("space", "repo"); + assertEquals(BASE_URL + RepositoryRootResource.REPOSITORIES_PATH_V2 + "space/repo/sources/", url); + } + @Before public void initUriInfo() { + initMocks(this); + when(uriInfoStore.get()).thenReturn(uriInfo); when(uriInfo.getBaseUri()).thenReturn(URI.create(BASE_URL)); } } diff --git a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/UserCollectionToDtoMapperTest.java b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/UserCollectionToDtoMapperTest.java index 4fb9402dfc..4d2bf7c62e 100644 --- a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/UserCollectionToDtoMapperTest.java +++ b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/UserCollectionToDtoMapperTest.java @@ -12,7 +12,6 @@ import org.mockito.Mock; import sonia.scm.PageResult; import sonia.scm.user.User; -import javax.ws.rs.core.UriInfo; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; @@ -28,14 +27,12 @@ import static sonia.scm.PageResult.createPage; public class UserCollectionToDtoMapperTest { + private final URI baseUri = URI.create("http://example.com/base/"); + private final ResourceLinks resourceLinks = ResourceLinksMock.createMock(baseUri); @Mock - private UriInfo uriInfo; + private UserToUserDtoMapper userToDtoMapper; @Mock - private UriInfoStore uriInfoStore; - @Mock - private UserToUserDtoMapper userToDtoMapper; - @Mock - private Subject subject; + private Subject subject; @InjectMocks private SubjectThreadState subjectThreadState; @@ -47,10 +44,7 @@ public class UserCollectionToDtoMapperTest { @Before public void init() throws URISyntaxException { initMocks(this); - URI baseUri = new URI("http://example.com/base/"); expectedBaseUri = baseUri.resolve(UserRootResource.USERS_PATH_V2 + "/"); - when(uriInfo.getBaseUri()).thenReturn(baseUri); - when(uriInfoStore.get()).thenReturn(uriInfo); subjectThreadState.bind(); ThreadContext.bind(subject); } diff --git a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/UserDtoToUserMapperTest.java b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/UserDtoToUserMapperTest.java index e76cee1ef7..f97fd91c3b 100644 --- a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/UserDtoToUserMapperTest.java +++ b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/UserDtoToUserMapperTest.java @@ -8,7 +8,6 @@ import org.mockito.Mock; import sonia.scm.user.User; import java.time.Instant; -import java.util.Optional; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; @@ -47,7 +46,7 @@ public class UserDtoToUserMapperTest { UserDto dto = new UserDto(); dto.setName("abc"); dto.setCreationDate(Instant.now()); - dto.setLastModified(Optional.empty()); + dto.setLastModified(null); return dto; } } diff --git a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/UserRootResourceTest.java b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/UserRootResourceTest.java index dbd69828b9..049d8ab1c8 100644 --- a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/UserRootResourceTest.java +++ b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/UserRootResourceTest.java @@ -21,7 +21,6 @@ import sonia.scm.user.UserManager; import sonia.scm.web.VndMediaType; import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.UriInfo; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; @@ -51,10 +50,7 @@ public class UserRootResourceTest { private Dispatcher dispatcher = MockDispatcherFactory.createDispatcher(); - @Mock - private UriInfo uriInfo; - @Mock - private UriInfoStore uriInfoStore; + private final ResourceLinks resourceLinks = ResourceLinksMock.createMock(URI.create("/")); @Mock private PasswordService passwordService; @@ -68,23 +64,21 @@ public class UserRootResourceTest { private ArgumentCaptor userCaptor = ArgumentCaptor.forClass(User.class); @Before - public void prepareEnvironment() throws IOException, UserException { + public void prepareEnvironment() throws UserException { initMocks(this); User dummyUser = createDummyUser("Neo"); - doNothing().when(userManager).create(userCaptor.capture()); + when(userManager.create(userCaptor.capture())).thenAnswer(invocation -> invocation.getArguments()[0]); doNothing().when(userManager).modify(userCaptor.capture()); doNothing().when(userManager).delete(userCaptor.capture()); - UserCollectionToDtoMapper userCollectionToDtoMapper = new UserCollectionToDtoMapper(userToDtoMapper, uriInfoStore); + UserCollectionToDtoMapper userCollectionToDtoMapper = new UserCollectionToDtoMapper(userToDtoMapper, resourceLinks); UserCollectionResource userCollectionResource = new UserCollectionResource(userManager, dtoToUserMapper, - userCollectionToDtoMapper); + userCollectionToDtoMapper, resourceLinks); UserResource userResource = new UserResource(dtoToUserMapper, userToDtoMapper, userManager); UserRootResource userRootResource = new UserRootResource(MockProvider.of(userCollectionResource), MockProvider.of(userResource)); dispatcher.getRegistry().addSingletonResource(userRootResource); - when(uriInfo.getBaseUri()).thenReturn(URI.create("/")); - when(uriInfoStore.get()).thenReturn(uriInfo); } @Test diff --git a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/UserToUserDtoMapperTest.java b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/UserToUserDtoMapperTest.java index d00f761702..330dd2a89e 100644 --- a/scm-webapp/src/test/java/sonia/scm/api/v2/resources/UserToUserDtoMapperTest.java +++ b/scm-webapp/src/test/java/sonia/scm/api/v2/resources/UserToUserDtoMapperTest.java @@ -8,13 +8,10 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; -import org.mockito.Mock; import sonia.scm.api.rest.resources.UserResource; import sonia.scm.user.User; -import javax.ws.rs.core.UriInfo; import java.net.URI; -import java.net.URISyntaxException; import java.time.Instant; import static org.junit.Assert.assertEquals; @@ -25,10 +22,9 @@ import static org.mockito.MockitoAnnotations.initMocks; public class UserToUserDtoMapperTest { - @Mock - private UriInfo uriInfo; - @Mock - private UriInfoStore uriInfoStore; + private final URI baseUri = URI.create("http://example.com/base/"); + @SuppressWarnings("unused") // Is injected + private final ResourceLinks resourceLinks = ResourceLinksMock.createMock(baseUri); @InjectMocks private UserToUserDtoMapperImpl mapper; @@ -39,12 +35,9 @@ public class UserToUserDtoMapperTest { private URI expectedBaseUri; @Before - public void init() throws URISyntaxException { + public void init() { initMocks(this); - URI baseUri = new URI("http://example.com/base/"); expectedBaseUri = baseUri.resolve(UserRootResource.USERS_PATH_V2 + "/"); - when(uriInfo.getBaseUri()).thenReturn(baseUri); - when(uriInfoStore.get()).thenReturn(uriInfo); subjectThreadState.bind(); ThreadContext.bind(subject); } @@ -125,6 +118,6 @@ public class UserToUserDtoMapperTest { UserDto userDto = mapper.map(user); assertEquals(expectedCreationDate, userDto.getCreationDate()); - assertEquals(expectedModificationDate, userDto.getLastModified().get()); + assertEquals(expectedModificationDate, userDto.getLastModified()); } } diff --git a/scm-webapp/src/test/java/sonia/scm/repository/DefaultNamespaceStrategyTest.java b/scm-webapp/src/test/java/sonia/scm/repository/DefaultNamespaceStrategyTest.java new file mode 100644 index 0000000000..dc40d1c1cb --- /dev/null +++ b/scm-webapp/src/test/java/sonia/scm/repository/DefaultNamespaceStrategyTest.java @@ -0,0 +1,24 @@ +package sonia.scm.repository; + +import com.github.sdorra.shiro.ShiroRule; +import com.github.sdorra.shiro.SubjectAware; +import org.junit.Rule; +import org.junit.Test; + +import static org.junit.Assert.*; + +@SubjectAware(configuration = "classpath:sonia/scm/shiro-001.ini") +public class DefaultNamespaceStrategyTest { + + @Rule + public ShiroRule shiroRule = new ShiroRule(); + + private DefaultNamespaceStrategy namespaceStrategy = new DefaultNamespaceStrategy(); + + @Test + @SubjectAware(username = "trillian", password = "secret") + public void testNamespaceStrategy() { + assertEquals("trillian", namespaceStrategy.getNamespace()); + } + +} diff --git a/scm-webapp/src/test/java/sonia/scm/repository/DefaultRepositoryManagerPerfTest.java b/scm-webapp/src/test/java/sonia/scm/repository/DefaultRepositoryManagerPerfTest.java index 90a78e63c6..665c54c9e1 100644 --- a/scm-webapp/src/test/java/sonia/scm/repository/DefaultRepositoryManagerPerfTest.java +++ b/scm-webapp/src/test/java/sonia/scm/repository/DefaultRepositoryManagerPerfTest.java @@ -33,13 +33,6 @@ package sonia.scm.repository; import com.google.common.base.Stopwatch; import com.google.common.collect.ImmutableSet; import com.google.inject.Provider; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.TimeUnit; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; @@ -58,7 +51,6 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import static org.mockito.Mockito.*; import org.mockito.runners.MockitoJUnitRunner; import sonia.scm.SCMContextProvider; import sonia.scm.Type; @@ -67,9 +59,19 @@ import sonia.scm.config.ScmConfiguration; import sonia.scm.security.AuthorizationCollector; import sonia.scm.security.DefaultKeyGenerator; import sonia.scm.security.KeyGenerator; -import sonia.scm.security.SecuritySystem; import sonia.scm.user.UserTestData; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + /** * Performance test for {@link RepositoryManager#getAll()}. * @@ -93,7 +95,7 @@ public class DefaultRepositoryManagerPerfTest { private final ScmConfiguration configuration = new ScmConfiguration(); private final KeyGenerator keyGenerator = new DefaultKeyGenerator(); - + @Mock private RepositoryHandler repositoryHandler; @@ -110,14 +112,15 @@ public class DefaultRepositoryManagerPerfTest { when(repositoryHandler.getType()).thenReturn(new Type(REPOSITORY_TYPE, REPOSITORY_TYPE)); Set handlerSet = ImmutableSet.of(repositoryHandler); RepositoryMatcher repositoryMatcher = new RepositoryMatcher(Collections.emptySet()); - + NamespaceStrategy namespaceStrategy = mock(NamespaceStrategy.class); repositoryManager = new DefaultRepositoryManager( configuration, contextProvider, keyGenerator, repositoryDAO, handlerSet, - repositoryMatcher + repositoryMatcher, + namespaceStrategy ); setUpTestRepositories(); @@ -127,10 +130,7 @@ public class DefaultRepositoryManagerPerfTest { ThreadContext.bind(securityManager); } - - /** - * Tear down test objects. - */ + @After public void tearDown(){ ThreadContext.unbindSecurityManager(); @@ -183,8 +183,8 @@ private long calculateAverage(List times) { when(repositoryDAO.getAll()).thenReturn(repositories.values()); } - private Repository createTestRepository(int number){ - Repository repository = new Repository(keyGenerator.createKey(), REPOSITORY_TYPE, "repo-" + number); + private Repository createTestRepository(int number) { + Repository repository = new Repository(keyGenerator.createKey(), REPOSITORY_TYPE, "namespace", "repo-" + number); repository.getPermissions().add(new Permission("trillian", PermissionType.READ)); return repository; } diff --git a/scm-webapp/src/test/java/sonia/scm/repository/DefaultRepositoryManagerTest.java b/scm-webapp/src/test/java/sonia/scm/repository/DefaultRepositoryManagerTest.java index 8c60e45b04..02b25c0735 100644 --- a/scm-webapp/src/test/java/sonia/scm/repository/DefaultRepositoryManagerTest.java +++ b/scm-webapp/src/test/java/sonia/scm/repository/DefaultRepositoryManagerTest.java @@ -31,45 +31,56 @@ package sonia.scm.repository; //~--- non-JDK imports -------------------------------------------------------- + import com.github.legman.Subscribe; import com.github.sdorra.shiro.ShiroRule; import com.github.sdorra.shiro.SubjectAware; import com.google.common.collect.ImmutableSet; - +import org.apache.shiro.authz.UnauthorizedException; +import org.junit.Rule; import org.junit.Test; - +import org.junit.rules.ExpectedException; +import org.mockito.invocation.InvocationOnMock; +import sonia.scm.HandlerEventType; +import sonia.scm.Manager; +import sonia.scm.ManagerTestBase; +import sonia.scm.ModelObject; import sonia.scm.Type; +import sonia.scm.TypedObject; import sonia.scm.config.ScmConfiguration; +import sonia.scm.event.ScmEventBus; import sonia.scm.repository.api.HookContext; import sonia.scm.repository.api.HookContextFactory; import sonia.scm.repository.api.HookFeature; import sonia.scm.repository.spi.HookContextProvider; import sonia.scm.repository.xml.XmlRepositoryDAO; import sonia.scm.security.DefaultKeyGenerator; +import sonia.scm.security.KeyGenerator; +import sonia.scm.store.ConfigurationStoreFactory; import sonia.scm.store.JAXBConfigurationStoreFactory; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; -import static org.hamcrest.Matchers.*; - -//~--- JDK imports ------------------------------------------------------------ -import java.io.IOException; import java.util.Collection; import java.util.Collections; - import java.util.HashSet; import java.util.Set; import java.util.Stack; -import org.apache.shiro.authz.UnauthorizedException; -import org.junit.Rule; -import org.junit.rules.ExpectedException; -import org.mockito.invocation.InvocationOnMock; -import sonia.scm.HandlerEventType; -import sonia.scm.Manager; -import sonia.scm.ManagerTestBase; -import sonia.scm.event.ScmEventBus; -import sonia.scm.security.KeyGenerator; -import sonia.scm.store.ConfigurationStoreFactory; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +//~--- JDK imports ------------------------------------------------------------ /** * Unit tests for {@link DefaultRepositoryManager}. @@ -89,14 +100,12 @@ public class DefaultRepositoryManagerTest extends ManagerTestBase keys = new Stack<>(); @@ -325,14 +268,8 @@ public class DefaultRepositoryManagerTest extends ManagerTestBase mockedNamespace); + return new DefaultRepositoryManager(configuration, contextProvider, - keyGenerator, repositoryDAO, handlerSet, createRepositoryMatcher()); + keyGenerator, repositoryDAO, handlerSet, createRepositoryMatcher(), namespaceStrategy); } private void createRepository(RepositoryManager m, Repository repository) - throws RepositoryException, IOException { + throws RepositoryException { m.create(repository); } @@ -573,7 +535,7 @@ public class DefaultRepositoryManagerTest extends ManagerTestBaseemptySet()); } - private Repository createRepository(Repository repository) throws RepositoryException, IOException { + private Repository createRepository(Repository repository) throws RepositoryException { manager.create(repository); assertNotNull(repository.getId()); assertNotNull(manager.get(repository.getId())); @@ -588,17 +550,17 @@ public class DefaultRepositoryManagerTest extends ManagerTestBase manager, Repository repository) - throws RepositoryException, IOException { + throws RepositoryException { String id = repository.getId(); diff --git a/scm-webapp/src/test/java/sonia/scm/repository/RepositoryMatcherTest.java b/scm-webapp/src/test/java/sonia/scm/repository/RepositoryMatcherTest.java index c832bb8691..1d6371074c 100644 --- a/scm-webapp/src/test/java/sonia/scm/repository/RepositoryMatcherTest.java +++ b/scm-webapp/src/test/java/sonia/scm/repository/RepositoryMatcherTest.java @@ -31,10 +31,13 @@ package sonia.scm.repository; import com.google.common.collect.Sets; -import java.util.Set; -import org.junit.Test; -import static org.junit.Assert.*; import org.junit.Before; +import org.junit.Test; + +import java.util.Set; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; /** * Unit tests for {@link RepositoryMatcher}. @@ -54,11 +57,11 @@ public class RepositoryMatcherTest { @Test public void testMatches() { - assertFalse(matcher.matches(repository("hg", "scm"), "hg", "scm-test/ka")); - assertFalse(matcher.matches(repository("git", "scm-test"), "hg", "scm-test")); + assertFalse(matcher.matches(repository("hg", "scm"), "hg", "namespace/scm-test/ka")); + assertFalse(matcher.matches(repository("git", "scm-test"), "hg", "namespace/scm-test")); - assertTrue(matcher.matches(repository("hg", "scm-test"), "hg", "scm-test/ka")); - assertTrue(matcher.matches(repository("hg", "scm-test"), "hg", "scm-test")); + assertTrue(matcher.matches(repository("hg", "scm-test"), "hg", "namespace/scm-test/ka")); + assertTrue(matcher.matches(repository("hg", "scm-test"), "hg", "namespace/scm-test")); } @Test @@ -68,7 +71,7 @@ public class RepositoryMatcherTest { } private Repository repository(String type, String name) { - return new Repository(type + "-" + name, type, name); + return new Repository(type + "-" + name, type, "namespace", name); } private static class AbcRepositoryPathMatcher implements RepositoryPathMatcher { diff --git a/scm-webapp/src/test/resources/sonia/scm/api/v2/group-test-update.json b/scm-webapp/src/test/resources/sonia/scm/api/v2/group-test-update.json new file mode 100644 index 0000000000..fd41ff5837 --- /dev/null +++ b/scm-webapp/src/test/resources/sonia/scm/api/v2/group-test-update.json @@ -0,0 +1,11 @@ +{ + "description": "Updated description", + "name": "admin", + "_embedded": { + "members": [ + { + "name": "user" + } + ] + } +} diff --git a/scm-webapp/src/test/resources/sonia/scm/api/v2/repository-test-update.json b/scm-webapp/src/test/resources/sonia/scm/api/v2/repository-test-update.json new file mode 100644 index 0000000000..660fa256bf --- /dev/null +++ b/scm-webapp/src/test/resources/sonia/scm/api/v2/repository-test-update.json @@ -0,0 +1,8 @@ +{ + "contact": "none@example.com", + "description": "Test repository", + "namespace": "space", + "name": "repo", + "archived": false, + "type": "git" +}