From a89104d4db06405267317d07fe7ab0f57df0b999 Mon Sep 17 00:00:00 2001 From: David Mason Date: Tue, 14 Oct 2014 14:34:48 +1000 Subject: [PATCH 01/55] [mvn-release-plugin] Prepare for next development iteration. --- pom.xml | 2 +- zanata-cli/pom.xml | 2 +- zanata-client-commands/pom.xml | 2 +- zanata-maven-plugin/pom.xml | 2 +- zanata-rest-client/pom.xml | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pom.xml b/pom.xml index 368ab470..f5e23c19 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 client - 3.4.0-SNAPSHOT + 3.6.0-SNAPSHOT Zanata client modules pom diff --git a/zanata-cli/pom.xml b/zanata-cli/pom.xml index d609b76c..9e91baef 100644 --- a/zanata-cli/pom.xml +++ b/zanata-cli/pom.xml @@ -4,7 +4,7 @@ org.zanata client - 3.4.0-SNAPSHOT + 3.6.0-SNAPSHOT zanata-cli Zanata command-line client diff --git a/zanata-client-commands/pom.xml b/zanata-client-commands/pom.xml index 26cac126..9659cd8f 100644 --- a/zanata-client-commands/pom.xml +++ b/zanata-client-commands/pom.xml @@ -4,7 +4,7 @@ org.zanata client - 3.4.0-SNAPSHOT + 3.6.0-SNAPSHOT zanata-client-commands Zanata client commands diff --git a/zanata-maven-plugin/pom.xml b/zanata-maven-plugin/pom.xml index f1355107..f6675664 100644 --- a/zanata-maven-plugin/pom.xml +++ b/zanata-maven-plugin/pom.xml @@ -4,7 +4,7 @@ org.zanata client - 3.4.0-SNAPSHOT + 3.6.0-SNAPSHOT zanata-maven-plugin diff --git a/zanata-rest-client/pom.xml b/zanata-rest-client/pom.xml index 05b74f5b..0559ec2a 100644 --- a/zanata-rest-client/pom.xml +++ b/zanata-rest-client/pom.xml @@ -6,7 +6,7 @@ org.zanata client - 3.4.0-SNAPSHOT + 3.6.0-SNAPSHOT jar From 80c16a1cacae082f703fe92b8a4651091bf7f61a Mon Sep 17 00:00:00 2001 From: Sean Flanigan Date: Wed, 5 Nov 2014 16:55:01 +1000 Subject: [PATCH 02/55] Travis: enable static analysis; resolve dependencies earlier --- .travis.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 737d6d7f..240027ec 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,8 @@ language: java -install: true -script: mvn --batch-mode --settings settings.xml test -Dgwt.validateOnly -Darquillian.jboss.home=/dev/null +# Attempt to resolve dependencies without actually compiling +# See http://docs.travis-ci.com/user/languages/java/#Dependency-Management +install: mvn dependency:resolve dependency:resolve-plugins dependency:go-offline +script: mvn --batch-mode --settings settings.xml test -Dgwt.validateOnly -Darquillian.jboss.home=/dev/null -DstaticAnalysis jdk: - openjdk7 - oraclejdk7 @@ -8,5 +10,3 @@ jdk: matrix: fast_finish: true -# allow_failures: -# - jdk: oraclejdk8 From 17709fa0c5928e28bd67dd23fb9694814c8fe6db Mon Sep 17 00:00:00 2001 From: Sean Flanigan Date: Wed, 5 Nov 2014 17:06:00 +1000 Subject: [PATCH 03/55] Try to speed up Travis builds a little --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 240027ec..58aabc17 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ language: java -# Attempt to resolve dependencies without actually compiling +# Attempt to resolve most dependencies without actually compiling # See http://docs.travis-ci.com/user/languages/java/#Dependency-Management -install: mvn dependency:resolve dependency:resolve-plugins dependency:go-offline +install: travis_wait mvn dependency:resolve script: mvn --batch-mode --settings settings.xml test -Dgwt.validateOnly -Darquillian.jboss.home=/dev/null -DstaticAnalysis jdk: - openjdk7 From 167ef743ad24e8c17745c1d44c5725dc81b48e92 Mon Sep 17 00:00:00 2001 From: Sean Flanigan Date: Wed, 5 Nov 2014 17:29:33 +1000 Subject: [PATCH 04/55] Disable dependency prefetch, rename settings.xml to .travis-settings.xml --- settings.xml => .travis-settings.xml | 0 .travis.yml | 15 ++++++++++++--- 2 files changed, 12 insertions(+), 3 deletions(-) rename settings.xml => .travis-settings.xml (100%) diff --git a/settings.xml b/.travis-settings.xml similarity index 100% rename from settings.xml rename to .travis-settings.xml diff --git a/.travis.yml b/.travis.yml index 58aabc17..adf214d4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,8 +1,17 @@ language: java -# Attempt to resolve most dependencies without actually compiling + +# Use the 'true' command to avoid up-front dependency fetching, for faster builds # See http://docs.travis-ci.com/user/languages/java/#Dependency-Management -install: travis_wait mvn dependency:resolve -script: mvn --batch-mode --settings settings.xml test -Dgwt.validateOnly -Darquillian.jboss.home=/dev/null -DstaticAnalysis +install: true + +script: | + mvn test \ + --batch-mode \ + --settings .travis-settings.xml \ + -Darquillian.jboss.home=/dev/null \ + -Dgwt.validateOnly \ + -DstaticAnalysis + jdk: - openjdk7 - oraclejdk7 From 1d992f87ae34158aad1c26194fff7d4848780253 Mon Sep 17 00:00:00 2001 From: Patrick Huang Date: Mon, 17 Nov 2014 15:46:05 +1000 Subject: [PATCH 05/55] remove deprecated publican push and pull commands --- .../client/commands/PublicanPullCommand.java | 134 --------- .../client/commands/PublicanPullOptions.java | 35 --- .../commands/PublicanPullOptionsImpl.java | 76 ----- .../client/commands/PublicanPushCommand.java | 269 ------------------ .../client/commands/PublicanPushOptions.java | 26 -- .../commands/PublicanPushOptionsImpl.java | 131 --------- .../client/commands/gettext/PublicanUtil.java | 27 -- .../pull/PublicanPullCommandTest.java | 141 --------- .../push/PublicanPushCommandTest.java | 125 -------- .../org/zanata/maven/PublicanPullMojo.java | 92 ------ .../org/zanata/maven/PublicanPushMojo.java | 125 -------- 11 files changed, 1181 deletions(-) delete mode 100644 zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPullCommand.java delete mode 100644 zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPullOptions.java delete mode 100644 zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPullOptionsImpl.java delete mode 100644 zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPushCommand.java delete mode 100644 zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPushOptions.java delete mode 100644 zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPushOptionsImpl.java delete mode 100644 zanata-client-commands/src/test/java/org/zanata/client/commands/pull/PublicanPullCommandTest.java delete mode 100644 zanata-client-commands/src/test/java/org/zanata/client/commands/push/PublicanPushCommandTest.java delete mode 100644 zanata-maven-plugin/src/main/java/org/zanata/maven/PublicanPullMojo.java delete mode 100644 zanata-maven-plugin/src/main/java/org/zanata/maven/PublicanPushMojo.java diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPullCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPullCommand.java deleted file mode 100644 index 4e22c1e6..00000000 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPullCommand.java +++ /dev/null @@ -1,134 +0,0 @@ -package org.zanata.client.commands; - -import java.net.URI; -import java.util.List; - -import javax.ws.rs.core.Response; - -import org.jboss.resteasy.client.ClientResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.zanata.adapter.po.PoWriter2; -import org.zanata.client.config.LocaleList; -import org.zanata.client.config.LocaleMapping; -import org.zanata.client.exceptions.ConfigException; -import org.zanata.common.LocaleId; -import org.zanata.rest.RestUtil; -import org.zanata.rest.StringSet; -import org.zanata.rest.client.ClientUtility; -import org.zanata.rest.client.ISourceDocResource; -import org.zanata.rest.client.ITranslatedDocResource; -import org.zanata.rest.client.ZanataProxyFactory; -import org.zanata.rest.dto.resource.Resource; -import org.zanata.rest.dto.resource.ResourceMeta; -import org.zanata.rest.dto.resource.TranslationsResource; - -/** - * @author Sean Flanigan sflaniga@redhat.com - * - * @deprecated - * @see org.zanata.client.commands.pull.PullCommand - */ -public class PublicanPullCommand extends - ConfigurableProjectCommand { - private static final Logger log = LoggerFactory - .getLogger(PublicanPullCommand.class); - - private final ISourceDocResource sourceDocResource; - private final ITranslatedDocResource translationResources; - private final URI uri; - - public PublicanPullCommand(PublicanPullOptions opts, - ZanataProxyFactory factory, ISourceDocResource sourceDocResource, - ITranslatedDocResource translationResources, URI uri) { - super(opts, factory); - this.sourceDocResource = sourceDocResource; - this.translationResources = translationResources; - this.uri = uri; - deprecate("please use \"pull\" with project type \"" - + PROJECT_TYPE_PUBLICAN + "\""); - } - - private PublicanPullCommand(PublicanPullOptions opts, - ZanataProxyFactory factory) { - this(opts, factory, factory.getSourceDocResource(opts.getProj(), - opts.getProjectVersion()), factory.getTranslatedDocResource( - opts.getProj(), opts.getProjectVersion()), factory - .getResourceURI(opts.getProj(), opts.getProjectVersion())); - } - - public PublicanPullCommand(PublicanPullOptions opts) { - this(opts, OptionsUtil.createRequestFactory(opts)); - } - - @Override - protected String getProjectType() { - return PROJECT_TYPE_PUBLICAN; - } - - @Override - public void run() throws Exception { - log.info("Server: {}", getOpts().getUrl()); - log.info("Project: {}", getOpts().getProj()); - log.info("Version: {}", getOpts().getProjectVersion()); - log.info("Username: {}", getOpts().getUsername()); - if (getOpts().getExportPot()) { - log.info("Exporting source and target (translation) documents"); - log.info("POT directory (originals): {}", getOpts().getDstDirPot()); - } else { - log.info("Exporting target documents (translations) only"); - } - log.info("PO base directory (translations): {}", getOpts().getDstDir()); - - LocaleList locales = getOpts().getLocaleMapList(); - if (locales == null) - throw new ConfigException("no locales specified"); - PoWriter2 poWriter = new PoWriter2(); - StringSet extensions = new StringSet("gettext;comment"); - - ClientResponse> listResponse = - sourceDocResource.get(null); - ClientUtility.checkResult(listResponse, uri); - List resourceMetaList = listResponse.getEntity(); - for (ResourceMeta resourceMeta : resourceMetaList) { - String docName = resourceMeta.getName(); - // TODO follow a Link - String docUri = RestUtil.convertToDocumentURIId(docName); - ClientResponse resourceResponse = - sourceDocResource.getResource(docUri, extensions); - ClientUtility.checkResult(resourceResponse, uri); - Resource doc = resourceResponse.getEntity(); - if (getOpts().getExportPot()) { - log.info("writing POT for document {}", docName); - poWriter.writePotToDir(getOpts().getDstDirPot(), doc); - } - - for (LocaleMapping locMapping : locales) { - LocaleId locale = new LocaleId(locMapping.getLocale()); - - ClientResponse transResponse = - translationResources.getTranslations(docUri, locale, - extensions); - // ignore 404 (no translation yet for specified document) - if (transResponse.getResponseStatus() == Response.Status.NOT_FOUND) { - log.info( - "no translations found in locale {} for document {}", - locale, docName); - continue; - } - ClientUtility.checkResult(transResponse, uri); - TranslationsResource targetDoc = transResponse.getEntity(); - - String localeDir = locMapping.getLocalLocale(); - log.info( - "writing PO translations in locale {} for document {}", - locale, docName); - poWriter.writePo(getOpts().getDstDir(), doc, localeDir, - targetDoc); - } - } - - } - -} diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPullOptions.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPullOptions.java deleted file mode 100644 index 3825c5ca..00000000 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPullOptions.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.zanata.client.commands; - -import java.io.File; - -import org.kohsuke.args4j.Option; - -/** - * @author Sean Flanigan sflaniga@redhat.com - * - * @deprecated - * @see org.zanata.client.commands.pull.PullOptions - */ -public interface PublicanPullOptions extends ConfigurableProjectOptions { - - @Option( - aliases = { "-d" }, - name = "--dst", - metaVar = "DIR", - required = true, - usage = "Base directory for publican files (with subdirectory \"pot\" and locale directories)") - public - void setDstDir(File dstDir); - - public void setDstDirPot(File dstDirPot); - - public File getDstDir(); - - public File getDstDirPot(); - - boolean getExportPot(); - - void setExportPot(boolean exportPot); - -} diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPullOptionsImpl.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPullOptionsImpl.java deleted file mode 100644 index 8a4ebb8d..00000000 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPullOptionsImpl.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.zanata.client.commands; - -import java.io.File; - -import org.kohsuke.args4j.Option; - -/** - * @author Sean Flanigan sflaniga@redhat.com - * - * @deprecated - * @see org.zanata.client.commands.pull.PullOptions - */ -public class PublicanPullOptionsImpl extends ConfigurableProjectOptionsImpl - implements PublicanPullOptions { - private File dstDir; - private File dstDirPot; - private boolean exportPot; - - @Override - public ZanataCommand initCommand() { - return new PublicanPullCommand(this); - } - - @Override - public String getCommandName() { - return "publican-pull"; - } - - @Override - public String getCommandDescription() { - return "Pulls translated text from Zanata. DEPRECATED: use 'pull' with projectType 'podir'"; - } - - @Option( - aliases = { "-d" }, - name = "--dst", - metaVar = "DIR", - required = true, - usage = "Base directory for publican files (with subdirectory \"pot\" and locale directories)") - @Override - public - void setDstDir(File dstDir) { - this.dstDir = dstDir; - if (dstDirPot == null) - dstDirPot = new File(dstDir, "pot"); - } - - @Override - public File getDstDir() { - return dstDir; - } - - @Override - public void setDstDirPot(File dstDirPot) { - this.dstDirPot = dstDirPot; - } - - @Override - public File getDstDirPot() { - return dstDirPot; - } - - @Override - public boolean getExportPot() { - return exportPot; - } - - @Override - @Option(name = "--export-pot", - usage = "Export source text from Zanata to local POT files") - public void setExportPot(boolean exportPot) { - this.exportPot = exportPot; - } - -} diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPushCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPushCommand.java deleted file mode 100644 index 3f4a2ce6..00000000 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPushCommand.java +++ /dev/null @@ -1,269 +0,0 @@ -package org.zanata.client.commands; - -import java.io.BufferedInputStream; -import java.io.Console; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.StringWriter; -import java.net.URI; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Marshaller; - -import org.apache.commons.io.filefilter.AndFileFilter; -import org.jboss.resteasy.client.ClientResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.xml.sax.InputSource; -import org.zanata.adapter.po.PoReader2; -import org.zanata.client.commands.gettext.PublicanUtil; -import org.zanata.client.config.LocaleMapping; -import org.zanata.common.LocaleId; -import org.zanata.rest.JaxbUtil; -import org.zanata.rest.RestUtil; -import org.zanata.rest.StringSet; -import org.zanata.rest.client.ClientUtility; -import org.zanata.rest.client.ISourceDocResource; -import org.zanata.rest.client.ITranslatedDocResource; -import org.zanata.rest.client.ZanataProxyFactory; -import org.zanata.rest.dto.resource.Resource; -import org.zanata.rest.dto.resource.ResourceMeta; -import org.zanata.rest.dto.resource.TranslationsResource; - -/** - * @author Sean Flanigan sflaniga@redhat.com - * - * @deprecated - * @see org.zanata.client.commands.push.PushCommand - */ -public class PublicanPushCommand extends - ConfigurableProjectCommand { - private static final Logger log = LoggerFactory - .getLogger(PublicanPushCommand.class); - - private final ISourceDocResource sourceDocResource; - private final ITranslatedDocResource translationResources; - private final URI uri; - - public PublicanPushCommand(PublicanPushOptions opts, - ZanataProxyFactory factory, ISourceDocResource sourceDocResource, - ITranslatedDocResource translationResources, URI uri) { - super(opts, factory); - this.sourceDocResource = sourceDocResource; - this.translationResources = translationResources; - this.uri = uri; - deprecate("please use \"push\" with project type \"" - + PROJECT_TYPE_PUBLICAN + "\""); - } - - private PublicanPushCommand(PublicanPushOptions opts, - ZanataProxyFactory factory) { - this(opts, factory, factory.getSourceDocResource(opts.getProj(), - opts.getProjectVersion()), factory.getTranslatedDocResource( - opts.getProj(), opts.getProjectVersion()), factory - .getResourceURI(opts.getProj(), opts.getProjectVersion())); - } - - public PublicanPushCommand(PublicanPushOptions opts) { - this(opts, OptionsUtil.createRequestFactory(opts)); - } - - @Override - protected String getProjectType() { - return PROJECT_TYPE_PUBLICAN; - } - - @Override - public void run() throws Exception { - log.info("Server: {}", getOpts().getUrl()); - log.info("Project: {}", getOpts().getProj()); - log.info("Version: {}", getOpts().getProjectVersion()); - log.info("Username: {}", getOpts().getUsername()); - log.info("Source language: {}", getOpts().getSourceLang()); - log.info("Copy previous translations: {}", getOpts().getCopyTrans()); - log.info("Merge type: {}", getOpts().getMergeType()); - if (getOpts().getImportPo()) { - log.info("Importing source and target documents"); - } else { - log.info("Importing source documents only"); - } - log.info("POT directory (originals): {}", getOpts().getSrcDirPot()); - if (getOpts().getImportPo()) { - log.info("PO base directory (translations): {}", getOpts() - .getSrcDir()); - } - File potDir = getOpts().getSrcDirPot(); - - if (!potDir.exists()) { - throw new RuntimeException("directory '" + potDir - + "' does not exist - check srcDir and srcDirPot options"); - } - - Console console = System.console(); - if (getOpts().isInteractiveMode()) { - if (console == null) - throw new RuntimeException( - "console not available: please run maven from a console, or use batch mode (mvn -B)"); - } - - if (getOpts().getImportPo()) { - log.warn("importPo option is set: existing translations on server will be overwritten/deleted"); - if (getOpts().isInteractiveMode()) { - console.printf("This will overwrite/delete any existing documents AND TRANSLATIONS on the server.\n"); - console.printf("Are you sure (y/n)? "); - expectYes(console); - } - } else if (getOpts().isInteractiveMode()) { - console.printf("This will overwrite/delete any existing documents on the server.\n"); - console.printf("Are you sure (y/n)? "); - expectYes(console); - } - - JAXBContext jc = null; - if (log.isDebugEnabled() || getOpts().getValidate()) { - jc = - JAXBContext.newInstance(Resource.class, - TranslationsResource.class); - } - Marshaller m = null; - if (log.isDebugEnabled()) { - m = jc.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); - } - - // NB we don't load all the docs into a HashMap, because that would - // waste - // memory - Set localDocNames = new HashSet(); - // populate localDocNames by looking in pot directory - - String[] potFiles = - PublicanUtil.findPotFiles(potDir, new AndFileFilter()); - for (String potName : potFiles) { - String docName = StringUtil.removeFileExtension(potName, ".pot"); - localDocNames.add(docName); - } - - ClientResponse> getResponse = - sourceDocResource.get(null); - ClientUtility.checkResult(getResponse, uri); - List remoteDocList = getResponse.getEntity(); - for (ResourceMeta doc : remoteDocList) { - // NB ResourceMeta.name = HDocument.docId - String docName = doc.getName(); - String docUri = RestUtil.convertToDocumentURIId(docName); - if (!localDocNames.contains(docName)) { - log.info("deleting resource {} from server", docName); - ClientResponse deleteResponse = - sourceDocResource.deleteResource(docUri); - ClientUtility.checkResult(deleteResponse, uri); - } - } - List locales = null; - if (getOpts().getImportPo()) { - if (getOpts().getLocaleMapList() != null) { - locales = - PublicanUtil.findLocales(getOpts().getSrcDir(), - getOpts().getLocaleMapList()); - if (locales.size() == 0) { - log.warn("option 'importPo' is set, but none of the configured locale directories was found (check zanata.xml)"); - } - } else { - locales = PublicanUtil.findLocales(getOpts().getSrcDir()); - if (locales.size() == 0) { - log.warn("option 'importPo' is set, but no locale directories were found"); - } else { - log.info("option 'importPo' is set, but no locales specified in configuration: importing " - + locales.size() + " directories"); - } - } - } - - PoReader2 poReader = new PoReader2(); - for (String docName : localDocNames) { - String docUri = RestUtil.convertToDocumentURIId(docName); - File potFile = new File(potDir, docName + ".pot"); - Resource srcDoc; - BufferedInputStream bis = - new BufferedInputStream(new FileInputStream(potFile)); - try { - InputSource potInputSource = new InputSource(bis); - potInputSource.setEncoding("utf8"); - // load 'srcDoc' from pot/${docID}.pot - srcDoc = - poReader.extractTemplate(potInputSource, new LocaleId( - getOpts().getSourceLang()), docName); - } finally { - bis.close(); - } - if (log.isDebugEnabled()) { - StringWriter writer = new StringWriter(); - m.marshal(srcDoc, writer); - log.debug("{}", writer); - } - if (getOpts().getValidate()) { - JaxbUtil.validateXml(srcDoc, jc); - } - StringSet extensions = new StringSet("comment;gettext"); - log.info("pushing source document [name={}] to server", - srcDoc.getName()); - boolean copyTrans = getOpts().getCopyTrans(); - ClientResponse putResponse = - sourceDocResource.putResource(docUri, srcDoc, extensions, - copyTrans); - ClientUtility.checkResult(putResponse, uri); - - if (getOpts().getImportPo()) { - for (LocaleMapping locale : locales) { - File localeDir = - new File(getOpts().getSrcDir(), - locale.getLocalLocale()); - File poFile = new File(localeDir, docName + ".po"); - if (poFile.canRead()) { - TranslationsResource targetDoc; - BufferedInputStream bis2 = - new BufferedInputStream(new FileInputStream( - poFile)); - try { - InputSource inputSource = new InputSource(bis2); - inputSource.setEncoding("utf8"); - targetDoc = poReader.extractTarget(inputSource); - } finally { - bis2.close(); - } - if (log.isDebugEnabled()) { - StringWriter writer = new StringWriter(); - m.marshal(targetDoc, writer); - log.debug("{}", writer); - } - if (getOpts().getValidate()) { - JaxbUtil.validateXml(targetDoc, jc); - } - log.info( - "pushing target document [name={} client-locale={}] to server [locale={}]", - new Object[] { srcDoc.getName(), - locale.getLocalLocale(), - locale.getLocale() }); - ClientResponse putTransResponse = - translationResources.putTranslations(docUri, - new LocaleId(locale.getLocale()), - targetDoc, extensions, getOpts() - .getMergeType()); - ClientUtility.checkResult(putTransResponse, uri); - String entity = - putTransResponse.getEntity(String.class); - if (entity != null && !entity.isEmpty()) { - log.warn("{}", entity); - } - } - } - } - } - } - -} diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPushOptions.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPushOptions.java deleted file mode 100644 index a68f048f..00000000 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPushOptions.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.zanata.client.commands; - -import java.io.File; - -/** - * - * @author Sean Flanigan sflaniga@redhat.com - * @deprecated - * @see org.zanata.client.commands.push.PushOptions - */ -public interface PublicanPushOptions extends ConfigurableProjectOptions { - public File getSrcDir(); - - public File getSrcDirPot(); - - public String getSourceLang(); - - public boolean getImportPo(); - - public boolean getCopyTrans(); - - public boolean getValidate(); - - public String getMergeType(); -} diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPushOptionsImpl.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPushOptionsImpl.java deleted file mode 100644 index 5263e035..00000000 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/PublicanPushOptionsImpl.java +++ /dev/null @@ -1,131 +0,0 @@ -package org.zanata.client.commands; - -import java.io.File; - -import org.kohsuke.args4j.Option; - -/** - * @author Sean Flanigan sflaniga@redhat.com - * - * @deprecated - * @see org.zanata.client.commands.push.PushOptions - */ -public class PublicanPushOptionsImpl extends ConfigurableProjectOptionsImpl - implements PublicanPushOptions { - private File srcDir; - private File srcDirPot; - - private String sourceLang = "en-US"; - - private boolean importPo; - private boolean copyTrans = true; - private boolean validate; - private String mergeType = "auto"; - - public PublicanPushOptionsImpl() { - super(); - } - - @Override - public String getCommandName() { - return "publican-push"; - } - - @Override - public String getCommandDescription() { - return "Publishes publican source text to Zanata so that it can be translated. DEPRECATED: use 'push' with projectType 'podir'"; - } - - @Override - public PublicanPushCommand initCommand() { - return new PublicanPushCommand(this); - } - - @Option( - aliases = { "-s" }, - name = "--src", - metaVar = "DIR", - required = true, - usage = "Base directory for publican files (with subdirectory \"pot\" and optional locale directories)") - public - void setSrcDir(File srcDir) { - this.srcDir = srcDir; - if (srcDirPot == null) - srcDirPot = new File(srcDir, "pot"); - } - - @Option( - name = "--src-pot", - metaVar = "DIR", - required = false, - usage = "Override base directory for publican POT files (defaults to \"pot\" under --src directory)") - public - void setSrcDirPot(File srcDirPot) { - this.srcDirPot = srcDirPot; - } - - @Option(aliases = { "-l" }, name = "--src-lang", - usage = "Language of source (defaults to en-US)") - public void setSourceLang(String sourceLang) { - this.sourceLang = sourceLang; - } - - @Option( - name = "--import-po", - usage = "Import translations from local PO files to Zanata, overwriting or erasing existing translations (DANGER!)") - public - void setImportPo(boolean importPo) { - this.importPo = importPo; - } - - @Option(name = "--validate", - usage = "Validate XML before sending request to server") - public void setValidate(boolean validate) { - this.validate = validate; - } - - @Override - public boolean getValidate() { - return validate; - } - - @Override - public boolean getImportPo() { - return importPo; - } - - @Override - public boolean getCopyTrans() { - return copyTrans; - } - - @Option( - name = "--no-copy-trans", - usage = "Don't copy latest translation from equivalent documents from other versions of the same project") - public - void setNoCopyTrans(boolean noCopyTrans) { - this.copyTrans = !noCopyTrans; - } - - @Override - public File getSrcDir() { - return srcDir; - } - - @Override - public File getSrcDirPot() { - return srcDirPot; - } - - @Override - public String getSourceLang() { - return sourceLang; - } - - @Override - public String getMergeType() { - return mergeType; - } - -} diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/gettext/PublicanUtil.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/gettext/PublicanUtil.java index cc32272f..7cb92b76 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/gettext/PublicanUtil.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/gettext/PublicanUtil.java @@ -2,21 +2,13 @@ import java.io.File; import java.io.FileFilter; -import java.io.IOException; import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; import java.util.List; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.filefilter.AndFileFilter; -import org.apache.commons.io.filefilter.SuffixFileFilter; -import org.apache.commons.io.filefilter.TrueFileFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zanata.client.config.LocaleList; import org.zanata.client.config.LocaleMapping; -import org.zanata.util.PathUtil; /** * @@ -31,25 +23,6 @@ public class PublicanUtil { private PublicanUtil() { } - public static String[] findPotFiles(File potDir, AndFileFilter fileFilter) - throws IOException { - SuffixFileFilter extensionFilter = new SuffixFileFilter(".pot"); - fileFilter.addFileFilter(extensionFilter); - - Collection files = - FileUtils.listFiles(potDir, fileFilter, TrueFileFilter.TRUE); - - String[] potFiles = new String[files.size()]; - Iterator iter = files.iterator(); - - for (int i = 0; i < potFiles.length; i++) { - File potFile = iter.next(); - String relativePath = PathUtil.getSubPath(potFile, potDir); - potFiles[i] = relativePath; - } - return potFiles; - } - public static File[] findLocaleDirs(File srcDir) { File[] localeDirs; localeDirs = srcDir.listFiles(new FileFilter() { diff --git a/zanata-client-commands/src/test/java/org/zanata/client/commands/pull/PublicanPullCommandTest.java b/zanata-client-commands/src/test/java/org/zanata/client/commands/pull/PublicanPullCommandTest.java deleted file mode 100644 index 4fc46830..00000000 --- a/zanata-client-commands/src/test/java/org/zanata/client/commands/pull/PublicanPullCommandTest.java +++ /dev/null @@ -1,141 +0,0 @@ -package org.zanata.client.commands.pull; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -import javax.ws.rs.core.Response.Status; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.zanata.client.commands.DummyResponse; -import org.zanata.client.commands.OptionsUtil; -import org.zanata.client.commands.PublicanPullCommand; -import org.zanata.client.commands.PublicanPullOptions; -import org.zanata.client.commands.PublicanPullOptionsImpl; -import org.zanata.client.commands.ZanataCommand; -import org.zanata.client.config.LocaleList; -import org.zanata.client.config.LocaleMapping; -import org.zanata.common.LocaleId; -import org.zanata.rest.RestUtil; -import org.zanata.rest.StringSet; -import org.zanata.rest.client.ISourceDocResource; -import org.zanata.rest.client.ITranslatedDocResource; -import org.zanata.rest.client.ZanataProxyFactory; -import org.zanata.rest.dto.resource.Resource; -import org.zanata.rest.dto.resource.ResourceMeta; -import org.zanata.rest.dto.resource.TranslationsResource; - -public class PublicanPullCommandTest { - @Mock - private ISourceDocResource mockSourceDocResource; - - @Mock - private ITranslatedDocResource mockTranslationResources; - - @Before - public void beforeMethod() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void publicanPullPo() throws Exception { - publicanPull(false, false); - } - - @Test - public void publicanPullPotAndPo() throws Exception { - publicanPull(true, false); - } - - @Test - public void publicanPullPotAndPoWithLocaleMapping() throws Exception { - publicanPull(true, true); - } - - @SuppressWarnings("deprecation") - private void publicanPull(boolean exportPot, boolean mapLocale) - throws Exception { - PublicanPullOptions opts = new PublicanPullOptionsImpl(); - String projectSlug = "project"; - opts.setProj(projectSlug); - String versionSlug = "1.0"; - opts.setProjectVersion(versionSlug); - opts.setDstDir(new File("target/test-output/test2")); - opts.setExportPot(exportPot); - opts.setProjectConfig(new File("src/test/resources/test2/zanata.xml")); - opts.setLocaleMapList(new LocaleList()); - OptionsUtil.applyConfigFiles(opts); - if (mapLocale) { - LocaleList locales = new LocaleList(); - locales.add(new LocaleMapping("ja", "ja-JP")); - opts.setLocaleMapList(locales); - } - - List resourceMetaList = new ArrayList(); - resourceMetaList.add(new ResourceMeta("RPM")); - resourceMetaList.add(new ResourceMeta("sub/RPM")); - - when(mockSourceDocResource.get(null)).thenReturn( - new DummyResponse>(Status.OK, - resourceMetaList)); - - Resource rpmResource = new Resource("RPM"); - - StringSet ext = new StringSet("comment;gettext"); - when( - mockSourceDocResource.getResource( - RestUtil.convertToDocumentURIId(rpmResource.getName()), - ext)).thenReturn( - new DummyResponse(Status.OK, rpmResource)); - - Resource subRpmResource = new Resource("sub/RPM"); - when( - mockSourceDocResource.getResource(RestUtil - .convertToDocumentURIId(subRpmResource.getName()), ext)) - .thenReturn( - new DummyResponse(Status.OK, subRpmResource)); - - LocaleId expectedLocale; - if (mapLocale) - expectedLocale = new LocaleId("ja"); - else - expectedLocale = new LocaleId("ja-JP"); - TranslationsResource rpmTransJa = new TranslationsResource(); - mockExpectGetTranslationsAndReturnResponse("RPM", expectedLocale, - rpmTransJa); - mockExpectGetTranslationsAndReturnResponse("sub/RPM", expectedLocale, - null); - ZanataProxyFactory mockRequestFactory = mock(ZanataProxyFactory.class); - - ZanataCommand cmd = - new PublicanPullCommand(opts, mockRequestFactory, - mockSourceDocResource, mockTranslationResources, - new URI("http://example.com/")); - cmd.runWithActions(); - } - - private void mockExpectGetTranslationsAndReturnResponse(String id, - LocaleId locale, TranslationsResource entity) { - String docUri = RestUtil.convertToDocumentURIId(id); - StringSet ext = new StringSet("comment;gettext"); - if (entity != null) { - when(mockTranslationResources.getTranslations(docUri, locale, ext)) - .thenReturn( - new DummyResponse(Status.OK, - entity)); - } else { - when(mockTranslationResources.getTranslations(docUri, locale, ext)) - .thenReturn( - new DummyResponse( - Status.NOT_FOUND, null)); - } - } - -} diff --git a/zanata-client-commands/src/test/java/org/zanata/client/commands/push/PublicanPushCommandTest.java b/zanata-client-commands/src/test/java/org/zanata/client/commands/push/PublicanPushCommandTest.java deleted file mode 100644 index 54189a0f..00000000 --- a/zanata-client-commands/src/test/java/org/zanata/client/commands/push/PublicanPushCommandTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package org.zanata.client.commands.push; - -import static org.mockito.Matchers.eq; -import static org.mockito.Matchers.isNotNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -import javax.ws.rs.core.Response.Status; - -import org.jboss.resteasy.client.ClientResponse; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Answers; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.zanata.client.commands.DummyResponse; -import org.zanata.client.commands.OptionsUtil; -import org.zanata.client.commands.PublicanPushCommand; -import org.zanata.client.commands.PublicanPushOptionsImpl; -import org.zanata.client.commands.ZanataCommand; -import org.zanata.client.config.LocaleList; -import org.zanata.client.config.LocaleMapping; -import org.zanata.common.LocaleId; -import org.zanata.rest.StringSet; -import org.zanata.rest.client.ISourceDocResource; -import org.zanata.rest.client.ITranslatedDocResource; -import org.zanata.rest.client.ZanataProxyFactory; -import org.zanata.rest.dto.resource.Resource; -import org.zanata.rest.dto.resource.ResourceMeta; -import org.zanata.rest.dto.resource.TranslationsResource; - -public class PublicanPushCommandTest { - @Mock(answer = Answers.RETURNS_MOCKS) - ISourceDocResource mockSourceDocResource; - - @Mock - ITranslatedDocResource mockTranslationResources; - - @Before - public void beforeMethod() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void publicanPushPot() throws Exception { - publicanPush(false, false); - } - - @Test - public void publicanPushPotAndPo() throws Exception { - publicanPush(true, false); - } - - @Test - public void publicanPushPotAndPoWithLocaleMapping() throws Exception { - publicanPush(true, true); - } - - @SuppressWarnings("deprecation") - private void publicanPush(boolean importPo, boolean mapLocale) - throws Exception { - PublicanPushOptionsImpl opts = new PublicanPushOptionsImpl(); - opts.setInteractiveMode(false); - String projectSlug = "project"; - opts.setProj(projectSlug); - String versionSlug = "1.0"; - opts.setProjectVersion(versionSlug); - opts.setSrcDir(new File("src/test/resources/test1")); - opts.setImportPo(importPo); - OptionsUtil.applyConfigFiles(opts); - if (mapLocale) { - LocaleList locales = new LocaleList(); - locales.add(new LocaleMapping("ja", "ja-JP")); - opts.setLocaleMapList(locales); - } - - List resourceMetaList = new ArrayList(); - resourceMetaList.add(new ResourceMeta("obsolete")); - resourceMetaList.add(new ResourceMeta("RPM")); - when(mockSourceDocResource.get(null)).thenReturn( - new DummyResponse>(Status.OK, - resourceMetaList)); - - final ClientResponse okResponse = - new DummyResponse(Status.OK, null); - when(mockSourceDocResource.deleteResource("obsolete")).thenReturn( - okResponse); - StringSet extensionSet = new StringSet("gettext;comment"); - when( - mockSourceDocResource.putResource(eq("RPM"), - (Resource) isNotNull(), eq(extensionSet), eq(true))) - .thenReturn(okResponse); - when( - mockSourceDocResource.putResource(eq("sub,RPM"), - (Resource) isNotNull(), eq(extensionSet), eq(true))) - .thenReturn(okResponse); - - if (importPo) { - LocaleId expectedLocale; - if (mapLocale) - expectedLocale = new LocaleId("ja"); - else - expectedLocale = new LocaleId("ja-JP"); - when( - mockTranslationResources.putTranslations(eq("RPM"), - eq(expectedLocale), - (TranslationsResource) isNotNull(), - eq(extensionSet), eq("auto"))).thenReturn( - okResponse); - } - ZanataProxyFactory mockRequestFactory = mock(ZanataProxyFactory.class); - - ZanataCommand cmd = - new PublicanPushCommand(opts, mockRequestFactory, - mockSourceDocResource, mockTranslationResources, - new URI("http://example.com/")); - cmd.runWithActions(); - } - -} diff --git a/zanata-maven-plugin/src/main/java/org/zanata/maven/PublicanPullMojo.java b/zanata-maven-plugin/src/main/java/org/zanata/maven/PublicanPullMojo.java deleted file mode 100644 index 55a00735..00000000 --- a/zanata-maven-plugin/src/main/java/org/zanata/maven/PublicanPullMojo.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.zanata.maven; - -import java.io.File; - -import org.zanata.client.commands.PublicanPullCommand; -import org.zanata.client.commands.PublicanPullOptions; - -/** - * Pulls translated text from Zanata. DEPRECATED: use 'pull' with projectType - * 'podir' goal. - * - * @goal publican-pull - * @requiresOnline true - * @author Sean Flanigan - * @deprecated - * @see PullSimpleMojo - */ -public class PublicanPullMojo extends - ConfigurableProjectMojo implements - PublicanPullOptions { - - /** - * Base directory for publican files (with subdirectory "pot" and optional - * locale directories), although the location of "pot" can be overridden - * with the dstDirPot option. - * - * @parameter expression="${zanata.dstDir}" - * @required - */ - private File dstDir; - - /** - * Base directory for pot files. - * - * @parameter expression="${zanata.dstDirPot}" - * default-value="${zanata.dstDir}/pot" - * @required - */ - private File dstDirPot; - - /** - * Export source text from Zanata to local POT files, overwriting or erasing - * existing POT files (DANGER!) - * - * @parameter expression="${zanata.exportPot}" - */ - private boolean exportPot; - - public PublicanPullMojo() throws Exception { - super(); - } - - public PublicanPullCommand initCommand() { - return new PublicanPullCommand(this); - } - - @Override - public void setDstDir(File dstDir) { - this.dstDir = dstDir; - } - - @Override - public void setDstDirPot(File dstDirPot) { - this.dstDirPot = dstDirPot; - } - - @Override - public File getDstDir() { - return dstDir; - } - - @Override - public File getDstDirPot() { - return dstDirPot; - } - - @Override - public boolean getExportPot() { - return exportPot; - } - - @Override - public void setExportPot(boolean exportPot) { - this.exportPot = exportPot; - } - - @Override - public String getCommandName() { - return "publican-pull"; - } - -} diff --git a/zanata-maven-plugin/src/main/java/org/zanata/maven/PublicanPushMojo.java b/zanata-maven-plugin/src/main/java/org/zanata/maven/PublicanPushMojo.java deleted file mode 100644 index 7e9530d7..00000000 --- a/zanata-maven-plugin/src/main/java/org/zanata/maven/PublicanPushMojo.java +++ /dev/null @@ -1,125 +0,0 @@ -package org.zanata.maven; - -import java.io.File; - -import org.zanata.client.commands.PublicanPushCommand; -import org.zanata.client.commands.PublicanPushOptions; - -/** - * Pushes publican source text to a Zanata project version so that it can be - * translated. DEPRECATED: use 'push' with projectType 'podir'. - * - * @goal publican-push - * @requiresOnline true - * @author Sean Flanigan - * @deprecated - * @see PushSimpleMojo - */ -public class PublicanPushMojo extends - ConfigurableProjectMojo implements - PublicanPushOptions { - - public PublicanPushMojo() throws Exception { - super(); - } - - @Override - public PublicanPushCommand initCommand() { - return new PublicanPushCommand(this); - } - - /** - * Base directory for publican files (with subdirectory "pot" and optional - * locale directories), although the location of "pot" can be overridden - * with the srcDirPot option. - * - * @parameter expression="${zanata.srcDir}" - * @required - */ - private File srcDir; - - /** - * Base directory for pot files. - * - * @parameter expression="${zanata.srcDirPot}" - * default-value="${zanata.srcDir}/pot" - */ - private File srcDirPot; - - /** - * Language of source (defaults to en-US) - * - * @parameter expression="${zanata.sourceLang}" - */ - private String sourceLang = "en-US"; - - /** - * Import/merge translations from local PO files to the server, overwriting - * or erasing existing translations (DANGER!) - * - * @parameter expression="${zanata.importPo}" - */ - private boolean importPo; - - /** - * Whether the server should copy latest translations from equivalent - * messages/documents in the database. - * - * @parameter expression="${zanata.copyTrans}" default-value="true" - */ - private boolean copyTrans; - - /** - * Should the client validate XML before sending request to server - * (debugging). - * - * @parameter expression="${zanata.validate}" - */ - private boolean validate; - - /** - * Merge type: "auto" (default) or "import" (DANGER!). - * - * @parameter expression="${zanata.merge}" default-value="auto" - */ - private String merge; - - @Override - public File getSrcDir() { - return srcDir; - } - - @Override - public File getSrcDirPot() { - return srcDirPot; - } - - @Override - public String getSourceLang() { - return sourceLang; - } - - @Override - public boolean getImportPo() { - return importPo; - } - - @Override - public boolean getCopyTrans() { - return copyTrans; - } - - public boolean getValidate() { - return validate; - } - - @Override - public String getMergeType() { - return merge; - } - - @Override - public String getCommandName() { - return "publican-push"; - } -} From 8257ff3c447ae47296690b8c8439bb1a537b502a Mon Sep 17 00:00:00 2001 From: Patrick Huang Date: Fri, 7 Nov 2014 07:30:00 +1000 Subject: [PATCH 06/55] create mock zanata rest server --- mock-server/pom.xml | 103 ++++++++++ .../rest/service/MockAccountResource.java | 52 +++++ .../MockAsynchronousProcessResource.java | 78 ++++++++ .../rest/service/MockCopyTransResource.java | 51 +++++ .../zanata/rest/service/MockFileResource.java | 159 ++++++++++++++++ .../rest/service/MockGlossaryResource.java | 65 +++++++ .../service/MockProjectIterationResource.java | 70 +++++++ .../rest/service/MockProjectResource.java | 56 ++++++ .../rest/service/MockProjectsResource.java | 51 +++++ .../zanata/rest/service/MockResourceUtil.java | 46 +++++ .../service/MockResourcesApplication.java | 54 ++++++ .../zanata/rest/service/MockServerRule.java | 80 ++++++++ .../rest/service/MockSourceDocResource.java | 93 +++++++++ .../rest/service/MockStatisticsResource.java | 81 ++++++++ .../service/MockTranslatedDocResource.java | 64 +++++++ .../rest/service/MockVersionResource.java | 44 +++++ pom.xml | 6 +- rest-client/pom.xml | 164 ++++++++++++++++ .../src/main/java/org/zanata/ManualTest.java | 36 ++++ .../org/zanata/rest/client/AccountClient.java | 60 ++++++ .../rest/client/ApiKeyHeaderFilter.java | 63 +++++++ .../rest/client/AsyncProcessClient.java | 101 ++++++++++ .../rest/client/CacheResponseFilter.java | 65 +++++++ .../org/zanata/rest/client/ClientUtil.java | 67 +++++++ .../zanata/rest/client/CopyTransClient.java | 72 +++++++ .../rest/client/FileResourceClient.java | 177 +++++++++++++++++ .../zanata/rest/client/GlossaryClient.java | 62 ++++++ .../org/zanata/rest/client/ProjectClient.java | 54 ++++++ .../rest/client/ProjectIterationClient.java | 64 +++++++ .../zanata/rest/client/ProjectsClient.java | 45 +++++ .../zanata/rest/client/RestClientFactory.java | 178 ++++++++++++++++++ .../rest/client/SourceDocResourceClient.java | 110 +++++++++++ .../rest/client/StatisticsResourceClient.java | 98 ++++++++++ .../zanata/rest/client/TraceDebugFilter.java | 143 ++++++++++++++ .../rest/client/TransDocResourceClient.java | 83 ++++++++ .../zanata/rest/client/AccountClientTest.java | 58 ++++++ .../rest/client/AsyncProcessClientTest.java | 82 ++++++++ .../rest/client/CopyTransClientTest.java | 57 ++++++ .../rest/client/FileResourceClientTest.java | 172 +++++++++++++++++ .../rest/client/GlossaryClientTest.java | 60 ++++++ .../rest/client/MockServerTestUtil.java | 64 +++++++ .../zanata/rest/client/ProjectClientTest.java | 59 ++++++ .../client/ProjectIterationClientTest.java | 64 +++++++ .../rest/client/ProjectsClientTest.java | 52 +++++ .../rest/client/RestClientFactoryTest.java | 46 +++++ .../client/SourceDocResourceClientTest.java | 79 ++++++++ .../client/StatisticsResourceClientTest.java | 78 ++++++++ .../client/TransDocResourceClientTest.java | 58 ++++++ rest-client/src/test/resources/log4j.xml | 38 ++++ rest-client/src/test/resources/test-odt.odt | Bin 0 -> 8772 bytes .../src/test/resources/zh-CN/test-odt.odt | Bin 0 -> 9074 bytes .../zanata/client/TestProjectGenerator.java | 12 ++ .../client/integraion/FileProjectITCase.java | 87 +++++++++ .../zanata/rest/client/ClientUtilityTest.java | 36 ++-- .../src/test/resources/test-odt.odt | Bin 0 -> 8772 bytes .../src/test/resources/zh-CN/test-odt.odt | Bin 0 -> 9074 bytes 56 files changed, 3883 insertions(+), 14 deletions(-) create mode 100644 mock-server/pom.xml create mode 100644 mock-server/src/main/java/org/zanata/rest/service/MockAccountResource.java create mode 100644 mock-server/src/main/java/org/zanata/rest/service/MockAsynchronousProcessResource.java create mode 100644 mock-server/src/main/java/org/zanata/rest/service/MockCopyTransResource.java create mode 100644 mock-server/src/main/java/org/zanata/rest/service/MockFileResource.java create mode 100644 mock-server/src/main/java/org/zanata/rest/service/MockGlossaryResource.java create mode 100644 mock-server/src/main/java/org/zanata/rest/service/MockProjectIterationResource.java create mode 100644 mock-server/src/main/java/org/zanata/rest/service/MockProjectResource.java create mode 100644 mock-server/src/main/java/org/zanata/rest/service/MockProjectsResource.java create mode 100644 mock-server/src/main/java/org/zanata/rest/service/MockResourceUtil.java create mode 100644 mock-server/src/main/java/org/zanata/rest/service/MockResourcesApplication.java create mode 100644 mock-server/src/main/java/org/zanata/rest/service/MockServerRule.java create mode 100644 mock-server/src/main/java/org/zanata/rest/service/MockSourceDocResource.java create mode 100644 mock-server/src/main/java/org/zanata/rest/service/MockStatisticsResource.java create mode 100644 mock-server/src/main/java/org/zanata/rest/service/MockTranslatedDocResource.java create mode 100644 mock-server/src/main/java/org/zanata/rest/service/MockVersionResource.java create mode 100644 rest-client/pom.xml create mode 100644 rest-client/src/main/java/org/zanata/ManualTest.java create mode 100644 rest-client/src/main/java/org/zanata/rest/client/AccountClient.java create mode 100644 rest-client/src/main/java/org/zanata/rest/client/ApiKeyHeaderFilter.java create mode 100644 rest-client/src/main/java/org/zanata/rest/client/AsyncProcessClient.java create mode 100644 rest-client/src/main/java/org/zanata/rest/client/CacheResponseFilter.java create mode 100644 rest-client/src/main/java/org/zanata/rest/client/ClientUtil.java create mode 100644 rest-client/src/main/java/org/zanata/rest/client/CopyTransClient.java create mode 100644 rest-client/src/main/java/org/zanata/rest/client/FileResourceClient.java create mode 100644 rest-client/src/main/java/org/zanata/rest/client/GlossaryClient.java create mode 100644 rest-client/src/main/java/org/zanata/rest/client/ProjectClient.java create mode 100644 rest-client/src/main/java/org/zanata/rest/client/ProjectIterationClient.java create mode 100644 rest-client/src/main/java/org/zanata/rest/client/ProjectsClient.java create mode 100644 rest-client/src/main/java/org/zanata/rest/client/RestClientFactory.java create mode 100644 rest-client/src/main/java/org/zanata/rest/client/SourceDocResourceClient.java create mode 100644 rest-client/src/main/java/org/zanata/rest/client/StatisticsResourceClient.java create mode 100644 rest-client/src/main/java/org/zanata/rest/client/TraceDebugFilter.java create mode 100644 rest-client/src/main/java/org/zanata/rest/client/TransDocResourceClient.java create mode 100644 rest-client/src/test/java/org/zanata/rest/client/AccountClientTest.java create mode 100644 rest-client/src/test/java/org/zanata/rest/client/AsyncProcessClientTest.java create mode 100644 rest-client/src/test/java/org/zanata/rest/client/CopyTransClientTest.java create mode 100644 rest-client/src/test/java/org/zanata/rest/client/FileResourceClientTest.java create mode 100644 rest-client/src/test/java/org/zanata/rest/client/GlossaryClientTest.java create mode 100644 rest-client/src/test/java/org/zanata/rest/client/MockServerTestUtil.java create mode 100644 rest-client/src/test/java/org/zanata/rest/client/ProjectClientTest.java create mode 100644 rest-client/src/test/java/org/zanata/rest/client/ProjectIterationClientTest.java create mode 100644 rest-client/src/test/java/org/zanata/rest/client/ProjectsClientTest.java create mode 100644 rest-client/src/test/java/org/zanata/rest/client/RestClientFactoryTest.java create mode 100644 rest-client/src/test/java/org/zanata/rest/client/SourceDocResourceClientTest.java create mode 100644 rest-client/src/test/java/org/zanata/rest/client/StatisticsResourceClientTest.java create mode 100644 rest-client/src/test/java/org/zanata/rest/client/TransDocResourceClientTest.java create mode 100644 rest-client/src/test/resources/log4j.xml create mode 100644 rest-client/src/test/resources/test-odt.odt create mode 100644 rest-client/src/test/resources/zh-CN/test-odt.odt create mode 100644 zanata-client-commands/src/test/java/org/zanata/client/integraion/FileProjectITCase.java create mode 100644 zanata-rest-client/src/test/resources/test-odt.odt create mode 100644 zanata-rest-client/src/test/resources/zh-CN/test-odt.odt diff --git a/mock-server/pom.xml b/mock-server/pom.xml new file mode 100644 index 00000000..6f8e4361 --- /dev/null +++ b/mock-server/pom.xml @@ -0,0 +1,103 @@ + + + 4.0.0 + + org.zanata + client + 3.6.0-SNAPSHOT + + mock-server + mock-server + + UTF-8 + 9.0.3.v20130506 + + + + org.zanata + zanata-common-api + + + org.zanata + zanata-adapter-po + + + org.eclipse.jetty + jetty-server + ${jetty.version} + + + org.eclipse.jetty + jetty-servlet + ${jetty.version} + + + org.eclipse.jetty + jetty-servlets + ${jetty.version} + + + + org.jboss.resteasy + async-http-servlet-3.0 + ${resteasy.version} + + + org.jboss.resteasy + jaxrs-api + + + org.jboss.resteasy + resteasy-jaxrs + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + org.scannotation + scannotation + 1.0.3 + + + javassist + javassist + 3.12.1.GA + + + org.jboss.resteasy + resteasy-jackson-provider + + + + org.codehaus.jackson + jackson-core-asl + + + + org.codehaus.jackson + jackson-jaxrs + + + + org.codehaus.jackson + jackson-mapper-asl + + + + org.codehaus.jackson + jackson-xc + + + + junit + junit + compile + + + diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockAccountResource.java b/mock-server/src/main/java/org/zanata/rest/service/MockAccountResource.java new file mode 100644 index 00000000..c8089cd1 --- /dev/null +++ b/mock-server/src/main/java/org/zanata/rest/service/MockAccountResource.java @@ -0,0 +1,52 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.service; + +import javax.ws.rs.Path; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.zanata.rest.dto.Account; + +/** + * @author Patrick Huang pahuang@redhat.com + */ +@Path(AccountResource.SERVICE_PATH) +public class MockAccountResource implements AccountResource { + @Context + UriInfo uriInfo; + private Account account = + new Account("admin@zanata.org", "Administrator", "admin", + "guesswhat"); + + @Override + public Response get() { + return Response.ok(account).build(); + } + + @Override + public Response put(Account account) { + return Response.created(uriInfo.getRequestUri()).build(); + } +} diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockAsynchronousProcessResource.java b/mock-server/src/main/java/org/zanata/rest/service/MockAsynchronousProcessResource.java new file mode 100644 index 00000000..1b014096 --- /dev/null +++ b/mock-server/src/main/java/org/zanata/rest/service/MockAsynchronousProcessResource.java @@ -0,0 +1,78 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.service; + +import java.util.Set; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.Path; + +import org.zanata.common.LocaleId; +import org.zanata.rest.dto.ProcessStatus; +import org.zanata.rest.dto.resource.Resource; +import org.zanata.rest.dto.resource.TranslationsResource; + +/** + * @author Patrick Huang pahuang@redhat.com + */ +@Path(AsynchronousProcessResource.SERVICE_PATH) +public class MockAsynchronousProcessResource implements + AsynchronousProcessResource { + @Override + public ProcessStatus startSourceDocCreation(String idNoSlash, + String projectSlug, String iterationSlug, Resource resource, + Set extensions, @DefaultValue("true") boolean copytrans) { + return MockResourceUtil.notUsedByClient(); + } + + @Override + public ProcessStatus startSourceDocCreationOrUpdate(String idNoSlash, + String projectSlug, String iterationSlug, Resource resource, + Set extensions, @DefaultValue("true") boolean copytrans) { + ProcessStatus processStatus = new ProcessStatus(); + processStatus.setStatusCode(ProcessStatus.ProcessStatusCode.Running); + processStatus.setPercentageComplete(50); + processStatus.setUrl("process1"); + return processStatus; + } + + @Override + public ProcessStatus startTranslatedDocCreationOrUpdate(String idNoSlash, + String projectSlug, String iterationSlug, LocaleId locale, + TranslationsResource translatedDoc, Set extensions, + String merge) { + ProcessStatus processStatus = new ProcessStatus(); + processStatus.setStatusCode(ProcessStatus.ProcessStatusCode.Running); + processStatus.setPercentageComplete(50); + processStatus.setUrl("process2"); + return processStatus; + } + + @Override + public ProcessStatus getProcessStatus(String processId) { + ProcessStatus processStatus = new ProcessStatus(); + processStatus.setStatusCode(ProcessStatus.ProcessStatusCode.Finished); + processStatus.setPercentageComplete(100); + processStatus.setUrl(processId); + return processStatus; + } +} diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockCopyTransResource.java b/mock-server/src/main/java/org/zanata/rest/service/MockCopyTransResource.java new file mode 100644 index 00000000..87a68b4e --- /dev/null +++ b/mock-server/src/main/java/org/zanata/rest/service/MockCopyTransResource.java @@ -0,0 +1,51 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.service; + +import javax.ws.rs.Path; + +import org.zanata.rest.dto.CopyTransStatus; + +/** + * @author Patrick Huang + * pahuang@redhat.com + */ +@Path(CopyTransResource.SERVICE_PATH) +public class MockCopyTransResource implements CopyTransResource { + @Override + public CopyTransStatus startCopyTrans(String projectSlug, + String iterationSlug, String docId) { + CopyTransStatus copyTransStatus = new CopyTransStatus(); + copyTransStatus.setInProgress(true); + copyTransStatus.setPercentageComplete(50); + return copyTransStatus; + } + + @Override + public CopyTransStatus getCopyTransStatus(String projectSlug, + String iterationSlug, String docId) { + CopyTransStatus copyTransStatus = new CopyTransStatus(); + copyTransStatus.setInProgress(false); + copyTransStatus.setPercentageComplete(100); + return copyTransStatus; + } +} diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockFileResource.java b/mock-server/src/main/java/org/zanata/rest/service/MockFileResource.java new file mode 100644 index 00000000..78be7b1d --- /dev/null +++ b/mock-server/src/main/java/org/zanata/rest/service/MockFileResource.java @@ -0,0 +1,159 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.service; + +import java.io.IOException; +import java.io.OutputStream; + +import javax.ws.rs.Path; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.StreamingOutput; + +import org.jboss.resteasy.annotations.providers.multipart.MultipartForm; +import org.zanata.adapter.po.PoWriter2; +import org.zanata.common.ContentState; +import org.zanata.common.LocaleId; +import org.zanata.common.ProjectType; +import org.zanata.rest.DocumentFileUploadForm; +import org.zanata.rest.StringSet; +import org.zanata.rest.dto.ChunkUploadResponse; +import org.zanata.rest.dto.resource.Resource; +import org.zanata.rest.dto.resource.TextFlow; +import org.zanata.rest.dto.resource.TextFlowTarget; +import org.zanata.rest.dto.resource.TranslationsResource; + +/** + * @author Patrick Huang pahuang@redhat.com + */ +@Path(FileResource.SERVICE_PATH) +public class MockFileResource implements FileResource { + @Override + public Response acceptedFileTypes() { + StringSet entity = new StringSet(""); + entity.addAll(ProjectType.getSupportedSourceFileTypes(ProjectType.File)); + entity.addAll(ProjectType + .getSupportedSourceFileTypes(ProjectType.Gettext)); + return Response.ok(entity.toString()).build(); + } + + @Override + public Response uploadSourceFile(String projectSlug, String iterationSlug, + String docId, @MultipartForm DocumentFileUploadForm uploadForm) { + return Response.status(Response.Status.CREATED).entity( + new ChunkUploadResponse(1L, 1, false, + "Upload of new source document successful.")) + .build(); + } + + @Override + public Response uploadTranslationFile(String projectSlug, + String iterationSlug, String localeId, String docId, String merge, + @MultipartForm DocumentFileUploadForm uploadForm) { + return Response.ok( + new ChunkUploadResponse(1L, 1, false, + "Translations uploaded successfully")) + .build(); + } + + @Override + public Response downloadSourceFile(String projectSlug, String iterationSlug, + String fileType, final String docId) { + StreamingOutput output = new StreamingOutput() { + + @Override + public void write(OutputStream output) + throws IOException, WebApplicationException { + PoWriter2 writer = new PoWriter2(false, false); + Resource doc = sampleResource(docId); + writer.writePot(output, "UTF-8", doc); + } + }; + return Response + .ok() + .header("Content-Disposition", + "attachment; filename=\"" + docId + + ".pot\"").type(MediaType.TEXT_PLAIN) + .entity(output).build(); + } + + private static Resource sampleResource(String docId) { + Resource doc = new Resource(docId); + doc.getTextFlows().add(new TextFlow("hello", LocaleId.EN_US, + "hello world")); + return doc; + } + + @Override + public Response downloadTranslationFile(String projectSlug, + String iterationSlug, String locale, String fileExtension, + final String docId) { + StreamingOutput output = new StreamingOutput() { + + @Override + public void write(OutputStream output) + throws IOException, WebApplicationException { + PoWriter2 writer = new PoWriter2(false, false); + writer.writePo(output, "UTF-8", sampleResource(docId), + sampleTransResource()); + } + }; + return Response.ok() + .header("Content-Disposition", + "attachment; filename=\"" + + docId + ".po\"").type(MediaType.TEXT_PLAIN) + .entity(output).build(); + } + + private static TranslationsResource sampleTransResource() { + TranslationsResource resource = new TranslationsResource(); + resource.getExtensions(true); + TextFlowTarget hello = new TextFlowTarget("hello"); + hello.getExtensions(true); + hello.setState(ContentState.Translated); + hello.setContents("hola mundo"); + resource.getTextFlowTargets().add(hello); + return resource; + } + + @Override + public Response download(final String downloadId) { + StreamingOutput output = new StreamingOutput() { + + @Override + public void write(OutputStream output) + throws IOException, WebApplicationException { + PoWriter2 writer = new PoWriter2(false, false); + writer.writePo(output, "UTF-8", sampleResource(downloadId), + sampleTransResource()); + } + }; + return Response.ok() + .header("Content-Disposition", + "attachment; filename=\"" + + downloadId + ".po\"") + .type(MediaType.TEXT_PLAIN) + .entity(output).build(); + } +} diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockGlossaryResource.java b/mock-server/src/main/java/org/zanata/rest/service/MockGlossaryResource.java new file mode 100644 index 00000000..d281fc6f --- /dev/null +++ b/mock-server/src/main/java/org/zanata/rest/service/MockGlossaryResource.java @@ -0,0 +1,65 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.service; + +import javax.ws.rs.Path; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.zanata.common.LocaleId; +import org.zanata.rest.dto.Glossary; + +/** + * @author Patrick Huang + * pahuang@redhat.com + */ +@Path(GlossaryResource.SERVICE_PATH) +public class MockGlossaryResource implements GlossaryResource { + @Context + UriInfo uriInfo; + + @Override + public Response getEntries() { + return MockResourceUtil.notUsedByClient(); + } + + @Override + public Response get(LocaleId locale) { + return MockResourceUtil.notUsedByClient(); + } + + @Override + public Response put(Glossary messageBody) { + return Response.created(uriInfo.getAbsolutePath()).build(); + } + + @Override + public Response deleteGlossary(LocaleId locale) { + return Response.ok().build(); + } + + @Override + public Response deleteGlossaries() { + return Response.ok().build(); + } +} diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockProjectIterationResource.java b/mock-server/src/main/java/org/zanata/rest/service/MockProjectIterationResource.java new file mode 100644 index 00000000..c4db4cd2 --- /dev/null +++ b/mock-server/src/main/java/org/zanata/rest/service/MockProjectIterationResource.java @@ -0,0 +1,70 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.service; + +import javax.ws.rs.Path; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.zanata.rest.dto.ProjectIteration; + +/** + * @author Patrick Huang pahuang@redhat.com + */ +@Path(ProjectIterationResource.SERVICE_PATH) +public class MockProjectIterationResource implements ProjectIterationResource { + @Context + UriInfo uriInfo; + + @Override + public Response head() { + return MockResourceUtil.notUsedByClient(); + } + + @Override + public Response get() { + return Response.ok(new ProjectIteration("master")).build(); + } + + @Override + public Response put(ProjectIteration project) { + return Response.created(uriInfo.getRequestUri()).build(); + } + + @Override + public Response sampleConfiguration() { + String config = + new StringBuilder() + .append("\n") + .append("\n") + .append(" ") + .append(uriInfo.getBaseUri()) + .append("\n") + .append(" about-fedora\n") + .append(" master\n") + .append("").toString(); + return Response.ok(config, MediaType.TEXT_PLAIN_TYPE).build(); + } +} diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockProjectResource.java b/mock-server/src/main/java/org/zanata/rest/service/MockProjectResource.java new file mode 100644 index 00000000..d7198684 --- /dev/null +++ b/mock-server/src/main/java/org/zanata/rest/service/MockProjectResource.java @@ -0,0 +1,56 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.service; + +import javax.ws.rs.Path; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.zanata.common.ProjectType; +import org.zanata.rest.dto.Project; + +/** + * @author Patrick Huang pahuang@redhat.com + */ +@Path(ProjectResource.SERVICE_PATH) +public class MockProjectResource implements ProjectResource { + @Context + UriInfo uriInfo; + + @Override + public Response head() { + return MockResourceUtil.notUsedByClient(); + } + + @Override + public Response get() { + return Response.ok(new Project("about-fedora", "About Fedora", + ProjectType.Podir.name().toLowerCase())).build(); + } + + @Override + public Response put(Project project) { + return Response.created(uriInfo.getRequestUri()).build(); + } +} diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockProjectsResource.java b/mock-server/src/main/java/org/zanata/rest/service/MockProjectsResource.java new file mode 100644 index 00000000..d23cfefc --- /dev/null +++ b/mock-server/src/main/java/org/zanata/rest/service/MockProjectsResource.java @@ -0,0 +1,51 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.service; + +import static org.zanata.common.ProjectType.Podir; + +import javax.ws.rs.Path; +import javax.ws.rs.core.GenericEntity; +import javax.ws.rs.core.Response; + +import org.zanata.rest.dto.Project; + +/** + * @author Patrick Huang pahuang@redhat.com + */ +@Path(ProjectsResource.SERVICE_PATH) +public class MockProjectsResource implements ProjectsResource { + + private static final Project[] PROJECTS = new Project[] { + new Project("about-fedora", "About Fedora", + Podir.name().toLowerCase()) + }; + + @Override + public Response get() { + GenericEntity genericEntity = + new GenericEntity(PROJECTS) { + }; + return Response.ok(genericEntity).build(); + } +} diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockResourceUtil.java b/mock-server/src/main/java/org/zanata/rest/service/MockResourceUtil.java new file mode 100644 index 00000000..78cfca37 --- /dev/null +++ b/mock-server/src/main/java/org/zanata/rest/service/MockResourceUtil.java @@ -0,0 +1,46 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.service; + +import java.util.Set; + +import javax.ws.rs.core.Response; + +import com.google.common.base.Preconditions; + +/** + * @author Patrick Huang + * pahuang@redhat.com + */ +class MockResourceUtil { + static void validateExtensions(Set extensions) { + Preconditions.checkArgument(extensions == null || extensions.isEmpty() + || extensions.contains("gettext") + || extensions.contains("comment")); + } + + static T notUsedByClient() { + throw new UnsupportedOperationException("Not being used by client"); + } + + +} diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockResourcesApplication.java b/mock-server/src/main/java/org/zanata/rest/service/MockResourcesApplication.java new file mode 100644 index 00000000..3c56f80d --- /dev/null +++ b/mock-server/src/main/java/org/zanata/rest/service/MockResourcesApplication.java @@ -0,0 +1,54 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.service; + +import java.util.Set; +import javax.ws.rs.core.Application; + +import com.google.common.collect.ImmutableSet; + +/** + * @author Patrick Huang pahuang@redhat.com + */ +public class MockResourcesApplication extends Application { + private static final ImmutableSet> services = ImmutableSet + .of( + MockVersionResource.class, + MockSourceDocResource.class, + MockTranslatedDocResource.class, + MockStatisticsResource.class, + MockFileResource.class, + MockProjectsResource.class, + MockProjectIterationResource.class, + MockProjectResource.class, + MockGlossaryResource.class, + MockCopyTransResource.class, + MockAccountResource.class, + MockAsynchronousProcessResource.class + ); + + @Override + public Set> getClasses() { + return services; + } +} diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockServerRule.java b/mock-server/src/main/java/org/zanata/rest/service/MockServerRule.java new file mode 100644 index 00000000..05d030c4 --- /dev/null +++ b/mock-server/src/main/java/org/zanata/rest/service/MockServerRule.java @@ -0,0 +1,80 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.service; + +import java.net.URI; + +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.servlet.ServletHolder; +import org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher; +import org.junit.rules.TestRule; +import org.junit.runner.Description; +import org.junit.runners.model.Statement; +import com.google.common.base.Throwables; + +/** + * This will start up a jetty server and host stubbed Zanata rest resources. All + * the resource implementation will either return fixed response or, if not used + * by client right now, throw exception. + * + * @author Patrick Huang pahuang@redhat.com + */ +public class MockServerRule implements TestRule { + private static Server server; + + public MockServerRule() { + startServerIfRequired(); + } + + private static void startServerIfRequired() { + if (server != null && server.isStarted()) { + return; + } + server = new Server(0); + ServletContextHandler context = + new ServletContextHandler(ServletContextHandler.NO_SESSIONS); + context.setContextPath("/"); + ServletHolder holder = + new ServletHolder(new HttpServlet30Dispatcher()); + holder.setInitParameter("javax.ws.rs.Application", + MockResourcesApplication.class.getCanonicalName()); + context.addServlet(holder, "/*"); + server.setHandler(context); + server.setStopAtShutdown(true); + try { + server.start(); + } catch (Exception e) { + throw Throwables.propagate(e); + } + } + + @Override + public Statement apply(final Statement base, Description description) { + return base; + } + + public URI getServerBaseUri() { + return server.getURI(); + } +} diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockSourceDocResource.java b/mock-server/src/main/java/org/zanata/rest/service/MockSourceDocResource.java new file mode 100644 index 00000000..c0563c5e --- /dev/null +++ b/mock-server/src/main/java/org/zanata/rest/service/MockSourceDocResource.java @@ -0,0 +1,93 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.service; + +import java.util.Collection; +import java.util.Date; +import java.util.Set; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.Path; +import javax.ws.rs.core.EntityTag; +import javax.ws.rs.core.GenericEntity; +import javax.ws.rs.core.Response; + +import org.zanata.rest.dto.resource.Resource; +import org.zanata.rest.dto.resource.ResourceMeta; + +/** + * @author Patrick Huang pahuang@redhat.com + */ +@Path(SourceDocResource.SERVICE_PATH) +public class MockSourceDocResource implements SourceDocResource { + + @Override + public Response head() { + return Response.ok(new EntityTag(new Date().toString())).build(); + } + + @Override + public Response get(Set extensions) { + MockResourceUtil.validateExtensions(extensions); + Collection samples = + new ResourceMeta("about-fedora").createSamples(); + GenericEntity> entity = + new GenericEntity>(samples) { + }; + return Response.ok(entity).build(); + } + + @Override + public Response post(Resource resource, Set extensions, + @DefaultValue("true") boolean copyTrans) { + return MockResourceUtil.notUsedByClient(); + } + + @Override + public Response getResource(String idNoSlash, Set extensions) { + MockResourceUtil.validateExtensions(extensions); + return Response.ok(new Resource(idNoSlash)).build(); + } + + @Override + public Response putResource(String idNoSlash, Resource resource, + Set extensions, @DefaultValue("true") boolean copyTrans) { + MockResourceUtil.validateExtensions(extensions); + return Response.ok(resource.getName()).build(); + } + + @Override + public Response deleteResource(String idNoSlash) { + return Response.ok().build(); + } + + @Override + public Response getResourceMeta(String idNoSlash, Set extensions) { + return MockResourceUtil.notUsedByClient(); + } + + @Override + public Response putResourceMeta(String idNoSlash, ResourceMeta resourceMeta, + Set extensions) { + return MockResourceUtil.notUsedByClient(); + } +} diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockStatisticsResource.java b/mock-server/src/main/java/org/zanata/rest/service/MockStatisticsResource.java new file mode 100644 index 00000000..14710782 --- /dev/null +++ b/mock-server/src/main/java/org/zanata/rest/service/MockStatisticsResource.java @@ -0,0 +1,81 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.service; + +import javax.ws.rs.DefaultValue; +import javax.ws.rs.Path; + +import org.zanata.common.BaseTranslationCount; +import org.zanata.common.LocaleId; +import org.zanata.common.TransUnitCount; +import org.zanata.rest.dto.stats.ContainerTranslationStatistics; +import org.zanata.rest.dto.stats.TranslationStatistics; +import org.zanata.rest.dto.stats.contribution.ContributionStatistics; +import org.zanata.rest.dto.stats.contribution.LocaleStatistics; + +/** + * @author Patrick Huang pahuang@redhat.com + */ +@Path(StatisticsResource.SERVICE_PATH) +public class MockStatisticsResource implements StatisticsResource { + + @Override + public ContainerTranslationStatistics getStatistics(String projectSlug, + String iterationSlug, + @DefaultValue("false") boolean includeDetails, + @DefaultValue("false") boolean includeWordStats, String[] locales) { + return generateStatistics(iterationSlug, locales); + } + + private ContainerTranslationStatistics generateStatistics( + String id, String[] locales) { + ContainerTranslationStatistics stats = + new ContainerTranslationStatistics(); + stats.setId(id); + for (String locale : locales) { + stats.addStats(new TranslationStatistics(new TransUnitCount( + 100, 0, + 0, 100, 0), locale.trim())); + } + return stats; + } + + @Override + public ContainerTranslationStatistics getStatistics(String projectSlug, + String iterationSlug, String docId, + @DefaultValue("false") boolean includeWordStats, String[] locales) { + return generateStatistics(docId, locales); + } + + @Override + public ContributionStatistics getContributionStatistics(String projectSlug, + String versionSlug, String username, String dateRange) { + ContributionStatistics contributionStatistics = + new ContributionStatistics(); + LocaleStatistics localeStatistics = new LocaleStatistics(); + localeStatistics.put(new LocaleId("zh"), new BaseTranslationCount(100, + 90, 0, 100, 0)); + contributionStatistics.put(username, localeStatistics); + return contributionStatistics; + } +} diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockTranslatedDocResource.java b/mock-server/src/main/java/org/zanata/rest/service/MockTranslatedDocResource.java new file mode 100644 index 00000000..7a4d3e47 --- /dev/null +++ b/mock-server/src/main/java/org/zanata/rest/service/MockTranslatedDocResource.java @@ -0,0 +1,64 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.service; + +import java.util.Set; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.Path; +import javax.ws.rs.core.Response; + +import org.zanata.common.LocaleId; +import org.zanata.rest.dto.resource.TextFlowTarget; +import org.zanata.rest.dto.resource.TranslationsResource; + +/** + * @author Patrick Huang pahuang@redhat.com + */ +@Path(TranslatedDocResource.SERVICE_PATH) +public class MockTranslatedDocResource implements TranslatedDocResource { + + @Override + public Response getTranslations(String idNoSlash, LocaleId locale, + Set extensions, boolean createSkeletons, + @HeaderParam("If-None-Match") String eTag) { + MockResourceUtil.validateExtensions(extensions); + TranslationsResource transResource = new TranslationsResource(); + transResource.getTextFlowTargets().add(new TextFlowTarget(idNoSlash)); + return Response.ok(transResource).build(); + } + + @Override + public Response deleteTranslations(String idNoSlash, LocaleId locale) { + return MockResourceUtil.notUsedByClient(); + } + + @Override + public Response putTranslations(String idNoSlash, LocaleId locale, + TranslationsResource messageBody, Set extensions, + @DefaultValue("auto") String merge) { + // used by PublicanPush only + MockResourceUtil.validateExtensions(extensions); + return Response.ok().build(); + } +} diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockVersionResource.java b/mock-server/src/main/java/org/zanata/rest/service/MockVersionResource.java new file mode 100644 index 00000000..2d3d518d --- /dev/null +++ b/mock-server/src/main/java/org/zanata/rest/service/MockVersionResource.java @@ -0,0 +1,44 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.service; + +import java.util.Date; +import javax.ws.rs.Path; +import javax.ws.rs.core.Response; + +import org.zanata.rest.dto.VersionInfo; + +/** + * @author Patrick Huang pahuang@redhat.com + */ +@Path(VersionResource.SERVICE_PATH) +public class MockVersionResource implements VersionResource { + + @Override + public Response get() { + return Response.ok( + new VersionInfo("3.6.0-SNAPSHOT", new Date().toString(), + "unknown")) + .build(); + } +} diff --git a/pom.xml b/pom.xml index f5e23c19..c3bf3c75 100644 --- a/pom.xml +++ b/pom.xml @@ -35,7 +35,7 @@ - 3.4.1 + 3.6.0-SNAPSHOT 3.3.0 3.0.1.Final @@ -202,9 +202,11 @@ + mock-server zanata-cli zanata-client-commands zanata-maven-plugin zanata-rest-client + rest-client - + \ No newline at end of file diff --git a/rest-client/pom.xml b/rest-client/pom.xml new file mode 100644 index 00000000..d83eb530 --- /dev/null +++ b/rest-client/pom.xml @@ -0,0 +1,164 @@ + + + 4.0.0 + + org.zanata + client + 3.6.0-SNAPSHOT + + rest-client + rest-client + http://maven.apache.org + + UTF-8 + + + + org.zanata + zanata-common-api + + + org.jboss.resteasy + resteasy-jaxrs + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + jaxrs-api + + + org.jboss.resteasy + resteasy-multipart-provider + + + + + org.zanata + zanata-adapter-po + + + + + org.zanata + mock-server + ${project.version} + test + + + + com.sun.jersey + jersey-core + 1.17.1 + + + com.sun.jersey + jersey-client + 1.17.1 + + + com.sun.jersey.contribs + jersey-multipart + 1.17.1 + + + + + + + + + org.codehaus.jackson + jackson-core-asl + + + + org.codehaus.jackson + jackson-jaxrs + + + + org.codehaus.jackson + jackson-mapper-asl + + + + org.codehaus.jackson + jackson-xc + + + + + org.slf4j + slf4j-api + + + log4j + log4j + + + org.slf4j + slf4j-log4j12 + + + + com.google.guava + guava + + + commons-codec + commons-codec + + + + + junit + junit + test + + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + + + + + + + + + + + + + + + + + + + + + + + + + + + + src/test/resources + + + + diff --git a/rest-client/src/main/java/org/zanata/ManualTest.java b/rest-client/src/main/java/org/zanata/ManualTest.java new file mode 100644 index 00000000..c8cc5bc5 --- /dev/null +++ b/rest-client/src/main/java/org/zanata/ManualTest.java @@ -0,0 +1,36 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Mark a test can only be run manually. + */ +@Retention(RetentionPolicy.SOURCE) +@Target({ ElementType.METHOD}) +public @interface ManualTest { + String value() default ""; +} diff --git a/rest-client/src/main/java/org/zanata/rest/client/AccountClient.java b/rest-client/src/main/java/org/zanata/rest/client/AccountClient.java new file mode 100644 index 00000000..aa879759 --- /dev/null +++ b/rest-client/src/main/java/org/zanata/rest/client/AccountClient.java @@ -0,0 +1,60 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import java.net.URI; + +import org.zanata.rest.MediaTypes; +import org.zanata.rest.dto.Account; + +import com.sun.jersey.api.client.WebResource; + +/** + * @author Patrick Huang pahuang@redhat.com + */ +public class AccountClient { + private final RestClientFactory factory; + private final URI baseUri; + + public AccountClient(RestClientFactory factory) { + this.factory = factory; + this.baseUri = factory.getBaseUri(); + } + + public Account get(String username) { + return webResource(username) + .get(Account.class); + } + + public void put(String username, Account account) { + webResource(username).type( + MediaTypes.APPLICATION_ZANATA_ACCOUNT_XML) + .put(account); + } + + private WebResource webResource(String username) { + return factory.getClient().resource(baseUri) + .path("accounts").path("u") + .path(username); + } +} diff --git a/rest-client/src/main/java/org/zanata/rest/client/ApiKeyHeaderFilter.java b/rest-client/src/main/java/org/zanata/rest/client/ApiKeyHeaderFilter.java new file mode 100644 index 00000000..9be0d28e --- /dev/null +++ b/rest-client/src/main/java/org/zanata/rest/client/ApiKeyHeaderFilter.java @@ -0,0 +1,63 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.Provider; + +import org.zanata.rest.RestConstant; + +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.filter.ClientFilter; + +@Provider +public class ApiKeyHeaderFilter extends ClientFilter { + private String apiKey; + private String username; + private String ver; + + public ApiKeyHeaderFilter(String username, String apiKey, String ver) { + this.username = username; + this.apiKey = apiKey; + this.ver = ver; + } + + @Override + public ClientResponse handle(ClientRequest cr) + throws ClientHandlerException { + MultivaluedMap headers = cr.getHeaders(); + headers.add(RestConstant.HEADER_USERNAME, username); + headers.add(RestConstant.HEADER_API_KEY, apiKey); + headers.add(RestConstant.HEADER_VERSION_NO, ver); + return getNext().handle(cr); + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } +} diff --git a/rest-client/src/main/java/org/zanata/rest/client/AsyncProcessClient.java b/rest-client/src/main/java/org/zanata/rest/client/AsyncProcessClient.java new file mode 100644 index 00000000..8411b585 --- /dev/null +++ b/rest-client/src/main/java/org/zanata/rest/client/AsyncProcessClient.java @@ -0,0 +1,101 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import java.net.URI; +import java.util.Set; +import javax.ws.rs.DefaultValue; + +import org.zanata.common.LocaleId; +import org.zanata.rest.dto.ProcessStatus; +import org.zanata.rest.dto.resource.Resource; +import org.zanata.rest.dto.resource.TranslationsResource; +import org.zanata.rest.service.AsynchronousProcessResource; +import com.sun.jersey.api.client.Client; + +/** + * @author Patrick Huang + * pahuang@redhat.com + */ +public class AsyncProcessClient implements AsynchronousProcessResource { + private final RestClientFactory factory; + private final URI baseUri; + + public AsyncProcessClient(RestClientFactory factory) { + this.factory = factory; + baseUri = factory.getBaseUri(); + } + + @Override + public ProcessStatus startSourceDocCreation(String idNoSlash, + String projectSlug, String iterationSlug, Resource resource, + Set extensions, @DefaultValue("true") boolean copytrans) { + throw new UnsupportedOperationException("Not supported. Use startSourceDocCreationOrUpdate instead."); + } + + @Override + public ProcessStatus startSourceDocCreationOrUpdate(String idNoSlash, + String projectSlug, String iterationSlug, Resource resource, + Set extensions, @DefaultValue("true") boolean copytrans) { + Client client = factory.getClient(); + CacheResponseFilter filter = new CacheResponseFilter(); + client.addFilter(filter); + client.resource(baseUri) + .path(AsynchronousProcessResource.SERVICE_PATH) + .path("projects").path("p").path(projectSlug) + .path("iterations").path("i").path(iterationSlug) + .path("r").path(idNoSlash) + .queryParams(ClientUtil.asMultivaluedMap("ext", extensions)) + .queryParam("copyTrans", String.valueOf(copytrans)) + .put(resource); + client.removeFilter(filter); + return filter.getEntity(ProcessStatus.class); + } + + @Override + public ProcessStatus startTranslatedDocCreationOrUpdate(String idNoSlash, + String projectSlug, String iterationSlug, LocaleId locale, + TranslationsResource translatedDoc, Set extensions, + String merge) { + Client client = factory.getClient(); + CacheResponseFilter filter = new CacheResponseFilter(); + client.addFilter(filter); + client.resource(baseUri) + .path(AsynchronousProcessResource.SERVICE_PATH) + .path("projects").path("p").path(projectSlug) + .path("iterations").path("i").path(iterationSlug) + .path("r").path(idNoSlash) + .path("translations").path(locale.getId()) + .queryParams(ClientUtil.asMultivaluedMap("ext", extensions)) + .queryParam("merge", merge) + .put(translatedDoc); + client.removeFilter(filter); + return filter.getEntity(ProcessStatus.class); + } + + @Override + public ProcessStatus getProcessStatus(String processId) { + return factory.getClient().resource(baseUri) + .path(AsynchronousProcessResource.SERVICE_PATH) + .path(processId).get(ProcessStatus.class); + } +} diff --git a/rest-client/src/main/java/org/zanata/rest/client/CacheResponseFilter.java b/rest-client/src/main/java/org/zanata/rest/client/CacheResponseFilter.java new file mode 100644 index 00000000..bee5a842 --- /dev/null +++ b/rest-client/src/main/java/org/zanata/rest/client/CacheResponseFilter.java @@ -0,0 +1,65 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import com.google.common.base.Optional; +import com.google.common.base.Preconditions; +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.GenericType; +import com.sun.jersey.api.client.filter.ClientFilter; + +/** + * This is a workaround that jersey client don't support put/post returning + * response. + * + * @author Patrick Huang pahuang@redhat.com + */ +public class CacheResponseFilter extends ClientFilter { + private Optional cachedClientResponse = Optional.absent(); + + @Override + public ClientResponse handle(ClientRequest cr) + throws ClientHandlerException { + ClientResponse response = getNext().handle(cr); + response.bufferEntity(); + cachedClientResponse = Optional.of(response); + return response; + } + + public T getEntity(Class type) { + checkState(); + return cachedClientResponse.get().getEntity(type); + } + + public T getEntity(GenericType genericType) { + checkState(); + return cachedClientResponse.get().getEntity(genericType); + } + + private void checkState() { + Preconditions.checkState(cachedClientResponse.isPresent(), + "No cached ClientResponse. Did you forget to add this filter?"); + } +} diff --git a/rest-client/src/main/java/org/zanata/rest/client/ClientUtil.java b/rest-client/src/main/java/org/zanata/rest/client/ClientUtil.java new file mode 100644 index 00000000..f367956f --- /dev/null +++ b/rest-client/src/main/java/org/zanata/rest/client/ClientUtil.java @@ -0,0 +1,67 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import java.lang.reflect.Method; +import java.util.Set; + +import javax.ws.rs.core.MultivaluedMap; + +import com.google.common.base.Throwables; +import com.sun.jersey.core.util.MultivaluedMapImpl; + +/** + * @author Patrick Huang + * pahuang@redhat.com + */ +public class ClientUtil { + + + static Method getMethod(Class resourceClass, + String methodName, Class... paramTypes) { + try { + return resourceClass.getMethod(methodName, paramTypes); + } catch (NoSuchMethodException e) { + throw Throwables.propagate(e); + } + } + + static Class[] arrayOf(int number, Class type) { + Class[] result = new Class[number]; + for (int i = 0; i < number; i++) { + result[i] = type; + } + return result; + } + + static MultivaluedMap asMultivaluedMap( + String paramKey, Iterable values) { + MultivaluedMapImpl map = new MultivaluedMapImpl(); + if (values == null) { + return map; + } + for (String extension : values) { + map.add(paramKey, extension); + } + return map; + } +} diff --git a/rest-client/src/main/java/org/zanata/rest/client/CopyTransClient.java b/rest-client/src/main/java/org/zanata/rest/client/CopyTransClient.java new file mode 100644 index 00000000..74a7dca1 --- /dev/null +++ b/rest-client/src/main/java/org/zanata/rest/client/CopyTransClient.java @@ -0,0 +1,72 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import java.net.URI; + +import org.zanata.rest.dto.CopyTransStatus; +import org.zanata.rest.service.CopyTransResource; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.WebResource; + +/** + * @author Patrick Huang pahuang@redhat.com + */ +public class CopyTransClient implements CopyTransResource { + private final RestClientFactory factory; + private final URI baseUri; + + public CopyTransClient(RestClientFactory factory) { + this.factory = factory; + baseUri = factory.getBaseUri(); + } + + @Override + public CopyTransStatus startCopyTrans(String projectSlug, + String iterationSlug, String docId) { + Client client = factory.getClient(); + CacheResponseFilter filter = new CacheResponseFilter(); + client.addFilter(filter); + webResource(client, projectSlug, iterationSlug, docId) + .post(); + client.removeFilter(filter); + return filter.getEntity(CopyTransStatus.class); + } + + private WebResource webResource(Client client, String projectSlug, + String iterationSlug, + String docId) { + return client.resource(baseUri) + .path(CopyTransResource.SERVICE_PATH) + .path("proj").path(projectSlug) + .path("iter").path(iterationSlug) + .path("doc").path(docId); + } + + @Override + public CopyTransStatus getCopyTransStatus(String projectSlug, + String iterationSlug, String docId) { + return webResource(factory.getClient(), projectSlug, iterationSlug, docId + ).get(CopyTransStatus.class); + } +} diff --git a/rest-client/src/main/java/org/zanata/rest/client/FileResourceClient.java b/rest-client/src/main/java/org/zanata/rest/client/FileResourceClient.java new file mode 100644 index 00000000..84d56d0c --- /dev/null +++ b/rest-client/src/main/java/org/zanata/rest/client/FileResourceClient.java @@ -0,0 +1,177 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import java.io.InputStream; +import java.net.URI; +import javax.ws.rs.core.MediaType; + +import org.zanata.rest.DocumentFileUploadForm; +import org.zanata.rest.StringSet; +import org.zanata.rest.dto.ChunkUploadResponse; +import org.zanata.rest.service.FileResource; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.multipart.FormDataMultiPart; + +import static org.zanata.rest.client.ClientUtil.arrayOf; +import static org.zanata.rest.client.ClientUtil.getMethod; + +/** + * @author Patrick Huang pahuang@redhat.com + */ +public class FileResourceClient { + private final RestClientFactory factory; + + private final URI baseUri; + + public FileResourceClient(RestClientFactory restClientFactory) { + this.factory = restClientFactory; + baseUri = restClientFactory.getBaseUri(); + + } + + public StringSet acceptedFileTypes() { + String types = factory.getClient() + .resource(baseUri) + .path(FileResource.SERVICE_PATH) + .path("accepted_types") + .get(String.class); + return new StringSet(types); + } + + public ChunkUploadResponse uploadSourceFile( + String projectSlug, + String iterationSlug, String docId, + DocumentFileUploadForm documentFileUploadForm) { + CacheResponseFilter filter = new CacheResponseFilter(); + Client client = factory.getClient(); + client.addFilter(filter); + WebResource.Builder builder = client + .resource(baseUri) + .path("file").path("source").path(projectSlug) + .path(iterationSlug) + .queryParam("docId", docId) + .type(MediaType.MULTIPART_FORM_DATA_TYPE); + FormDataMultiPart form = + prepareFormDataMultiPart(documentFileUploadForm); + + builder.post(form); + ChunkUploadResponse chunkUploadResponse = + filter.getEntity(ChunkUploadResponse.class); + client.removeFilter(filter); + return chunkUploadResponse; + } + + private FormDataMultiPart prepareFormDataMultiPart( + DocumentFileUploadForm documentFileUploadForm) { + FormDataMultiPart form = + new FormDataMultiPart() + .field("file", documentFileUploadForm + .getFileStream(), + MediaType.APPLICATION_OCTET_STREAM_TYPE); + addBodyPartIfPresent(form, "adapterParams", + documentFileUploadForm.getAdapterParams()); + addBodyPartIfPresent(form, "type", documentFileUploadForm.getFileType()); + addBodyPartIfPresent(form, "first", documentFileUploadForm.getFirst()); + addBodyPartIfPresent(form, "hash", documentFileUploadForm.getHash()); + addBodyPartIfPresent(form, "last", documentFileUploadForm.getLast()); + addBodyPartIfPresent(form, "size", documentFileUploadForm.getSize()); + addBodyPartIfPresent(form, "uploadId", + documentFileUploadForm.getUploadId()); + return form; + } + + public ChunkUploadResponse uploadTranslationFile( + String projectSlug, + String iterationSlug, String locale, String docId, + String mergeType, + DocumentFileUploadForm documentFileUploadForm) { + CacheResponseFilter filter = new CacheResponseFilter(); + Client client = factory.getClient(); + client.addFilter(filter); + WebResource.Builder builder = client.resource(baseUri) + .path(FileResource.SERVICE_PATH) + .path("translation") + .path(projectSlug) + .path(iterationSlug) + .path(locale) + .queryParam("docId", docId) + .queryParam("merge", mergeType) + .type(MediaType.MULTIPART_FORM_DATA_TYPE); + FormDataMultiPart form = + prepareFormDataMultiPart(documentFileUploadForm); + + builder.post(form); + ChunkUploadResponse chunkUploadResponse = + filter.getEntity(ChunkUploadResponse.class); + client.removeFilter(filter); + return chunkUploadResponse; + } + + public InputStream downloadSourceFile(String projectSlug, + String iterationSlug, + String fileType, String docId) { + WebResource webResource = factory.getClient().resource(baseUri); + URI uri = + webResource + .getUriBuilder() + .path(FileResource.SERVICE_PATH) + .path(getMethod(FileResource.class, + "downloadSourceFile", + arrayOf(4, String.class))) + .build(projectSlug, iterationSlug, fileType); + return webResource + .path(uri.getPath()) + .queryParam("docId", docId) + .get(InputStream.class); + } + + public InputStream downloadTranslationFile(String projectSlug, + String iterationSlug, String locale, String fileExtension, + String docId) { + WebResource webResource = factory.getClient().resource(baseUri); + URI uri = + webResource + .getUriBuilder() + .path(FileResource.SERVICE_PATH) + .path(getMethod(FileResource.class, + "downloadTranslationFile", + arrayOf(5, String.class))) + .build(projectSlug, iterationSlug, locale, + fileExtension); + return webResource + .path(uri.getPath()) + .queryParam("docId", docId) + .get(InputStream.class); + + } + + private static FormDataMultiPart addBodyPartIfPresent( + FormDataMultiPart form, String field, T value) { + if (value != null) { + return form.field(field, value.toString()); + } + return form; + } +} diff --git a/rest-client/src/main/java/org/zanata/rest/client/GlossaryClient.java b/rest-client/src/main/java/org/zanata/rest/client/GlossaryClient.java new file mode 100644 index 00000000..673e6470 --- /dev/null +++ b/rest-client/src/main/java/org/zanata/rest/client/GlossaryClient.java @@ -0,0 +1,62 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import java.net.URI; + +import org.zanata.common.LocaleId; +import org.zanata.rest.dto.Glossary; +import org.zanata.rest.service.GlossaryResource; +import com.sun.jersey.api.client.WebResource; + +/** + * @author Patrick Huang pahuang@redhat.com + */ +public class GlossaryClient { + private final RestClientFactory factory; + private final URI baseUri; + + public GlossaryClient(RestClientFactory factory) { + this.factory = factory; + baseUri = factory.getBaseUri(); + } + + public void put(Glossary glossary) { + webResource().put(glossary); + } + + public void delete(LocaleId locale) { + webResource().path(locale.getId()) + .delete(); + + } + + public void deleteAll() { + webResource().delete(); + } + + private WebResource webResource() { + return factory.getClient().resource(baseUri) + .path(GlossaryResource.SERVICE_PATH); + } +} diff --git a/rest-client/src/main/java/org/zanata/rest/client/ProjectClient.java b/rest-client/src/main/java/org/zanata/rest/client/ProjectClient.java new file mode 100644 index 00000000..c88566a0 --- /dev/null +++ b/rest-client/src/main/java/org/zanata/rest/client/ProjectClient.java @@ -0,0 +1,54 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import org.zanata.rest.dto.Project; +import com.sun.jersey.api.client.WebResource; + +/** + * @author Patrick Huang pahuang@redhat.com + */ +public class ProjectClient { + private final RestClientFactory factory; + private final String projectSlug; + + public ProjectClient(RestClientFactory factory, String projectSlug) { + this.factory = factory; + this.projectSlug = projectSlug; + } + + public Project get() { + return webResource() + .get(Project.class); + } + + private WebResource webResource() { + return factory.getClient() + .resource(factory.getBaseUri()) + .path("projects").path("p").path(projectSlug); + } + + public void put(Project project) { + webResource().put(project); + } +} diff --git a/rest-client/src/main/java/org/zanata/rest/client/ProjectIterationClient.java b/rest-client/src/main/java/org/zanata/rest/client/ProjectIterationClient.java new file mode 100644 index 00000000..3b7e5224 --- /dev/null +++ b/rest-client/src/main/java/org/zanata/rest/client/ProjectIterationClient.java @@ -0,0 +1,64 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import java.net.URI; + +import org.zanata.rest.dto.ProjectIteration; +import com.sun.jersey.api.client.WebResource; + +/** + * @author Patrick Huang + * pahuang@redhat.com + */ +public class ProjectIterationClient { + private final RestClientFactory factory; + private final String projectSlug; + private final String versionSlug; + private URI baseUri; + + public ProjectIterationClient(RestClientFactory factory, String projectSlug, String versionSlug) { + this.factory = factory; + this.projectSlug = projectSlug; + this.versionSlug = versionSlug; + baseUri = factory.getBaseUri(); + } + + public ProjectIteration get() { + return webResource() + .get(ProjectIteration.class); + } + + private WebResource webResource() { + return factory.getClient().resource(baseUri) + .path("projects").path("p").path(projectSlug) + .path("iterations").path("i").path(versionSlug); + } + + public void put(ProjectIteration projectVersion) { + webResource().put(projectVersion); + } + + public String sampleConfiguration() { + return webResource().path("config").get(String.class); + } +} diff --git a/rest-client/src/main/java/org/zanata/rest/client/ProjectsClient.java b/rest-client/src/main/java/org/zanata/rest/client/ProjectsClient.java new file mode 100644 index 00000000..4f25408f --- /dev/null +++ b/rest-client/src/main/java/org/zanata/rest/client/ProjectsClient.java @@ -0,0 +1,45 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import org.zanata.rest.dto.Project; +import org.zanata.rest.service.ProjectsResource; +import com.sun.jersey.api.client.GenericType; + +/** + * @author Patrick Huang pahuang@redhat.com + */ +public class ProjectsClient { + private final RestClientFactory factory; + + public ProjectsClient(RestClientFactory factory) { + this.factory = factory; + } + + public Project[] getProjects() { + return factory.getClient().resource(factory.getBaseUri()) + .path(ProjectsResource.SERVICE_PATH) + .get(new GenericType() { + }); + } +} diff --git a/rest-client/src/main/java/org/zanata/rest/client/RestClientFactory.java b/rest-client/src/main/java/org/zanata/rest/client/RestClientFactory.java new file mode 100644 index 00000000..75ede466 --- /dev/null +++ b/rest-client/src/main/java/org/zanata/rest/client/RestClientFactory.java @@ -0,0 +1,178 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.security.SecureRandom; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import org.codehaus.jackson.jaxrs.JacksonJsonProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.zanata.rest.dto.VersionInfo; + +import com.google.common.base.Throwables; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.config.ClientConfig; +import com.sun.jersey.api.client.config.DefaultClientConfig; +import com.sun.jersey.client.urlconnection.HTTPSProperties; +import com.sun.jersey.multipart.impl.MultiPartWriter; + +/** + * @author Patrick Huang pahuang@redhat.com + */ +public class RestClientFactory { + private static final Logger log = + LoggerFactory.getLogger(RestClientFactory.class); + private String clientVersion; + private VersionInfo clientApiVersion; + + private Client client; + private URI baseURI; + + public RestClientFactory(URI base, String username, String apiKey, + VersionInfo clientApiVersion, boolean logHttp, + boolean sslCertDisabled) { + baseURI = base; + this.clientApiVersion = clientApiVersion; + clientVersion = clientApiVersion.getVersionNo(); + DefaultClientConfig clientConfig = + new DefaultClientConfig(MultiPartWriter.class); + + sslConfiguration(sslCertDisabled, clientConfig); + clientConfig.getClasses().add(JacksonJsonProvider.class); + + client = Client.create(clientConfig); + client.addFilter( + new ApiKeyHeaderFilter(username, apiKey, clientVersion)); + client.addFilter(new TraceDebugFilter(logHttp)); + } + + private static void sslConfiguration(boolean sslCertDisabled, + ClientConfig clientConfig) { + if (!sslCertDisabled) { + return; + } + try { + final SSLContext sslContext = SSLContext.getInstance("TLS"); + + // Create a trust manager that does not validate certificate chains + // against our server + final TrustManager[] trustAllCerts; + trustAllCerts = + new TrustManager[] { new AcceptAllX509TrustManager() }; + sslContext.init(null, trustAllCerts, new SecureRandom()); + HttpsURLConnection + .setDefaultSSLSocketFactory(sslContext + .getSocketFactory()); + clientConfig.getProperties().put( + HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, + new HTTPSProperties( + new HostnameVerifier() { + @Override + public boolean verify(String s, + SSLSession sslSession) { + // whatever your matching policy states + return true; + } + }, sslContext + )); + } catch (Exception e) { + log.warn("error creating SSL client", e); + Throwables.propagate(e); + } + } + + public VersionInfo getServerVersionInfo() { + return client.resource(getBaseUri()).path("version") + .get(VersionInfo.class); + } + + private URL getBaseUrl() { + try { + return new URL(fixBase(baseURI).toString() + getUrlPrefix()); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } + + protected URI getBaseUri() { + try { + return getBaseUrl().toURI(); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } + + private static URI fixBase(URI base) { + if (base != null) { + String baseString = base.toString(); + if (!baseString.endsWith("/")) { + try { + URI result = new URI(baseString + "/"); + log.warn("Appending '/' to base URL '{}': using '{}'", + baseString, result); + return result; + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } + } + return base; + } + + protected String getUrlPrefix() { + return "rest/"; + } + + protected Client getClient() { + return client; + } + + private static class AcceptAllX509TrustManager implements X509TrustManager { + public X509Certificate[] getAcceptedIssuers() { + return null; + } + + public void + checkClientTrusted(X509Certificate[] certs, String authType) + throws CertificateException { + } + + public void + checkServerTrusted(X509Certificate[] certs, String authType) + throws CertificateException { + } + } +} diff --git a/rest-client/src/main/java/org/zanata/rest/client/SourceDocResourceClient.java b/rest-client/src/main/java/org/zanata/rest/client/SourceDocResourceClient.java new file mode 100644 index 00000000..11946f89 --- /dev/null +++ b/rest-client/src/main/java/org/zanata/rest/client/SourceDocResourceClient.java @@ -0,0 +1,110 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import java.net.URI; +import java.util.List; +import java.util.Set; + +import org.zanata.rest.dto.resource.Resource; +import org.zanata.rest.dto.resource.ResourceMeta; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.GenericType; + +import com.sun.jersey.api.client.WebResource; + +/** + * This "implements" caller methods to endpoints in SourceDocResource. + * + * N.B.(as of 11/11/2014 commit 8dbf5ec) post is not used. putResource(with + * copyTrans) is only used by PublicanPushCommand. putResource is not used. + * getResourceMeta is not used. putResourceMeta is not used. + * + * @author Patrick Huang pahuang@redhat.com + */ +public class SourceDocResourceClient { + private final RestClientFactory factory; + private final String project; + private final String projectVersion; + private final URI baseUri; + + public SourceDocResourceClient(RestClientFactory factory, String project, + String projectVersion) { + this.factory = factory; + this.project = project; + this.projectVersion = projectVersion; + baseUri = factory.getBaseUri(); + } + + public List getResourceMeta(Set extensions) { + Client client = factory.getClient(); + WebResource webResource = getBaseServiceResource(client) + .queryParams(ClientUtil.asMultivaluedMap( + "ext", extensions)); + return webResource + .get(new GenericType>() { + }); + } + + private WebResource getBaseServiceResource(Client client) { + return client.resource(baseUri) + .path("projects").path("p") + .path(project) + .path("iterations").path("i") + .path(projectVersion) + .path("r"); + } + + public Resource getResource(String idNoSlash, Set extensions) { + Client client = factory.getClient(); + WebResource webResource = + getBaseServiceResource(client) + .path(idNoSlash) + .queryParams(ClientUtil.asMultivaluedMap( + "ext", extensions)); + return webResource.get(Resource.class); + } + + public String putResource(String idNoSlash, Resource resource, + Set extensions, boolean copyTrans) { + Client client = factory.getClient(); + CacheResponseFilter filter = new CacheResponseFilter(); + client.addFilter(filter); + WebResource webResource = getBaseServiceResource(client) + .path(idNoSlash) + .queryParams(ClientUtil.asMultivaluedMap( + "ext", extensions)) + .queryParam("copyTrans", String.valueOf(copyTrans)); + + webResource.put(resource); + client.removeFilter(filter); + return filter.getEntity(String.class); + } + + public String deleteResource(String idNoSlash) { + Client client = factory.getClient(); + WebResource webResource = getBaseServiceResource(client); + return webResource.path(idNoSlash).delete(String.class); + } + +} diff --git a/rest-client/src/main/java/org/zanata/rest/client/StatisticsResourceClient.java b/rest-client/src/main/java/org/zanata/rest/client/StatisticsResourceClient.java new file mode 100644 index 00000000..7c877c5b --- /dev/null +++ b/rest-client/src/main/java/org/zanata/rest/client/StatisticsResourceClient.java @@ -0,0 +1,98 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import java.net.URI; +import javax.ws.rs.DefaultValue; + +import org.zanata.rest.dto.stats.ContainerTranslationStatistics; +import org.zanata.rest.dto.stats.contribution.ContributionStatistics; +import org.zanata.rest.service.StatisticsResource; +import com.google.common.collect.Lists; +import com.sun.jersey.api.client.WebResource; + +import static org.zanata.rest.client.ClientUtil.asMultivaluedMap; + +/** + * @author Patrick Huang pahuang@redhat.com + */ +public class StatisticsResourceClient implements StatisticsResource { + private final RestClientFactory factory; + private final URI baseUri; + + public StatisticsResourceClient(RestClientFactory factory) { + this.factory = factory; + baseUri = factory.getBaseUri(); + } + + @Override + public ContainerTranslationStatistics getStatistics(String projectSlug, + String iterationSlug, + @DefaultValue("false") boolean includeDetails, + @DefaultValue("false") boolean includeWordStats, String[] locales) { + WebResource webResource = + factory.getClient().resource(baseUri).path("stats") + .path("proj") + .path(projectSlug) + .path("iter") + .path(iterationSlug) + .queryParam("detail", String.valueOf(includeDetails)) + .queryParam("word", String.valueOf(includeWordStats)) + .queryParams(asMultivaluedMap("locale", + Lists.newArrayList(locales))); + return webResource.get(ContainerTranslationStatistics.class); + } + + @Override + public ContainerTranslationStatistics getStatistics(String projectSlug, + String iterationSlug, String docId, + @DefaultValue("false") boolean includeWordStats, String[] locales) { + WebResource webResource = + factory.getClient().resource(baseUri).path("stats") + .path("proj") + .path(projectSlug) + .path("iter") + .path(iterationSlug) + .path("doc") + .path(docId) + .queryParam("word", String.valueOf(includeWordStats)) + .queryParams(asMultivaluedMap("locale", + Lists.newArrayList(locales))); + return webResource.get(ContainerTranslationStatistics.class); + } + + @Override + public ContributionStatistics getContributionStatistics(String projectSlug, + String versionSlug, String username, String dateRange) { + WebResource webResource = + factory.getClient().resource(baseUri).path("stats") + .path("project") + .path(projectSlug) + .path("version") + .path(versionSlug) + .path("contributor") + .path(username) + .path(dateRange); + return webResource.get(ContributionStatistics.class); + } +} diff --git a/rest-client/src/main/java/org/zanata/rest/client/TraceDebugFilter.java b/rest-client/src/main/java/org/zanata/rest/client/TraceDebugFilter.java new file mode 100644 index 00000000..3ea3e3f0 --- /dev/null +++ b/rest-client/src/main/java/org/zanata/rest/client/TraceDebugFilter.java @@ -0,0 +1,143 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package org.zanata.rest.client; + +import java.io.ByteArrayInputStream; +import java.util.ArrayList; +import java.util.List; + +import javax.ws.rs.ext.Provider; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.zanata.rest.RestConstant; + +import com.google.common.base.Charsets; +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.filter.ClientFilter; + +/** + * Performs logging of Requests on the client side. This interceptor + * logs at the level TRACE, unless the option logHttp is set, in which case it + * will log as INFO. + * + * @author Patrick Huang + * pahuang@redhat.com + * + */ +@Provider +public class TraceDebugFilter extends ClientFilter { + + private static final Logger log = LoggerFactory + .getLogger(TraceDebugFilter.class); + + private boolean logHttp; + + @Override + public ClientResponse handle(ClientRequest cr) + throws ClientHandlerException { + if (!logHttp && !log.isTraceEnabled()) { + return getNext().handle(cr); + } + log(">> REST Request: " + cr.getMethod() + " => " + + cr.getURI()); + + // Log before sending a request + for (String key : cr.getHeaders().keySet()) { + String headerVal = + cr.getHeaders().get(key).toString(); + if (key.equals(RestConstant.HEADER_API_KEY)) { + headerVal = + this.maskHeaderValues( + cr.getHeaders() + .get(key)); + } + + log(">> Header: " + key + " = " + headerVal); + } + log(">> body: " + cr.getEntity()); + + + + ClientResponse response = getNext().handle(cr); + + // log after a response has been received + log("<< REST Response: " + response.getStatus() + + ":" + response.getClientResponseStatus()); + for (String key : response.getHeaders().keySet()) { + log("<< Header: " + key + " = " + + response.getHeaders().get(key)); + } + response.bufferEntity(); + log(">> Body: " + getPayloadAsString(response)); + return response; + } + + // this is jersey implementation specific + private String getPayloadAsString(ClientResponse response) { + ByteArrayInputStream entityInputStream = null; + try { + entityInputStream = + (ByteArrayInputStream) response.getEntityInputStream(); + int available = entityInputStream.available(); + byte[] data = new byte[available]; + entityInputStream.read(data); + return new String(data, 0, available, Charsets.UTF_8); + } catch (Exception e) { + log.warn("can't read response payload"); + return "[error reading response]"; + } finally { + if (entityInputStream != null) { + entityInputStream.reset(); + } + } + + } + + public TraceDebugFilter(boolean logHttp) { + this.logHttp = logHttp; + } + + private void log(String msg) { + if (logHttp) { + log.info(msg); + } else { + log.trace(msg); + } + } + + /** + * Masks a list of header values so they are not displayed as clear text in + * the logs. + */ + private String maskHeaderValues(List headerValues) { + List maskedList = new ArrayList(headerValues.size()); + + for (Object actualValue : headerValues) { + // mask all characters with stars + maskedList.add(actualValue.toString().replaceAll(".", "*")); + } + + return maskedList.toString(); + } +} diff --git a/rest-client/src/main/java/org/zanata/rest/client/TransDocResourceClient.java b/rest-client/src/main/java/org/zanata/rest/client/TransDocResourceClient.java new file mode 100644 index 00000000..60a67afe --- /dev/null +++ b/rest-client/src/main/java/org/zanata/rest/client/TransDocResourceClient.java @@ -0,0 +1,83 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import java.net.URI; +import java.util.Set; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.PathParam; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.HttpHeaders; + +import org.zanata.common.LocaleId; +import org.zanata.rest.dto.resource.TranslationsResource; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.WebResource; + +import static org.zanata.rest.client.ClientUtil.asMultivaluedMap; + +/** + * This "implements" caller methods to endpoints in TranslatedDocResource. + * + * @author Patrick Huang pahuang@redhat.com + */ +public class TransDocResourceClient { + private final RestClientFactory factory; + private final String project; + private final String projectVersion; + private final URI baseUri; + + public TransDocResourceClient(RestClientFactory factory, String project, + String projectVersion) { + this.factory = factory; + this.project = project; + this.projectVersion = projectVersion; + baseUri = factory.getBaseUri(); + } + + public TranslationsResource getTranslations( + @PathParam("id") String idNoSlash, + @PathParam("locale") LocaleId locale, + @QueryParam("ext") Set extensions, + @QueryParam("skeletons") boolean createSkeletons, + @HeaderParam(HttpHeaders.IF_NONE_MATCH) String eTag) { + Client client = factory.getClient(); + return getBaseServiceResource(client) + .path(idNoSlash) + .path("translations").path(locale.getId()) + .queryParams(asMultivaluedMap("ext", extensions)) + .queryParam("skeletons", String.valueOf(createSkeletons)) + .header(HttpHeaders.IF_NONE_MATCH, eTag) + .get(TranslationsResource.class); + } + + private WebResource getBaseServiceResource(Client client) { + return client.resource(baseUri) + .path("projects").path("p") + .path(project) + .path("iterations").path("i") + .path(projectVersion) + .path("r"); + } + +} diff --git a/rest-client/src/test/java/org/zanata/rest/client/AccountClientTest.java b/rest-client/src/test/java/org/zanata/rest/client/AccountClientTest.java new file mode 100644 index 00000000..7f9a8d67 --- /dev/null +++ b/rest-client/src/test/java/org/zanata/rest/client/AccountClientTest.java @@ -0,0 +1,58 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.zanata.rest.dto.Account; +import org.zanata.rest.service.MockServerRule; + +import static org.junit.Assert.*; + +public class AccountClientTest { + @ClassRule + public static MockServerRule mockServerRule = new MockServerRule(); + private AccountClient client; + + @Before + public void setUp() throws Exception { + client = new AccountClient(MockServerTestUtil + .createClientFactory(mockServerRule.getServerBaseUri())); + + } + + @Test + public void testGet() throws Exception { + Account account = client.get("admin"); + + assertThat(account.getEmail(), Matchers.equalTo("admin@zanata.org")); + } + + @Test + public void testPut() throws Exception { + client.put("admin", new Account("a@b.c", "d", "e", "f")); + + MockServerTestUtil.verifyServerRespondSuccessStatus(); + } +} \ No newline at end of file diff --git a/rest-client/src/test/java/org/zanata/rest/client/AsyncProcessClientTest.java b/rest-client/src/test/java/org/zanata/rest/client/AsyncProcessClientTest.java new file mode 100644 index 00000000..c6d34499 --- /dev/null +++ b/rest-client/src/test/java/org/zanata/rest/client/AsyncProcessClientTest.java @@ -0,0 +1,82 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.zanata.common.LocaleId; +import org.zanata.rest.dto.ProcessStatus; +import org.zanata.rest.dto.resource.Resource; +import org.zanata.rest.dto.resource.TranslationsResource; +import org.zanata.rest.service.MockServerRule; + +import com.google.common.collect.Sets; + +import static org.junit.Assert.*; + +public class AsyncProcessClientTest { + @ClassRule + public static MockServerRule mockServerRule = new MockServerRule(); + private AsyncProcessClient client; + + @Before + public void setUp() throws Exception { + client = new AsyncProcessClient(MockServerTestUtil + .createClientFactory(mockServerRule.getServerBaseUri())); + } + + @Test + public void testStartSourceDocCreationOrUpdate() throws Exception { + ProcessStatus processStatus = + client.startSourceDocCreationOrUpdate("message", + "about-fedora", + "master", + new Resource("message"), Sets.newHashSet("gettext"), + false); + + assertThat(processStatus.getStatusCode(), Matchers.equalTo( + ProcessStatus.ProcessStatusCode.Running)); + } + + @Test + public void testStartTranslatedDocCreationOrUpdate() throws Exception { + ProcessStatus processStatus = + client.startTranslatedDocCreationOrUpdate("message", + "about-fedora", + "master", LocaleId.DE, + new TranslationsResource(), Sets.newHashSet("gettext"), + "auto"); + + assertThat(processStatus.getStatusCode(), Matchers.equalTo( + ProcessStatus.ProcessStatusCode.Running)); + } + + @Test + public void testGetProcessStatus() throws Exception { + ProcessStatus processStatus = client.getProcessStatus("a"); + + assertThat(processStatus.getStatusCode(), Matchers.equalTo( + ProcessStatus.ProcessStatusCode.Finished)); + } +} \ No newline at end of file diff --git a/rest-client/src/test/java/org/zanata/rest/client/CopyTransClientTest.java b/rest-client/src/test/java/org/zanata/rest/client/CopyTransClientTest.java new file mode 100644 index 00000000..698d63c8 --- /dev/null +++ b/rest-client/src/test/java/org/zanata/rest/client/CopyTransClientTest.java @@ -0,0 +1,57 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.zanata.rest.dto.CopyTransStatus; +import org.zanata.rest.service.MockServerRule; + +import static org.junit.Assert.*; + +public class CopyTransClientTest { + @ClassRule + public static MockServerRule mockServerRule = new MockServerRule(); + private CopyTransClient client; + + @Before + public void setUp() throws Exception { + client = new CopyTransClient(MockServerTestUtil + .createClientFactory(mockServerRule.getServerBaseUri())); + } + + @Test + public void testStartCopyTrans() throws Exception { + CopyTransStatus copyTransStatus = + client.startCopyTrans("about-fedora", "master", "Authors"); + assertThat(copyTransStatus.isInProgress(), Matchers.is(true)); + } + + @Test + public void testGetCopyTransStatus() throws Exception { + CopyTransStatus copyTransStatus = + client.getCopyTransStatus("about-fedora", "master", "Authors"); + assertThat(copyTransStatus.isInProgress(), Matchers.is(false)); + } +} \ No newline at end of file diff --git a/rest-client/src/test/java/org/zanata/rest/client/FileResourceClientTest.java b/rest-client/src/test/java/org/zanata/rest/client/FileResourceClientTest.java new file mode 100644 index 00000000..bcf208ec --- /dev/null +++ b/rest-client/src/test/java/org/zanata/rest/client/FileResourceClientTest.java @@ -0,0 +1,172 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URISyntaxException; +import java.security.DigestInputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import org.apache.commons.codec.binary.Hex; +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.xml.sax.InputSource; +import org.zanata.adapter.po.PoReader2; +import org.zanata.common.LocaleId; +import org.zanata.rest.DocumentFileUploadForm; +import org.zanata.rest.StringSet; +import org.zanata.rest.dto.ChunkUploadResponse; +import org.zanata.rest.dto.resource.Resource; +import org.zanata.rest.dto.resource.TranslationsResource; +import org.zanata.rest.service.MockServerRule; + +import static org.junit.Assert.*; + +public class FileResourceClientTest { + private static final Logger log = + LoggerFactory.getLogger(FileResourceClientTest.class); + private FileResourceClient client; + + @ClassRule + public static MockServerRule mockServerRule = new MockServerRule(); + + @Before + public void setUp() throws URISyntaxException { + RestClientFactory restClientFactory = MockServerTestUtil + .createClientFactory(mockServerRule.getServerBaseUri()); + client = new FileResourceClient(restClientFactory); + } + + @Test + public void testServerAcceptedType() { + StringSet serverAcceptedTypes = client + .acceptedFileTypes(); + + assertThat(serverAcceptedTypes, Matchers.containsInAnyOrder("dtd", + "txt", "idml", "html", "htm", "odt", "odp", "odg", "ods", + "srt", "sbt", "sub", "vtt", "pot")); + } + + @Test +// @Ignore +// @ManualTest("I can't create a Jersey server endpoint that can parse multipart form data embedded in DocumentFileUploadForm") + public + void testSourceFileUpload() throws Exception { +// client = clientTalkingToRealServer(); + DocumentFileUploadForm uploadForm = new DocumentFileUploadForm(); + File source = loadFileFromClasspath("test-odt.odt"); + FileInputStream fileInputStream = new FileInputStream(source); + + uploadForm.setFileStream(fileInputStream); + uploadForm.setFileType("odt"); + uploadForm.setHash(calculateFileHash(source)); + uploadForm.setFirst(true); + uploadForm.setLast(true); + uploadForm.setSize(source.length()); + ChunkUploadResponse uploadResponse = client + .uploadSourceFile("about-fedora", "master", + "test.odt", + uploadForm); + log.info("response: {}", uploadResponse); + assertThat(uploadResponse.getAcceptedChunks(), Matchers.equalTo(1)); + } + + private static File loadFileFromClasspath(String file) { + return new File(Thread.currentThread().getContextClassLoader() + .getResource(file).getFile()); + } + + @Test + public + void testTranslationFileUpload() throws Exception { +// client = clientTalkingToRealServer(); + DocumentFileUploadForm uploadForm = new DocumentFileUploadForm(); + File source = loadFileFromClasspath("zh-CN/test-odt.odt"); + FileInputStream fileInputStream = new FileInputStream(source); + + uploadForm.setFileStream(fileInputStream); + uploadForm.setFileType("odt"); + uploadForm.setHash(calculateFileHash(source)); + uploadForm.setFirst(true); + uploadForm.setLast(true); + uploadForm.setSize(source.length()); + ChunkUploadResponse uploadResponse = client + .uploadTranslationFile("about-fedora", "master", + "zh", + "test.odt", "auto", + uploadForm); + log.info("response: {}", uploadResponse); + assertThat(uploadResponse.getAcceptedChunks(), Matchers.equalTo(1)); + } + + private String calculateFileHash(File srcFile) { + try { + MessageDigest md = MessageDigest.getInstance("MD5"); + InputStream fileStream = new FileInputStream(srcFile); + try { + fileStream = new DigestInputStream(fileStream, md); + byte[] buffer = new byte[256]; + while (fileStream.read(buffer) > 0) { + // continue + } + } finally { + fileStream.close(); + } + return new String(Hex.encodeHex(md.digest())); + } catch (NoSuchAlgorithmException | IOException e) { + throw new RuntimeException(e); + } + } + + @Test + public void testDownloadSourceFile() throws IOException { + InputStream inputStream = + client.downloadSourceFile("about-fedora", "master", "pot", + "About-Fedora"); + PoReader2 reader = new PoReader2(); + Resource resource = + reader.extractTemplate(new InputSource(inputStream), + LocaleId.EN_US, "About-Fedora"); + assertThat(resource.getTextFlows(), Matchers.hasSize(1)); + } + + @Test + public void testDownloadTranslationFile() { + InputStream inputStream = + client.downloadTranslationFile("about-fedora", "master", "es", + "po", "About-Fedora"); + PoReader2 reader = new PoReader2(); + TranslationsResource translationsResource = + reader.extractTarget(new InputSource(inputStream)); + assertThat(translationsResource.getTextFlowTargets(), + Matchers.hasSize(1)); + } + +} \ No newline at end of file diff --git a/rest-client/src/test/java/org/zanata/rest/client/GlossaryClientTest.java b/rest-client/src/test/java/org/zanata/rest/client/GlossaryClientTest.java new file mode 100644 index 00000000..ff80ac6b --- /dev/null +++ b/rest-client/src/test/java/org/zanata/rest/client/GlossaryClientTest.java @@ -0,0 +1,60 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.zanata.common.LocaleId; +import org.zanata.rest.dto.Glossary; +import org.zanata.rest.service.MockServerRule; + +public class GlossaryClientTest { + @ClassRule + public static MockServerRule mockServerRule = new MockServerRule(); + private GlossaryClient client; + + @Before + public void setUp() throws Exception { + client = new GlossaryClient(MockServerTestUtil + .createClientFactory(mockServerRule.getServerBaseUri())); + } + + @Test + public void testPut() throws Exception { + client.put(new Glossary()); + + MockServerTestUtil.verifyServerRespondSuccessStatus(); + } + + @Test + public void testDelete() throws Exception { + client.delete(LocaleId.DE); + MockServerTestUtil.verifyServerRespondSuccessStatus(); + } + + @Test + public void testDeleteAll() throws Exception { + client.deleteAll(); + MockServerTestUtil.verifyServerRespondSuccessStatus(); + } +} \ No newline at end of file diff --git a/rest-client/src/test/java/org/zanata/rest/client/MockServerTestUtil.java b/rest-client/src/test/java/org/zanata/rest/client/MockServerTestUtil.java new file mode 100644 index 00000000..fc8d9cbd --- /dev/null +++ b/rest-client/src/test/java/org/zanata/rest/client/MockServerTestUtil.java @@ -0,0 +1,64 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import java.net.URI; +import java.net.URISyntaxException; + +import org.hamcrest.Matchers; +import org.zanata.rest.dto.VersionInfo; + +import static org.junit.Assert.assertThat; + +/** + * @author Patrick Huang + * pahuang@redhat.com + */ +public class MockServerTestUtil { + + public static RestClientFactory createClientFactory(URI serverBaseUri) { + return new RestClientFactory(serverBaseUri, + "admin", + "b6d7044e9ee3b2447c28fb7c50d86d98", new VersionInfo( + "3.6.0-SNAPSHOT", "unknown", "unknown"), true, true) { + @Override + protected String getUrlPrefix() { + return ""; + } + }; + } + + // If you ever want to test against real server, switch to use this one + public static RestClientFactory clientTalkingToRealServer() + throws URISyntaxException { + return new RestClientFactory(new URI("http://localhost:8080/zanata/"), + "admin", + "b6d7044e9ee3b2447c28fb7c50d86d98", new VersionInfo( + "3.6.0-SNAPSHOT", "unknown", "unknown"), true, + true); + } + + static void verifyServerRespondSuccessStatus() { + assertThat("server return successfuly status code", true, Matchers + .is(true)); + } +} diff --git a/rest-client/src/test/java/org/zanata/rest/client/ProjectClientTest.java b/rest-client/src/test/java/org/zanata/rest/client/ProjectClientTest.java new file mode 100644 index 00000000..39f9a5c9 --- /dev/null +++ b/rest-client/src/test/java/org/zanata/rest/client/ProjectClientTest.java @@ -0,0 +1,59 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.zanata.rest.dto.Project; +import org.zanata.rest.service.MockServerRule; + +import static org.junit.Assert.*; + +public class ProjectClientTest { + @ClassRule + public static MockServerRule mockServerRule = new MockServerRule(); + private ProjectClient client; + + @Before + public void setUp() throws Exception { + client = new ProjectClient(MockServerTestUtil + .createClientFactory(mockServerRule.getServerBaseUri()), + "about-fedora"); + } + + @Test + public void testGet() throws Exception { + Project project = client.get(); + + assertThat(project.getId(), Matchers.equalTo("about-fedora")); + } + + @Test + public void testPut() throws Exception { + client.put(new Project("a", "b", "gettext")); + + MockServerTestUtil.verifyServerRespondSuccessStatus(); + } + +} \ No newline at end of file diff --git a/rest-client/src/test/java/org/zanata/rest/client/ProjectIterationClientTest.java b/rest-client/src/test/java/org/zanata/rest/client/ProjectIterationClientTest.java new file mode 100644 index 00000000..d894aebe --- /dev/null +++ b/rest-client/src/test/java/org/zanata/rest/client/ProjectIterationClientTest.java @@ -0,0 +1,64 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.zanata.rest.dto.ProjectIteration; +import org.zanata.rest.service.MockServerRule; + +import static org.junit.Assert.*; + +public class ProjectIterationClientTest { + @ClassRule + public static MockServerRule mockServerRule = new MockServerRule(); + private ProjectIterationClient client; + + @Before + public void setUp() throws Exception { + client = new ProjectIterationClient(MockServerTestUtil + .createClientFactory(mockServerRule.getServerBaseUri()), + "about-fedora", "master"); + } + + @Test + public void testGet() throws Exception { + ProjectIteration projectIteration = client.get(); + assertThat(projectIteration.getId(), Matchers.equalTo("master")); + } + + @Test + public void testPut() throws Exception { + client.put(new ProjectIteration("1.1")); + + MockServerTestUtil.verifyServerRespondSuccessStatus(); + } + + @Test + public void testSampleConfig() { + String config = client.sampleConfiguration(); + + assertThat(config, Matchers.containsString("")); + } +} \ No newline at end of file diff --git a/rest-client/src/test/java/org/zanata/rest/client/ProjectsClientTest.java b/rest-client/src/test/java/org/zanata/rest/client/ProjectsClientTest.java new file mode 100644 index 00000000..34ea513f --- /dev/null +++ b/rest-client/src/test/java/org/zanata/rest/client/ProjectsClientTest.java @@ -0,0 +1,52 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.zanata.rest.dto.Project; +import org.zanata.rest.service.MockServerRule; + +import static org.junit.Assert.*; + +public class ProjectsClientTest { + @ClassRule + public static MockServerRule mockServerRule = new MockServerRule(); + private ProjectsClient client; + + @Before + public void setUp() { + client = new ProjectsClient(MockServerTestUtil + .createClientFactory(mockServerRule.getServerBaseUri())); + } + + @Test + public void canGetProjects() { + Project[] projects = client.getProjects(); + + assertThat(projects, Matchers.arrayWithSize(1)); + assertThat(projects[0].getId(), Matchers.equalTo("about-fedora")); + } + +} \ No newline at end of file diff --git a/rest-client/src/test/java/org/zanata/rest/client/RestClientFactoryTest.java b/rest-client/src/test/java/org/zanata/rest/client/RestClientFactoryTest.java new file mode 100644 index 00000000..a98d7839 --- /dev/null +++ b/rest-client/src/test/java/org/zanata/rest/client/RestClientFactoryTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import org.hamcrest.MatcherAssert; +import org.hamcrest.Matchers; +import org.junit.Rule; +import org.junit.Test; +import org.zanata.rest.dto.VersionInfo; +import org.zanata.rest.service.MockServerRule; + +public class RestClientFactoryTest { + + @Rule + public MockServerRule mockServerRule = new MockServerRule(); + + @Test + public void testGetVersion() { + VersionInfo serverVersionInfo = MockServerTestUtil.createClientFactory( + mockServerRule.getServerBaseUri()) + .getServerVersionInfo(); + + MatcherAssert.assertThat(serverVersionInfo.getVersionNo(), + Matchers.equalTo("3.6.0-SNAPSHOT")); + } + +} \ No newline at end of file diff --git a/rest-client/src/test/java/org/zanata/rest/client/SourceDocResourceClientTest.java b/rest-client/src/test/java/org/zanata/rest/client/SourceDocResourceClientTest.java new file mode 100644 index 00000000..40007e08 --- /dev/null +++ b/rest-client/src/test/java/org/zanata/rest/client/SourceDocResourceClientTest.java @@ -0,0 +1,79 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import static org.junit.Assert.assertThat; + +import java.net.URISyntaxException; +import java.util.List; + +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.zanata.rest.dto.resource.Resource; +import org.zanata.rest.dto.resource.ResourceMeta; +import org.zanata.rest.service.MockServerRule; +import com.google.common.collect.Sets; + +public class SourceDocResourceClientTest { + @ClassRule + public static MockServerRule mockServerRule = new MockServerRule(); + + private SourceDocResourceClient client; + + @Before + public void setUp() throws URISyntaxException { + client = + new SourceDocResourceClient( + MockServerTestUtil.createClientFactory(mockServerRule.getServerBaseUri()), "about-fedora", + "master"); + } + + @Test + public void testGetResourceMeta() { + List resourceMeta = client.getResourceMeta(null); + + assertThat(resourceMeta, Matchers.hasSize(2)); + } + + @Test + public void testGetResource() { + Resource resource = client.getResource("test", + Sets.newHashSet("gettext", "comment")); + + assertThat(resource.getName(), Matchers.equalTo("test")); + } + + @Test + public void testPutResource() { + String result = client.putResource("test", new Resource("newName"), + Sets.newHashSet("gettext"), true); + assertThat(result, Matchers.equalTo("newName")); + } + + @Test + public void testDeleteResource() { + String result = client.deleteResource("test"); + assertThat(result, Matchers.isEmptyOrNullString()); + } +} \ No newline at end of file diff --git a/rest-client/src/test/java/org/zanata/rest/client/StatisticsResourceClientTest.java b/rest-client/src/test/java/org/zanata/rest/client/StatisticsResourceClientTest.java new file mode 100644 index 00000000..c28478b8 --- /dev/null +++ b/rest-client/src/test/java/org/zanata/rest/client/StatisticsResourceClientTest.java @@ -0,0 +1,78 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import static org.junit.Assert.assertThat; + +import java.net.URISyntaxException; + +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.zanata.rest.dto.stats.ContainerTranslationStatistics; +import org.zanata.rest.dto.stats.contribution.ContributionStatistics; +import org.zanata.rest.service.MockServerRule; + +public class StatisticsResourceClientTest { + @ClassRule + public static MockServerRule mockServerRule = new MockServerRule(); + + private StatisticsResourceClient client; + + @Before + public void setUp() throws URISyntaxException { + client = + new StatisticsResourceClient( + MockServerTestUtil.createClientFactory(mockServerRule.getServerBaseUri())); + } + + @Test + public void testGetIterationStatistics() { + String versionSlug = "master"; + ContainerTranslationStatistics statistics = + client.getStatistics("pahuang-test", versionSlug, true, true, + new String[] { "de-DE", "de", "zh-CN" }); + + assertThat(statistics.getId(), Matchers.equalTo(versionSlug)); + assertThat(statistics.getStats(), Matchers.hasSize(3)); + } + + @Test + public void testGetDocStatistics() { + String docId = "About-Fedora"; + ContainerTranslationStatistics statistics = + client.getStatistics("about-fedora", "master", docId, + true, new String[] { "de-DE", "zh-CN" }); + assertThat(statistics.getId(), Matchers.equalTo(docId)); + assertThat(statistics.getStats(), Matchers.hasSize(2)); + } + + @Test + public void testGetContributorStatistics() { + ContributionStatistics statistics = + client.getContributionStatistics("about-fedora", "master", + "pahuang", "2014-10-01..2014-11-10"); + assertThat(statistics, Matchers.hasKey("pahuang")); + } + +} \ No newline at end of file diff --git a/rest-client/src/test/java/org/zanata/rest/client/TransDocResourceClientTest.java b/rest-client/src/test/java/org/zanata/rest/client/TransDocResourceClientTest.java new file mode 100644 index 00000000..d59bb3fa --- /dev/null +++ b/rest-client/src/test/java/org/zanata/rest/client/TransDocResourceClientTest.java @@ -0,0 +1,58 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.zanata.common.LocaleId; +import org.zanata.rest.dto.resource.TranslationsResource; +import org.zanata.rest.service.MockServerRule; + +import com.google.common.collect.Sets; + +import static org.junit.Assert.*; + +public class TransDocResourceClientTest { + @ClassRule + public static MockServerRule mockServerRule = new MockServerRule(); + + private TransDocResourceClient client; + + @Before + public void setUp() { + client = new TransDocResourceClient( + MockServerTestUtil.createClientFactory(mockServerRule.getServerBaseUri()), "about-fedora", + "master"); + } + + @Test + public void testGetTranslations() { + TranslationsResource translations = + client.getTranslations("test", LocaleId.DE, + Sets.newHashSet("gettext", "comment"), true, "abc"); + + assertThat(translations.getTextFlowTargets(), Matchers.hasSize(1)); + } + +} \ No newline at end of file diff --git a/rest-client/src/test/resources/log4j.xml b/rest-client/src/test/resources/log4j.xml new file mode 100644 index 00000000..a717797b --- /dev/null +++ b/rest-client/src/test/resources/log4j.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + diff --git a/rest-client/src/test/resources/test-odt.odt b/rest-client/src/test/resources/test-odt.odt new file mode 100644 index 0000000000000000000000000000000000000000..ba7e10ec42f91db4a9b1c67303ce848f727ef743 GIT binary patch literal 8772 zcmeHMc|6qH`ybJ@M0RD#GGvJ{3|R(~HQAS}Su)08#0)cIEmX3kNKy8z5!th3U$R7r zEM?z!kt~rGznRMAcHQsqe*ga-uNj|n&hviGbDr}#&z$#j^tDLIm;e9@0AQO>TGhH4 zLM;FQ0Eiz#6Tk)Kg2a2fBH^yC&L{*NkHVnA9%wsJ3>=5TiDF!lXgdtT-35upi{g=9 zc>TX90~Gr>F^~ZO#Lo|9NIYEB%f(s#4B?C01Bt~E)F}YPMa6*JNHhXtheA6j0F8~# zf@FYaU{vxLdwUcD3Edq5L@));O@N|t(4SojKzA$}`ok6|8t#I`LGcLaexsoKrJ+9t z`q|>;j6z>h06OCFu23-8)6-MbQ$iGjbpVUY%F2R&^a6hkWrz4v&ea|3{6oqP0Y*9_ ziPOe`#YM%zyRt+J|E*C(+5IMAFql6FBF^FG6n_i{5fhUH|E%whe%$A92oSdGU7{H<`5(rh&?r0#?hHa;k#IZ)3sZ%=px|h3 zO*k5dM9YH@l=+GLfgmgt|I|C|I4|5>;5YW;f-)c;$Y&x zN&jm8DeHhlBMG_*Yp;#6#Uk~7Y(TJts3e~;8s){kukoTQ7DMzpSVB_FMVwFB9p!8X zIxPnIrF~D4{I3@mN?bqKpS3?%{YUf9xIsZd@goQk;?AFin(%}};)(Od5o1U7g;Csu z47FcvZEED^gYP4tZV!P@WHbmw-MKVW6RUbPKm2}S;-Q^ytw+~=6n&gSKHTIfJgN0y z-Iu}AKUQF3j5%sX5OX~;ZE_4?cSAfnGJXuz2mQ)%rTp6@TML3yNugO#OEFG`rn!^B zS8?!B-fTYRx^^oR((Z0mM1~($b=OwPEA1W4&yz!bjw~Nro#u~Wi+p>jq~F;?Qch0! zbXKCJl~wQ1U~d=2bc~*d@%?`nm=Q5cY zwFWa!aRm=4+WO)Ot~lT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2|vt>q4?Jq~4=9-|9LpV0|Nt38cI$2DvOy1;ZoHa#qQ5mrR z^^l5`i+C7iN&Mwa+45D+?XKnlGa1Hn_+N4=nQGiPG;wH)7KTutVVIaP0T zRY`{yza=YUzk+S;SN8kOT#bcu_h+Z;*l9DU59~t=bJ&_Zo!CT7Qyy~)VM9Jt=dpNY z9Eqy7(05DqK1~Z4byZv(`ey4Y9FsQi`81fG$qxwyGP*-OgSFqdvMTt;ns5|u5;{Q-0?Qcr7 zb2PUB!}lh3Fh_H!+rO26XZ1U9Wo22dhn$Kka=`!0FZiLd_F0EhCmnY9p8u1`E#hgP z47D*DwjGQnG_x+ngtszgr6)V`rL}$hVEdX~Ys;gX9Bws7)nO8O^ii+!8LU8Sl-!fp zj@QvWIC#!iD`r}_{QFBgD7m3jzb zrFEt@&v|XPRQhSe(eyl%!+^=?3u_A%DVwQ^>Xa}jw_Kk?SLazW@cdm zA`sb0#G1GoIVFm*^n#^Or&-pfB=)f^*DM2$-x-xn7@8~3Gt#eebp4%ic%&YZn+G+p zx_!KIQwLH09co=>PchDuX>W*f>N{Eb*N?|2IMyc6UTC7X^pkmr& zgX{;Zc+-A}x1*0b=t!RmKJCQ+IEx`55(EA|+6}kyFY+Vytp@tD)?dTgKUI|B$-fJ7 z|3LZCxxf06Z-X~KSrk`4WMJf9Y%1^fZKSf#o4a!gU{1?iP&c3b74+^~H&!0jH=b^vS-run4Kbh&4 z1%HauZ$N+L(!X!wpK*$QgYzr5{yokuyZ)4g-{Ab2YyTeU&ov^W{_p1cm3#jl=azkc uirQ~*{u>wn3+zW9{z@dbZ2VJV;b6bzW;GBB>g{6$@DCKuKif37cmD-|^Rc1; literal 0 HcmV?d00001 diff --git a/zanata-client-commands/src/test/java/org/zanata/client/TestProjectGenerator.java b/zanata-client-commands/src/test/java/org/zanata/client/TestProjectGenerator.java index 7d5a95a8..193b6c5e 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/TestProjectGenerator.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/TestProjectGenerator.java @@ -2,7 +2,9 @@ import java.io.File; import java.io.FilenameFilter; +import java.net.MalformedURLException; import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.util.Map; @@ -18,6 +20,7 @@ import org.zanata.rest.dto.Project; import org.zanata.rest.dto.ProjectIteration; import com.google.common.base.Preconditions; +import com.google.common.base.Throwables; import com.google.common.collect.ImmutableMap; /** @@ -161,6 +164,15 @@ public String getUrl() { return url; } + public URL getURL() { + try { + return new URI(url).toURL(); + } + catch (MalformedURLException | URISyntaxException e) { + throw Throwables.propagate(e); + } + } + public String getUsername() { return username; } diff --git a/zanata-client-commands/src/test/java/org/zanata/client/integraion/FileProjectITCase.java b/zanata-client-commands/src/test/java/org/zanata/client/integraion/FileProjectITCase.java new file mode 100644 index 00000000..fadb401b --- /dev/null +++ b/zanata-client-commands/src/test/java/org/zanata/client/integraion/FileProjectITCase.java @@ -0,0 +1,87 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.client.integraion; + +import java.io.File; +import java.io.IOException; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.zanata.client.TestProjectGenerator; +import org.zanata.client.commands.ConfigurableProjectOptions; +import org.zanata.client.commands.push.PushOptionsImpl; +import org.zanata.client.commands.push.RawPushCommand; +import org.zanata.client.config.LocaleList; +import org.zanata.client.config.LocaleMapping; +import org.zanata.common.ProjectType; + +/** + * @author Patrick Huang + * pahuang@redhat.com + */ +public class FileProjectITCase { + private static final Logger log = + LoggerFactory.getLogger(FileProjectITCase.class); + @Rule + public TemporaryFolder tempFolder = new TemporaryFolder(); + + private TestProjectGenerator testProjectGenerator = + new TestProjectGenerator(); + private PushOptionsImpl opts; + + @Before + public void setUp() throws Exception { + opts = new PushOptionsImpl(); + TestProjectGenerator.ServerInstance instance = + TestProjectGenerator.ServerInstance.FunctionalTestCargo; + opts.setUrl(instance.getURL()); + opts.setUsername(instance.getUsername()); + opts.setKey(instance.getKey()); + testProjectGenerator.ensureProjectOnServer(opts, + ProjectType.File, instance); + opts.setLocaleMapList(new LocaleList()); + opts.getLocaleMapList().add(new LocaleMapping("zh-CN")); + opts.setBatchMode(true); + } + + @Test + public void manualTest() throws IOException { + File baseDir = + testProjectGenerator.getProjectBaseDir(ProjectType.File); + log.debug("testing project is at: {}", baseDir); + opts.setFileTypes("odt,ods"); + opts.setSrcDir(new File(baseDir, "src")); + opts.setTransDir(baseDir); + opts.setProj(testProjectGenerator.sampleProjectSlug(baseDir)); + opts.setProjectVersion(testProjectGenerator.sampleIterationSlug()); + opts.setProjectType("file"); + opts.setFileTypes("odt"); + + RawPushCommand pushCommand = new RawPushCommand(opts); + + pushCommand.run(); + } +} diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/ClientUtilityTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/ClientUtilityTest.java index a64245e1..ddbf17b2 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/ClientUtilityTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/ClientUtilityTest.java @@ -21,23 +21,35 @@ package org.zanata.rest.client; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; - -import java.net.MalformedURLException; +import java.net.URI; import java.net.URISyntaxException; +import org.hamcrest.MatcherAssert; +import org.hamcrest.Matchers; +import org.junit.Before; import org.junit.Test; +import org.zanata.rest.client.RestClientFactory; +import org.zanata.rest.dto.VersionInfo; + +public class RestClientFactoryTest { + + private RestClientFactory restClientFactory; + + @Before + public void setUp() throws URISyntaxException { + restClientFactory = + new RestClientFactory(new URI("http://localhost:8180/zanata/"), + "admin", + "b6d7044e9ee3b2447c28fb7c50d86d98", new VersionInfo( + "3.6.0-SNAPSHOT", "unknown", "unknown"), true, true); + } -public class ClientUtilityTest { @Test - public void test() throws URISyntaxException, MalformedURLException { + public void testGetVersion() { + VersionInfo serverVersionInfo = restClientFactory.getServerVersionInfo(); - assertThat(ClientUtility.getBaseURL( - "https://zanata.org/rest/version/?a=b"), equalTo( - "https://zanata.org/")); - assertThat(ClientUtility.getBaseURL("https://zanata.org"), - equalTo("https://zanata.org/")); + MatcherAssert.assertThat(serverVersionInfo.getVersionNo(), + Matchers.equalTo("3.6.0-SNAPSHOT")); } -} +} \ No newline at end of file diff --git a/zanata-rest-client/src/test/resources/test-odt.odt b/zanata-rest-client/src/test/resources/test-odt.odt new file mode 100644 index 0000000000000000000000000000000000000000..ba7e10ec42f91db4a9b1c67303ce848f727ef743 GIT binary patch literal 8772 zcmeHMc|6qH`ybJ@M0RD#GGvJ{3|R(~HQAS}Su)08#0)cIEmX3kNKy8z5!th3U$R7r zEM?z!kt~rGznRMAcHQsqe*ga-uNj|n&hviGbDr}#&z$#j^tDLIm;e9@0AQO>TGhH4 zLM;FQ0Eiz#6Tk)Kg2a2fBH^yC&L{*NkHVnA9%wsJ3>=5TiDF!lXgdtT-35upi{g=9 zc>TX90~Gr>F^~ZO#Lo|9NIYEB%f(s#4B?C01Bt~E)F}YPMa6*JNHhXtheA6j0F8~# zf@FYaU{vxLdwUcD3Edq5L@));O@N|t(4SojKzA$}`ok6|8t#I`LGcLaexsoKrJ+9t z`q|>;j6z>h06OCFu23-8)6-MbQ$iGjbpVUY%F2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A`sb0#G1GoIVFm*^n#^Or&-pfB=)f^*DM2$-x-xn7@8~3Gt#eebp4%ic%&YZn+G+p zx_!KIQwLH09co=>PchDuX>W*f>N{Eb*N?|2IMyc6UTC7X^pkmr& zgX{;Zc+-A}x1*0b=t!RmKJCQ+IEx`55(EA|+6}kyFY+Vytp@tD)?dTgKUI|B$-fJ7 z|3LZCxxf06Z-X~KSrk`4WMJf9Y%1^fZKSf#o4a!gU{1?iP&c3b74+^~H&!0jH=b^vS-run4Kbh&4 z1%HauZ$N+L(!X!wpK*$QgYzr5{yokuyZ)4g-{Ab2YyTeU&ov^W{_p1cm3#jl=azkc uirQ~*{u>wn3+zW9{z@dbZ2VJV;b6bzW;GBB>g{6$@DCKuKif37cmD-|^Rc1; literal 0 HcmV?d00001 From 85bbade80857ef09de08a598dc99872f128f6f0a Mon Sep 17 00:00:00 2001 From: Patrick Huang Date: Tue, 18 Nov 2014 09:54:03 +1000 Subject: [PATCH 07/55] move new client back to zanata-rest-client module --- rest-client/pom.xml | 164 ------------------ .../src/main/java/org/zanata/ManualTest.java | 36 ---- rest-client/src/test/resources/log4j.xml | 38 ---- rest-client/src/test/resources/test-odt.odt | Bin 8772 -> 0 bytes .../src/test/resources/zh-CN/test-odt.odt | Bin 9074 -> 0 bytes zanata-rest-client/pom.xml | 111 +++++++++--- .../org/zanata/rest/client/AccountClient.java | 0 .../rest/client/ApiKeyHeaderDecorator.java | 70 -------- .../rest/client/ApiKeyHeaderFilter.java | 0 .../rest/client/AsyncProcessClient.java | 0 .../rest/client/CacheResponseFilter.java | 0 .../org/zanata/rest/client/ClientUtil.java | 0 .../org/zanata/rest/client/ClientUtility.java | 2 +- .../zanata/rest/client/CopyTransClient.java | 0 .../rest/client/FileResourceClient.java | 0 .../zanata/rest/client/GlossaryClient.java | 0 .../client/ITranslationResourcesFactory.java | 10 -- .../org/zanata/rest/client/ProjectClient.java | 0 .../rest/client/ProjectIterationClient.java | 0 .../zanata/rest/client/ProjectsClient.java | 0 .../zanata/rest/client/RestClientFactory.java | 0 .../rest/client/SourceDocResourceClient.java | 0 .../rest/client/StatisticsResourceClient.java | 0 .../zanata/rest/client/TraceDebugFilter.java | 0 .../rest/client/TraceDebugInterceptor.java | 122 ------------- .../rest/client/TransDocResourceClient.java | 0 .../rest/client/ZanataProxyFactory.java | 10 +- .../zanata/rest/client/AccountClientTest.java | 0 .../client/ApiKeyHeaderDecoratorTest.java | 52 +++--- .../rest/client/AsyncProcessClientTest.java | 0 .../zanata/rest/client/ClientUtilityTest.java | 55 ------ .../rest/client/CopyTransClientTest.java | 0 .../rest/client/FileResourceClientTest.java | 0 .../rest/client/GlossaryClientTest.java | 0 .../rest/client/MockServerTestUtil.java | 0 .../zanata/rest/client/ProjectClientTest.java | 0 .../client/ProjectIterationClientTest.java | 0 .../rest/client/ProjectsClientTest.java | 0 .../rest/client/RestClientFactoryTest.java | 0 .../client/SourceDocResourceClientTest.java | 0 .../client/StatisticsResourceClientTest.java | 0 .../client/TransDocResourceClientTest.java | 0 42 files changed, 121 insertions(+), 549 deletions(-) delete mode 100644 rest-client/pom.xml delete mode 100644 rest-client/src/main/java/org/zanata/ManualTest.java delete mode 100644 rest-client/src/test/resources/log4j.xml delete mode 100644 rest-client/src/test/resources/test-odt.odt delete mode 100644 rest-client/src/test/resources/zh-CN/test-odt.odt rename {rest-client => zanata-rest-client}/src/main/java/org/zanata/rest/client/AccountClient.java (100%) delete mode 100644 zanata-rest-client/src/main/java/org/zanata/rest/client/ApiKeyHeaderDecorator.java rename {rest-client => zanata-rest-client}/src/main/java/org/zanata/rest/client/ApiKeyHeaderFilter.java (100%) rename {rest-client => zanata-rest-client}/src/main/java/org/zanata/rest/client/AsyncProcessClient.java (100%) rename {rest-client => zanata-rest-client}/src/main/java/org/zanata/rest/client/CacheResponseFilter.java (100%) rename {rest-client => zanata-rest-client}/src/main/java/org/zanata/rest/client/ClientUtil.java (100%) rename {rest-client => zanata-rest-client}/src/main/java/org/zanata/rest/client/CopyTransClient.java (100%) rename {rest-client => zanata-rest-client}/src/main/java/org/zanata/rest/client/FileResourceClient.java (100%) rename {rest-client => zanata-rest-client}/src/main/java/org/zanata/rest/client/GlossaryClient.java (100%) delete mode 100644 zanata-rest-client/src/main/java/org/zanata/rest/client/ITranslationResourcesFactory.java rename {rest-client => zanata-rest-client}/src/main/java/org/zanata/rest/client/ProjectClient.java (100%) rename {rest-client => zanata-rest-client}/src/main/java/org/zanata/rest/client/ProjectIterationClient.java (100%) rename {rest-client => zanata-rest-client}/src/main/java/org/zanata/rest/client/ProjectsClient.java (100%) rename {rest-client => zanata-rest-client}/src/main/java/org/zanata/rest/client/RestClientFactory.java (100%) rename {rest-client => zanata-rest-client}/src/main/java/org/zanata/rest/client/SourceDocResourceClient.java (100%) rename {rest-client => zanata-rest-client}/src/main/java/org/zanata/rest/client/StatisticsResourceClient.java (100%) rename {rest-client => zanata-rest-client}/src/main/java/org/zanata/rest/client/TraceDebugFilter.java (100%) delete mode 100644 zanata-rest-client/src/main/java/org/zanata/rest/client/TraceDebugInterceptor.java rename {rest-client => zanata-rest-client}/src/main/java/org/zanata/rest/client/TransDocResourceClient.java (100%) rename {rest-client => zanata-rest-client}/src/test/java/org/zanata/rest/client/AccountClientTest.java (100%) rename {rest-client => zanata-rest-client}/src/test/java/org/zanata/rest/client/AsyncProcessClientTest.java (100%) delete mode 100644 zanata-rest-client/src/test/java/org/zanata/rest/client/ClientUtilityTest.java rename {rest-client => zanata-rest-client}/src/test/java/org/zanata/rest/client/CopyTransClientTest.java (100%) rename {rest-client => zanata-rest-client}/src/test/java/org/zanata/rest/client/FileResourceClientTest.java (100%) rename {rest-client => zanata-rest-client}/src/test/java/org/zanata/rest/client/GlossaryClientTest.java (100%) rename {rest-client => zanata-rest-client}/src/test/java/org/zanata/rest/client/MockServerTestUtil.java (100%) rename {rest-client => zanata-rest-client}/src/test/java/org/zanata/rest/client/ProjectClientTest.java (100%) rename {rest-client => zanata-rest-client}/src/test/java/org/zanata/rest/client/ProjectIterationClientTest.java (100%) rename {rest-client => zanata-rest-client}/src/test/java/org/zanata/rest/client/ProjectsClientTest.java (100%) rename {rest-client => zanata-rest-client}/src/test/java/org/zanata/rest/client/RestClientFactoryTest.java (100%) rename {rest-client => zanata-rest-client}/src/test/java/org/zanata/rest/client/SourceDocResourceClientTest.java (100%) rename {rest-client => zanata-rest-client}/src/test/java/org/zanata/rest/client/StatisticsResourceClientTest.java (100%) rename {rest-client => zanata-rest-client}/src/test/java/org/zanata/rest/client/TransDocResourceClientTest.java (100%) diff --git a/rest-client/pom.xml b/rest-client/pom.xml deleted file mode 100644 index d83eb530..00000000 --- a/rest-client/pom.xml +++ /dev/null @@ -1,164 +0,0 @@ - - - 4.0.0 - - org.zanata - client - 3.6.0-SNAPSHOT - - rest-client - rest-client - http://maven.apache.org - - UTF-8 - - - - org.zanata - zanata-common-api - - - org.jboss.resteasy - resteasy-jaxrs - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - jaxrs-api - - - org.jboss.resteasy - resteasy-multipart-provider - - - - - org.zanata - zanata-adapter-po - - - - - org.zanata - mock-server - ${project.version} - test - - - - com.sun.jersey - jersey-core - 1.17.1 - - - com.sun.jersey - jersey-client - 1.17.1 - - - com.sun.jersey.contribs - jersey-multipart - 1.17.1 - - - - - - - - - org.codehaus.jackson - jackson-core-asl - - - - org.codehaus.jackson - jackson-jaxrs - - - - org.codehaus.jackson - jackson-mapper-asl - - - - org.codehaus.jackson - jackson-xc - - - - - org.slf4j - slf4j-api - - - log4j - log4j - - - org.slf4j - slf4j-log4j12 - - - - com.google.guava - guava - - - commons-codec - commons-codec - - - - - junit - junit - test - - - org.hamcrest - hamcrest-core - test - - - org.hamcrest - hamcrest-library - test - - - - - - - - - - - - - - - - - - - - - - - - - - - - src/test/resources - - - - diff --git a/rest-client/src/main/java/org/zanata/ManualTest.java b/rest-client/src/main/java/org/zanata/ManualTest.java deleted file mode 100644 index c8cc5bc5..00000000 --- a/rest-client/src/main/java/org/zanata/ManualTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2014, Red Hat, Inc. and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.zanata; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Mark a test can only be run manually. - */ -@Retention(RetentionPolicy.SOURCE) -@Target({ ElementType.METHOD}) -public @interface ManualTest { - String value() default ""; -} diff --git a/rest-client/src/test/resources/log4j.xml b/rest-client/src/test/resources/log4j.xml deleted file mode 100644 index a717797b..00000000 --- a/rest-client/src/test/resources/log4j.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/rest-client/src/test/resources/test-odt.odt b/rest-client/src/test/resources/test-odt.odt deleted file mode 100644 index ba7e10ec42f91db4a9b1c67303ce848f727ef743..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8772 zcmeHMc|6qH`ybJ@M0RD#GGvJ{3|R(~HQAS}Su)08#0)cIEmX3kNKy8z5!th3U$R7r zEM?z!kt~rGznRMAcHQsqe*ga-uNj|n&hviGbDr}#&z$#j^tDLIm;e9@0AQO>TGhH4 zLM;FQ0Eiz#6Tk)Kg2a2fBH^yC&L{*NkHVnA9%wsJ3>=5TiDF!lXgdtT-35upi{g=9 zc>TX90~Gr>F^~ZO#Lo|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jGQnG_x+ngtszgr6)V`rL}$hVEdX~Ys;gX9Bws7)nO8O^ii+!8LU8Sl-!fp zj@QvWIC#!iD`r}_{QFBgD7m3jzb zrFEt@&v|XPRQhSe(eyl%!+^=?3u_A%DVwQ^>Xa}jw_Kk?SLazW@cdm zA`sb0#G1GoIVFm*^n#^Or&-pfB=)f^*DM2$-x-xn7@8~3Gt#eebp4%ic%&YZn+G+p zx_!KIQwLH09co=>PchDuX>W*f>N{Eb*N?|2IMyc6UTC7X^pkmr& zgX{;Zc+-A}x1*0b=t!RmKJCQ+IEx`55(EA|+6}kyFY+Vytp@tD)?dTgKUI|B$-fJ7 z|3LZCxxf06Z-X~KSrk`4WMJf9Y%1^fZKSf#o4a!gU{1?iP&c3b74+^~H&!0jH=b^vS-run4Kbh&4 z1%HauZ$N+L(!X!wpK*$QgYzr5{yokuyZ)4g-{Ab2YyTeU&ov^W{_p1cm3#jl=azkc uirQ~*{u>wn3+zW9{z@dbZ2VJV;b6bzW;GBB>g{6$@DCKuKif37cmD-|^Rc1; diff --git a/zanata-rest-client/pom.xml b/zanata-rest-client/pom.xml index 0559ec2a..3aedfd7d 100644 --- a/zanata-rest-client/pom.xml +++ b/zanata-rest-client/pom.xml @@ -23,34 +23,106 @@ org.zanata zanata-common-api + + + + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + jaxrs-api + + + org.jboss.resteasy + resteasy-multipart-provider + + + + + org.zanata + zanata-adapter-po - junit - junit + + org.zanata + mock-server + ${project.version} test + - org.jboss.resteasy - jaxrs-api - ${resteasy.version} + com.sun.jersey + jersey-core + 1.17.1 - - org.jboss.resteasy - resteasy-jaxrs - - - net.jcip - jcip-annotations - - + com.sun.jersey + jersey-client + 1.17.1 + + + com.sun.jersey.contribs + jersey-multipart + 1.17.1 + + + + org.codehaus.jackson + jackson-core-asl + - org.jboss.resteasy - resteasy-client - ${resteasy.version} + org.codehaus.jackson + jackson-jaxrs + + + org.codehaus.jackson + jackson-mapper-asl + + + + org.codehaus.jackson + jackson-xc + + + + log4j + log4j + + + org.slf4j + slf4j-log4j12 + + + + commons-codec + commons-codec + + + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + + + + junit + junit + test + + commons-beanutils commons-beanutils @@ -61,10 +133,7 @@ - - org.apache.httpcomponents - httpclient - + org.slf4j slf4j-api diff --git a/rest-client/src/main/java/org/zanata/rest/client/AccountClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/AccountClient.java similarity index 100% rename from rest-client/src/main/java/org/zanata/rest/client/AccountClient.java rename to zanata-rest-client/src/main/java/org/zanata/rest/client/AccountClient.java diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/ApiKeyHeaderDecorator.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ApiKeyHeaderDecorator.java deleted file mode 100644 index 805f7ab5..00000000 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/ApiKeyHeaderDecorator.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.zanata.rest.client; - -import javax.ws.rs.ext.Provider; - -import org.jboss.resteasy.annotations.interception.ClientInterceptor; -import org.jboss.resteasy.client.ClientResponse; -import org.jboss.resteasy.spi.interception.ClientExecutionContext; -import org.jboss.resteasy.spi.interception.ClientExecutionInterceptor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.zanata.rest.RestConstant; - -@Provider -@ClientInterceptor -public class ApiKeyHeaderDecorator implements ClientExecutionInterceptor { - private static Logger log = LoggerFactory - .getLogger(ApiKeyHeaderDecorator.class); - private String apiKey; - private String username; - private String ver; - - public ApiKeyHeaderDecorator() { - } - - public ApiKeyHeaderDecorator(String username, String apiKey, String ver) { - this.username = username; - this.apiKey = apiKey; - this.ver = ver; - } - - @SuppressWarnings("rawtypes") - @Override - public ClientResponse execute(ClientExecutionContext ctx) throws Exception { - ctx.getRequest().getHeadersAsObjects() - .add(RestConstant.HEADER_USERNAME, username); - ctx.getRequest().getHeadersAsObjects() - .add(RestConstant.HEADER_API_KEY, apiKey); - ctx.getRequest().getHeadersAsObjects() - .add(RestConstant.HEADER_VERSION_NO, ver); - try { - return ctx.proceed(); - } catch (Error e) { - // NB Seam/RestEasy doesn't log these exceptions fully for some - // reason - log.warn("error processing request", e); - throw e; - } catch (Exception e) { - // NB Seam/RestEasy doesn't log these exceptions fully for some - // reason - log.warn("exception processing request", e); - throw e; - } - } - - public String getApiKey() { - return apiKey; - } - - public void setApiKey(String apiKey) { - this.apiKey = apiKey; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } -} diff --git a/rest-client/src/main/java/org/zanata/rest/client/ApiKeyHeaderFilter.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ApiKeyHeaderFilter.java similarity index 100% rename from rest-client/src/main/java/org/zanata/rest/client/ApiKeyHeaderFilter.java rename to zanata-rest-client/src/main/java/org/zanata/rest/client/ApiKeyHeaderFilter.java diff --git a/rest-client/src/main/java/org/zanata/rest/client/AsyncProcessClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/AsyncProcessClient.java similarity index 100% rename from rest-client/src/main/java/org/zanata/rest/client/AsyncProcessClient.java rename to zanata-rest-client/src/main/java/org/zanata/rest/client/AsyncProcessClient.java diff --git a/rest-client/src/main/java/org/zanata/rest/client/CacheResponseFilter.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/CacheResponseFilter.java similarity index 100% rename from rest-client/src/main/java/org/zanata/rest/client/CacheResponseFilter.java rename to zanata-rest-client/src/main/java/org/zanata/rest/client/CacheResponseFilter.java diff --git a/rest-client/src/main/java/org/zanata/rest/client/ClientUtil.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ClientUtil.java similarity index 100% rename from rest-client/src/main/java/org/zanata/rest/client/ClientUtil.java rename to zanata-rest-client/src/main/java/org/zanata/rest/client/ClientUtil.java diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/ClientUtility.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ClientUtility.java index b0d1a5c5..aa4c8e04 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/ClientUtility.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/ClientUtility.java @@ -31,7 +31,7 @@ public static void checkResult(ClientResponse response, URI uri) { // if server returns a redirect (most likely due to http to https // redirect), we don't want to bury this information in a xml // marshalling exception. - String movedTo = response.getHeaderString("Location"); + String movedTo = "FIX ME"; String message; if (!Strings.isNullOrEmpty(movedTo)) { diff --git a/rest-client/src/main/java/org/zanata/rest/client/CopyTransClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/CopyTransClient.java similarity index 100% rename from rest-client/src/main/java/org/zanata/rest/client/CopyTransClient.java rename to zanata-rest-client/src/main/java/org/zanata/rest/client/CopyTransClient.java diff --git a/rest-client/src/main/java/org/zanata/rest/client/FileResourceClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/FileResourceClient.java similarity index 100% rename from rest-client/src/main/java/org/zanata/rest/client/FileResourceClient.java rename to zanata-rest-client/src/main/java/org/zanata/rest/client/FileResourceClient.java diff --git a/rest-client/src/main/java/org/zanata/rest/client/GlossaryClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/GlossaryClient.java similarity index 100% rename from rest-client/src/main/java/org/zanata/rest/client/GlossaryClient.java rename to zanata-rest-client/src/main/java/org/zanata/rest/client/GlossaryClient.java diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/ITranslationResourcesFactory.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ITranslationResourcesFactory.java deleted file mode 100644 index bfa6617e..00000000 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/ITranslationResourcesFactory.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.zanata.rest.client; - -import java.net.URI; - -public interface ITranslationResourcesFactory { - ITranslatedDocResource getTranslatedDocResource(String projectSlug, - String versionSlug); - - URI getResourceURI(String projectSlug, String versionSlug); -} diff --git a/rest-client/src/main/java/org/zanata/rest/client/ProjectClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectClient.java similarity index 100% rename from rest-client/src/main/java/org/zanata/rest/client/ProjectClient.java rename to zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectClient.java diff --git a/rest-client/src/main/java/org/zanata/rest/client/ProjectIterationClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectIterationClient.java similarity index 100% rename from rest-client/src/main/java/org/zanata/rest/client/ProjectIterationClient.java rename to zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectIterationClient.java diff --git a/rest-client/src/main/java/org/zanata/rest/client/ProjectsClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectsClient.java similarity index 100% rename from rest-client/src/main/java/org/zanata/rest/client/ProjectsClient.java rename to zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectsClient.java diff --git a/rest-client/src/main/java/org/zanata/rest/client/RestClientFactory.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/RestClientFactory.java similarity index 100% rename from rest-client/src/main/java/org/zanata/rest/client/RestClientFactory.java rename to zanata-rest-client/src/main/java/org/zanata/rest/client/RestClientFactory.java diff --git a/rest-client/src/main/java/org/zanata/rest/client/SourceDocResourceClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/SourceDocResourceClient.java similarity index 100% rename from rest-client/src/main/java/org/zanata/rest/client/SourceDocResourceClient.java rename to zanata-rest-client/src/main/java/org/zanata/rest/client/SourceDocResourceClient.java diff --git a/rest-client/src/main/java/org/zanata/rest/client/StatisticsResourceClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/StatisticsResourceClient.java similarity index 100% rename from rest-client/src/main/java/org/zanata/rest/client/StatisticsResourceClient.java rename to zanata-rest-client/src/main/java/org/zanata/rest/client/StatisticsResourceClient.java diff --git a/rest-client/src/main/java/org/zanata/rest/client/TraceDebugFilter.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/TraceDebugFilter.java similarity index 100% rename from rest-client/src/main/java/org/zanata/rest/client/TraceDebugFilter.java rename to zanata-rest-client/src/main/java/org/zanata/rest/client/TraceDebugFilter.java diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/TraceDebugInterceptor.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/TraceDebugInterceptor.java deleted file mode 100644 index ca9e00bf..00000000 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/TraceDebugInterceptor.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright 2010, Red Hat, Inc. and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.zanata.rest.client; - -import java.util.ArrayList; -import java.util.List; - -import javax.ws.rs.ext.Provider; - -import org.jboss.resteasy.annotations.interception.ClientInterceptor; -import org.jboss.resteasy.client.ClientResponse; -import org.jboss.resteasy.spi.interception.ClientExecutionContext; -import org.jboss.resteasy.spi.interception.ClientExecutionInterceptor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.zanata.rest.RestConstant; - -/** - * Performs logging of Resteasy Requests on the client side. This interceptor - * logs at the level TRACE, unless the option logHttp is set, in which case it - * will log as INFO. - * - * @author Carlos Munoz camunoz@redhat.com - * - */ -@Provider -@ClientInterceptor -public class TraceDebugInterceptor implements ClientExecutionInterceptor { - - private static final Logger log = LoggerFactory - .getLogger(TraceDebugInterceptor.class); - - private boolean logHttp; - - public TraceDebugInterceptor() { - this(true); - } - - public TraceDebugInterceptor(boolean logHttp) { - this.logHttp = logHttp; - } - - private void log(String msg) { - if (logHttp) { - log.info(msg); - } else { - log.trace(msg); - } - } - - @SuppressWarnings("rawtypes") - @Override - public ClientResponse execute(ClientExecutionContext ctx) throws Exception { - if (!logHttp && !log.isTraceEnabled()) { - return ctx.proceed(); - } - - log(">> REST Request: " + ctx.getRequest().getHttpMethod() + " => " - + ctx.getRequest().getUri()); - - // Log before sending a request - for (String key : ctx.getRequest().getHeaders().keySet()) { - String headerVal = - ctx.getRequest().getHeaders().get(key).toString(); - if (key.equals(RestConstant.HEADER_API_KEY)) { - headerVal = - this.maskHeaderValues(ctx.getRequest().getHeaders() - .get(key)); - } - - log(">> Header: " + key + " = " + headerVal); - } - log(">> Body: " + ctx.getRequest().getBody()); - - ClientResponse result = ctx.proceed(); - - // log after a response has been received - log("<< REST Response: " + result.getResponseStatus().getStatusCode() - + ":" + result.getResponseStatus()); - for (String key : result.getHeaders().keySet()) { - log("<< Header: " + key + " = " + result.getHeaders().get(key)); - } - - return result; - } - - /** - * Masks a list of header values so they are not displayed as clear text in - * the logs. - */ - private String maskHeaderValues(List headerValues) { - List maskedList = new ArrayList(headerValues.size()); - - for (String actualValue : headerValues) { - maskedList.add(actualValue.replaceAll(".", "*")); // mask all - // characters with - // stars - } - - return maskedList.toString(); - } - -} diff --git a/rest-client/src/main/java/org/zanata/rest/client/TransDocResourceClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/TransDocResourceClient.java similarity index 100% rename from rest-client/src/main/java/org/zanata/rest/client/TransDocResourceClient.java rename to zanata-rest-client/src/main/java/org/zanata/rest/client/TransDocResourceClient.java diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/ZanataProxyFactory.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ZanataProxyFactory.java index e0925347..afc0b096 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/ZanataProxyFactory.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/ZanataProxyFactory.java @@ -47,7 +47,7 @@ import com.google.common.base.Throwables; // TODO fix deprecation warnings -public class ZanataProxyFactory implements ITranslationResourcesFactory { +public class ZanataProxyFactory { private static final Logger log = LoggerFactory .getLogger(ZanataProxyFactory.class); @@ -121,9 +121,9 @@ public ZanataProxyFactory(URI base, String username, String apiKey, // See https://issues.jboss.org/browse/RESTEASY-1075 // See org.zanata.rest.client.ClientUtility.checkResult(org.jboss.resteasy.client.ClientResponse, java.net.URI)() crf.setFollowRedirects(true); - registerPrefixInterceptor(new TraceDebugInterceptor(logHttp)); - registerPrefixInterceptor(new ApiKeyHeaderDecorator(username, apiKey, - clientApiVersion.getVersionNo())); +// registerPrefixInterceptor(new TraceDebugInterceptor(logHttp)); +// registerPrefixInterceptor(new ApiKeyHeaderDecorator(username, apiKey, +// clientApiVersion.getVersionNo())); if (eagerVersionCheck) { performVersionCheck(); } @@ -355,7 +355,6 @@ public IProjectsResource getProjectsResource() { return createProxy(IProjectsResource.class); } - @Override public ITranslatedDocResource getTranslatedDocResource(String projectSlug, String versionSlug) { return createProxy(ITranslatedDocResource.class, @@ -384,7 +383,6 @@ public IAsynchronousProcessResource getAsynchronousProcessResource() { return createProxy(IAsynchronousProcessResource.class); } - @Override public URI getResourceURI(String projectSlug, String versionSlug) { String spec = "projects/p/" + projectSlug + "/iterations/i/" + versionSlug diff --git a/rest-client/src/test/java/org/zanata/rest/client/AccountClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/AccountClientTest.java similarity index 100% rename from rest-client/src/test/java/org/zanata/rest/client/AccountClientTest.java rename to zanata-rest-client/src/test/java/org/zanata/rest/client/AccountClientTest.java diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/ApiKeyHeaderDecoratorTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/ApiKeyHeaderDecoratorTest.java index 49248b3f..9d19af15 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/ApiKeyHeaderDecoratorTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/ApiKeyHeaderDecoratorTest.java @@ -39,31 +39,31 @@ public class ApiKeyHeaderDecoratorTest { @Test public void testHeaders() throws Exception { - String username = "username"; - String apiKey = "apiKey"; - String ver = "ver"; - ApiKeyHeaderDecorator decorator = - new ApiKeyHeaderDecorator(username, apiKey, ver); - - final ClientRequest mockRequest = - new ClientRequest("http://uri.example.com/"); - ClientExecutionContext mockCtx = new ClientExecutionContext() { - - @SuppressWarnings("rawtypes") - @Override - public ClientResponse proceed() throws Exception { - return null; - } - - @Override - public ClientRequest getRequest() { - return mockRequest; - } - }; - decorator.execute(mockCtx); - MultivaluedMap headers = mockRequest.getHeaders(); - assertEquals(username, headers.getFirst(RestConstant.HEADER_USERNAME)); - assertEquals(apiKey, headers.getFirst(RestConstant.HEADER_API_KEY)); - assertEquals(ver, headers.getFirst(RestConstant.HEADER_VERSION_NO)); +// String username = "username"; +// String apiKey = "apiKey"; +// String ver = "ver"; +// ApiKeyHeaderDecorator decorator = +// new ApiKeyHeaderDecorator(username, apiKey, ver); +// +// final ClientRequest mockRequest = +// new ClientRequest("http://uri.example.com/"); +// ClientExecutionContext mockCtx = new ClientExecutionContext() { +// +// @SuppressWarnings("rawtypes") +// @Override +// public ClientResponse proceed() throws Exception { +// return null; +// } +// +// @Override +// public ClientRequest getRequest() { +// return mockRequest; +// } +// }; +// decorator.execute(mockCtx); +// MultivaluedMap headers = mockRequest.getHeaders(); +// assertEquals(username, headers.getFirst(RestConstant.HEADER_USERNAME)); +// assertEquals(apiKey, headers.getFirst(RestConstant.HEADER_API_KEY)); +// assertEquals(ver, headers.getFirst(RestConstant.HEADER_VERSION_NO)); } } diff --git a/rest-client/src/test/java/org/zanata/rest/client/AsyncProcessClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/AsyncProcessClientTest.java similarity index 100% rename from rest-client/src/test/java/org/zanata/rest/client/AsyncProcessClientTest.java rename to zanata-rest-client/src/test/java/org/zanata/rest/client/AsyncProcessClientTest.java diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/ClientUtilityTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/ClientUtilityTest.java deleted file mode 100644 index ddbf17b2..00000000 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/ClientUtilityTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2014, Red Hat, Inc. and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.zanata.rest.client; - -import java.net.URI; -import java.net.URISyntaxException; - -import org.hamcrest.MatcherAssert; -import org.hamcrest.Matchers; -import org.junit.Before; -import org.junit.Test; -import org.zanata.rest.client.RestClientFactory; -import org.zanata.rest.dto.VersionInfo; - -public class RestClientFactoryTest { - - private RestClientFactory restClientFactory; - - @Before - public void setUp() throws URISyntaxException { - restClientFactory = - new RestClientFactory(new URI("http://localhost:8180/zanata/"), - "admin", - "b6d7044e9ee3b2447c28fb7c50d86d98", new VersionInfo( - "3.6.0-SNAPSHOT", "unknown", "unknown"), true, true); - } - - @Test - public void testGetVersion() { - VersionInfo serverVersionInfo = restClientFactory.getServerVersionInfo(); - - MatcherAssert.assertThat(serverVersionInfo.getVersionNo(), - Matchers.equalTo("3.6.0-SNAPSHOT")); - } - -} \ No newline at end of file diff --git a/rest-client/src/test/java/org/zanata/rest/client/CopyTransClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/CopyTransClientTest.java similarity index 100% rename from rest-client/src/test/java/org/zanata/rest/client/CopyTransClientTest.java rename to zanata-rest-client/src/test/java/org/zanata/rest/client/CopyTransClientTest.java diff --git a/rest-client/src/test/java/org/zanata/rest/client/FileResourceClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/FileResourceClientTest.java similarity index 100% rename from rest-client/src/test/java/org/zanata/rest/client/FileResourceClientTest.java rename to zanata-rest-client/src/test/java/org/zanata/rest/client/FileResourceClientTest.java diff --git a/rest-client/src/test/java/org/zanata/rest/client/GlossaryClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/GlossaryClientTest.java similarity index 100% rename from rest-client/src/test/java/org/zanata/rest/client/GlossaryClientTest.java rename to zanata-rest-client/src/test/java/org/zanata/rest/client/GlossaryClientTest.java diff --git a/rest-client/src/test/java/org/zanata/rest/client/MockServerTestUtil.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/MockServerTestUtil.java similarity index 100% rename from rest-client/src/test/java/org/zanata/rest/client/MockServerTestUtil.java rename to zanata-rest-client/src/test/java/org/zanata/rest/client/MockServerTestUtil.java diff --git a/rest-client/src/test/java/org/zanata/rest/client/ProjectClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectClientTest.java similarity index 100% rename from rest-client/src/test/java/org/zanata/rest/client/ProjectClientTest.java rename to zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectClientTest.java diff --git a/rest-client/src/test/java/org/zanata/rest/client/ProjectIterationClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectIterationClientTest.java similarity index 100% rename from rest-client/src/test/java/org/zanata/rest/client/ProjectIterationClientTest.java rename to zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectIterationClientTest.java diff --git a/rest-client/src/test/java/org/zanata/rest/client/ProjectsClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectsClientTest.java similarity index 100% rename from rest-client/src/test/java/org/zanata/rest/client/ProjectsClientTest.java rename to zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectsClientTest.java diff --git a/rest-client/src/test/java/org/zanata/rest/client/RestClientFactoryTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/RestClientFactoryTest.java similarity index 100% rename from rest-client/src/test/java/org/zanata/rest/client/RestClientFactoryTest.java rename to zanata-rest-client/src/test/java/org/zanata/rest/client/RestClientFactoryTest.java diff --git a/rest-client/src/test/java/org/zanata/rest/client/SourceDocResourceClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/SourceDocResourceClientTest.java similarity index 100% rename from rest-client/src/test/java/org/zanata/rest/client/SourceDocResourceClientTest.java rename to zanata-rest-client/src/test/java/org/zanata/rest/client/SourceDocResourceClientTest.java diff --git a/rest-client/src/test/java/org/zanata/rest/client/StatisticsResourceClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/StatisticsResourceClientTest.java similarity index 100% rename from rest-client/src/test/java/org/zanata/rest/client/StatisticsResourceClientTest.java rename to zanata-rest-client/src/test/java/org/zanata/rest/client/StatisticsResourceClientTest.java diff --git a/rest-client/src/test/java/org/zanata/rest/client/TransDocResourceClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/TransDocResourceClientTest.java similarity index 100% rename from rest-client/src/test/java/org/zanata/rest/client/TransDocResourceClientTest.java rename to zanata-rest-client/src/test/java/org/zanata/rest/client/TransDocResourceClientTest.java From 354594150a101b5a49a5ab8735af9e5b6f5e6eb5 Mon Sep 17 00:00:00 2001 From: Patrick Huang Date: Wed, 19 Nov 2014 09:32:52 +1000 Subject: [PATCH 08/55] remove resteasy dependency and switch to new client --- mock-server/pom.xml | 82 +++- .../rest/service/MockStatisticsResource.java | 6 +- pom.xml | 20 +- .../org/zanata/client/ClientToServerTest.java | 17 +- zanata-client-commands/pom.xml | 35 +- .../client/commands/ConfigurableCommand.java | 17 +- .../commands/ConfigurableProjectCommand.java | 15 +- .../client/commands/ListLocalCommand.java | 8 +- .../client/commands/ListRemoteCommand.java | 26 +- .../zanata/client/commands/OptionsUtil.java | 72 +-- .../client/commands/PushPullCommand.java | 44 +- .../client/commands/PutProjectCommand.java | 22 +- .../client/commands/PutUserCommand.java | 27 +- .../client/commands/PutVersionCommand.java | 18 +- .../zanata/client/commands/UpdateChecker.java | 37 +- .../delete/GlossaryDeleteCommand.java | 32 +- .../glossary/push/GlossaryPushCommand.java | 24 +- .../client/commands/init/InitCommand.java | 60 +-- .../commands/init/ProjectIterationPrompt.java | 39 +- .../client/commands/init/ProjectPrompt.java | 46 +- .../commands/init/SourceConfigPrompt.java | 18 +- .../commands/init/TransConfigPrompt.java | 12 +- .../client/commands/pull/PullCommand.java | 52 +- .../client/commands/pull/RawPullCommand.java | 46 +- .../commands/push/OfflinePoStrategy.java | 21 +- .../client/commands/push/PushCommand.java | 81 ++- .../client/commands/push/RawPushCommand.java | 56 +-- .../commands/stats/GetStatisticsCommand.java | 41 +- ...ServerRule.java => MockitoServerRule.java} | 191 ++++---- .../zanata/client/TestProjectGenerator.java | 23 +- .../java/org/zanata/client/TestUtils.java | 27 + .../zanata/client/commands/DummyResponse.java | 233 --------- .../client/commands/HTTPMockContainer.java | 9 - .../client/commands/init/InitCommandTest.java | 60 +-- .../init/ProjectIterationPromptTest.java | 56 +-- .../commands/init/ProjectPromptTest.java | 116 ++--- .../client/commands/push/PushCommandTest.java | 79 ++- .../commands/push/XliffPushStrategyTest.java | 5 +- .../zanata/client/config/ConfigUtilTest.java | 5 +- .../client/integraion/FileProjectITCase.java | 87 ---- .../integraion/PushPullFileProjectITCase.java | 45 +- .../integraion/PushPullGettextITCase.java | 45 +- zanata-rest-client/pom.xml | 45 +- .../org/zanata/rest/client/AccountClient.java | 2 +- .../rest/client/AsyncProcessClient.java | 37 +- .../rest/client/CacheResponseFilter.java | 2 +- .../org/zanata/rest/client/ClientUtil.java | 115 ++++- .../org/zanata/rest/client/ClientUtility.java | 91 ---- .../zanata/rest/client/CopyTransClient.java | 14 +- .../rest/client/FileResourceClient.java | 48 +- .../zanata/rest/client/GlossaryClient.java | 2 +- .../org/zanata/rest/client/ProjectClient.java | 3 +- .../rest/client/ProjectIterationClient.java | 2 +- .../zanata/rest/client/ProjectsClient.java | 2 +- .../zanata/rest/client/RestClientFactory.java | 92 ++++ .../rest/client/SourceDocResourceClient.java | 2 +- .../rest/client/StatisticsResourceClient.java | 2 +- .../rest/client/TransDocResourceClient.java | 7 +- .../rest/client/ZanataProxyFactory.java | 462 ------------------ .../rest/client/FileResourceClientTest.java | 6 +- .../client/TransDocResourceClientTest.java | 3 +- 61 files changed, 1022 insertions(+), 1870 deletions(-) rename zanata-client-commands/src/test/java/org/zanata/client/{MockServerRule.java => MockitoServerRule.java} (69%) delete mode 100644 zanata-client-commands/src/test/java/org/zanata/client/commands/DummyResponse.java delete mode 100644 zanata-client-commands/src/test/java/org/zanata/client/integraion/FileProjectITCase.java delete mode 100644 zanata-rest-client/src/main/java/org/zanata/rest/client/ClientUtility.java delete mode 100644 zanata-rest-client/src/main/java/org/zanata/rest/client/ZanataProxyFactory.java diff --git a/mock-server/pom.xml b/mock-server/pom.xml index 6f8e4361..7d14d182 100644 --- a/mock-server/pom.xml +++ b/mock-server/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 org.zanata @@ -9,14 +11,34 @@ mock-server mock-server + + + + scm:git:git://github.com/zanata/zanata-client.git + scm:git:git@github.com:zanata/zanata-client.git + https://github.com/zanata/zanata-client + HEAD + + UTF-8 9.0.3.v20130506 + + org.jboss.resteasy + jaxrs-api + org.zanata zanata-common-api + + + + com.sun.jersey + jersey-core + + org.zanata @@ -43,13 +65,15 @@ async-http-servlet-3.0 ${resteasy.version} - - org.jboss.resteasy - jaxrs-api - org.jboss.resteasy resteasy-jaxrs + + + net.jcip + jcip-annotations + + org.jboss.resteasy @@ -58,16 +82,27 @@ org.jboss.resteasy resteasy-multipart-provider + + + javax.servlet + servlet-api + + + commons-logging + commons-logging + + org.scannotation scannotation 1.0.3 - - - javassist - javassist - 3.12.1.GA + + + javassist + javassist + + org.jboss.resteasy @@ -99,5 +134,30 @@ junit compile + + + com.google.guava + guava + + + + + + maven-surefire-plugin + + false + + + + com.ning.maven.plugins + maven-duplicate-finder-plugin + 1.0.7 + + + true + + + + diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockStatisticsResource.java b/mock-server/src/main/java/org/zanata/rest/service/MockStatisticsResource.java index 14710782..89bd18a5 100644 --- a/mock-server/src/main/java/org/zanata/rest/service/MockStatisticsResource.java +++ b/mock-server/src/main/java/org/zanata/rest/service/MockStatisticsResource.java @@ -24,11 +24,11 @@ import javax.ws.rs.DefaultValue; import javax.ws.rs.Path; -import org.zanata.common.BaseTranslationCount; import org.zanata.common.LocaleId; import org.zanata.common.TransUnitCount; import org.zanata.rest.dto.stats.ContainerTranslationStatistics; import org.zanata.rest.dto.stats.TranslationStatistics; +import org.zanata.rest.dto.stats.contribution.BaseContributionStatistic; import org.zanata.rest.dto.stats.contribution.ContributionStatistics; import org.zanata.rest.dto.stats.contribution.LocaleStatistics; @@ -73,8 +73,8 @@ public ContributionStatistics getContributionStatistics(String projectSlug, ContributionStatistics contributionStatistics = new ContributionStatistics(); LocaleStatistics localeStatistics = new LocaleStatistics(); - localeStatistics.put(new LocaleId("zh"), new BaseTranslationCount(100, - 90, 0, 100, 0)); + localeStatistics.put(new LocaleId("zh"), new BaseContributionStatistic( + 100, 90, 100, 0)); contributionStatistics.put(username, localeStatistics); return contributionStatistics; } diff --git a/pom.xml b/pom.xml index c3bf3c75..c052562f 100644 --- a/pom.xml +++ b/pom.xml @@ -8,7 +8,7 @@ org.zanata zanata-parent - 20 + 21-SNAPSHOT ../parent @@ -38,6 +38,7 @@ 3.6.0-SNAPSHOT 3.3.0 3.0.1.Final + 1.17.1 @@ -73,6 +74,22 @@ commons-logging commons-logging + + org.jboss.resteasy + resteasy-jaxrs + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + jaxrs-api + + + org.jboss.resteasy + resteasy-multipart-provider + @@ -207,6 +224,5 @@ zanata-client-commands zanata-maven-plugin zanata-rest-client - rest-client \ No newline at end of file diff --git a/zanata-cli/src/test/java/org/zanata/client/ClientToServerTest.java b/zanata-cli/src/test/java/org/zanata/client/ClientToServerTest.java index e682441a..4a5fbb0e 100644 --- a/zanata-cli/src/test/java/org/zanata/client/ClientToServerTest.java +++ b/zanata-cli/src/test/java/org/zanata/client/ClientToServerTest.java @@ -56,27 +56,26 @@ public void test503ResponseHandling() throws IOException { HTTPMockContainer mockContainer = HTTPMockContainer.notOkResponse(Status.SERVICE_UNAVAILABLE); ContainerServer server = new ContainerServer(mockContainer); - SocketConnection connection = new SocketConnection(server); - try { - InetSocketAddress address = (InetSocketAddress) connection.connect(new InetSocketAddress(0)); + try (SocketConnection connection = new SocketConnection(server)) { + InetSocketAddress address = (InetSocketAddress) connection + .connect(new InetSocketAddress(0)); int port = address.getPort(); String command = "stats"; - String url = "http://localhost:"+port+"/"; + String url = "http://localhost:" + port + "/"; String project = "iok"; String version = "6.4"; - // client.setErrors(true); + // client.setErrors(true); client.processArgs(command, "--url", url, "--project", project, - "--project-version", version, "--username", "admin", "--key", + "--project-version", version, "--username", "admin", + "--key", "abcdeabcdeabcdeabcdeabcdeabcde12"); server.stop(); Mockito.verify(mockAbortStrategy).abort(throwableCapture.capture()); assertThat("Client will display meaningful message for 503", throwableCapture.getValue().getMessage() - .contains("Service is currently unavailable")); - } finally { - connection.close(); + .contains("503 Service Unavailable")); } } } diff --git a/zanata-client-commands/pom.xml b/zanata-client-commands/pom.xml index 9659cd8f..ddf791ef 100644 --- a/zanata-client-commands/pom.xml +++ b/zanata-client-commands/pom.xml @@ -48,25 +48,15 @@ - com.google.code.findbugs - annotations - provided + com.sun.jersey + jersey-client + ${jersey.version} - org.jboss.resteasy - jaxrs-api - ${resteasy.version} - - - org.jboss.resteasy - resteasy-jaxrs - - - net.jcip - jcip-annotations - - + com.google.code.findbugs + annotations + provided @@ -80,6 +70,11 @@ slf4j-api + + com.sun.jersey + jersey-core + ${jersey.version} + junit junit @@ -175,4 +170,12 @@ + + + + src/test/resources + false + + + diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/ConfigurableCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/ConfigurableCommand.java index 322a3e71..073a3c2d 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/ConfigurableCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/ConfigurableCommand.java @@ -30,7 +30,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zanata.client.config.CommandHook; -import org.zanata.rest.client.ZanataProxyFactory; +import org.zanata.rest.client.RestClientFactory; /** * Base class for commands which supports configuration by the user's zanata.ini @@ -41,19 +41,18 @@ public abstract class ConfigurableCommand implements ZanataCommand { private final O opts; - private ZanataProxyFactory requestFactory; + private RestClientFactory clientFactory; private boolean deprecated; private String deprecationMessage; private static final Logger log = LoggerFactory .getLogger(ConfigurableCommand.class); - public ConfigurableCommand(O opts, ZanataProxyFactory factory) { + public ConfigurableCommand(O opts, RestClientFactory clientFactory) { this.opts = opts; - if (factory != null) - this.requestFactory = factory; - else - this.requestFactory = OptionsUtil.createRequestFactory(opts); + this.clientFactory = + clientFactory == null ? OptionsUtil.createClientFactory(opts) + : clientFactory; } public ConfigurableCommand(O opts) { @@ -77,8 +76,8 @@ public O getOpts() { return opts; } - public ZanataProxyFactory getRequestFactory() { - return requestFactory; + public RestClientFactory getClientFactory() { + return clientFactory; } @Override diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/ConfigurableProjectCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/ConfigurableProjectCommand.java index 51a68be9..25bf59bc 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/ConfigurableProjectCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/ConfigurableProjectCommand.java @@ -21,7 +21,7 @@ package org.zanata.client.commands; import org.zanata.client.exceptions.ConfigException; -import org.zanata.rest.client.ZanataProxyFactory; +import org.zanata.rest.client.RestClientFactory; /** * Base class for commands which supports configuration by the user's zanata.ini @@ -41,8 +41,12 @@ public abstract class ConfigurableProjectCommand @@ -14,13 +13,8 @@ public class ListLocalCommand extends private static final Logger log = LoggerFactory .getLogger(ListLocalCommand.class); - public ListLocalCommand(ConfigurableProjectOptions opts, - ZanataProxyFactory factory) { - super(opts, factory); - } - public ListLocalCommand(ConfigurableProjectOptions opts) { - this(opts, null); + super(opts); } @Override diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/ListRemoteCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/ListRemoteCommand.java index 1ad954c4..9f7a9f9f 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/ListRemoteCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/ListRemoteCommand.java @@ -20,15 +20,13 @@ */ package org.zanata.client.commands; -import org.jboss.resteasy.client.ClientResponse; +import java.util.List; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.zanata.rest.client.ClientUtility; -import org.zanata.rest.client.ISourceDocResource; +import org.zanata.rest.client.SourceDocResourceClient; import org.zanata.rest.dto.resource.ResourceMeta; -import java.util.List; - /** * @author Sean Flanigan * @@ -47,18 +45,14 @@ public void run() throws Exception { log.info("Server: " + getOpts().getUrl()); log.info("Project: " + getOpts().getProj()); log.info("Version: " + getOpts().getProjectVersion()); - ISourceDocResource sourceDocResource = - getRequestFactory().getSourceDocResource(getOpts().getProj(), - getOpts().getProjectVersion()); - ClientResponse> response = - sourceDocResource.get(null); - ClientUtility.checkResult( - response, - getRequestFactory().getResourceURI(getOpts().getProj(), - getOpts().getProjectVersion())); - List list = response.getEntity(); + SourceDocResourceClient client = getClientFactory() + .getSourceDocResourceClient( + getOpts().getProj(), getOpts().getProjectVersion()); + + List list = client.getResourceMeta(null); + ConsoleInteractor console = new ConsoleInteractorImpl(); for (ResourceMeta doc : list) { - System.out.println(doc.getName()); + console.printfln(doc.getName()); } } diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/OptionsUtil.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/OptionsUtil.java index e7f02833..4bd5852f 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/OptionsUtil.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/OptionsUtil.java @@ -17,7 +17,7 @@ import org.zanata.client.config.LocaleList; import org.zanata.client.config.ZanataConfig; import org.zanata.client.exceptions.ConfigException; -import org.zanata.rest.client.ZanataProxyFactory; +import org.zanata.rest.client.RestClientFactory; import org.zanata.util.VersionUtility; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; @@ -268,22 +268,6 @@ public static void applyUserConfig(ConfigurableOptions opts, } } - /** - * Creates proxy factory that will perform an eager REST version check. - */ - public static ZanataProxyFactory createRequestFactory( - ConfigurableOptions opts) { - try { - checkMandatoryOptsForRequestFactory(opts); - return new ZanataProxyFactory(opts.getUrl().toURI(), - opts.getUsername(), opts.getKey(), - VersionUtility.getAPIVersionInfo(), opts.getLogHttp(), - opts.isDisableSSLCert()); - } catch (URISyntaxException e) { - throw new ConfigException(e); - } - } - private static void checkMandatoryOptsForRequestFactory( ConfigurableOptions opts) { if (opts.getUrl() == null) { @@ -300,30 +284,52 @@ private static void checkMandatoryOptsForRequestFactory( } } + public static String stripValidHolders(String rule) { + String temp = rule; + for (Placeholders placeholder : Placeholders.values()) { + temp = temp.replace(placeholder.holder(), ""); + } + return temp; + } + /** - * Creates proxy factory that will NOT perform an eager REST version check. - * You can call - * org.zanata.rest.client.ZanataProxyFactory#performVersionCheck() - * afterwards. + * Creates rest client factory that will perform an eager REST version check. */ - public static ZanataProxyFactory createRequestFactoryWithoutVersionCheck( - ConfigurableProjectOptions opts) { + public static RestClientFactory + createClientFactory( + O opts) { + checkMandatoryOptsForRequestFactory(opts); try { - checkMandatoryOptsForRequestFactory(opts); - return new ZanataProxyFactory(opts.getUrl().toURI(), - opts.getUsername(), opts.getKey(), - VersionUtility.getAPIVersionInfo(), opts.getLogHttp(), - opts.isDisableSSLCert(), false); + RestClientFactory restClientFactory = + new RestClientFactory(opts.getUrl().toURI(), + opts.getUsername(), opts.getKey(), + VersionUtility.getAPIVersionInfo(), + opts.getLogHttp(), + opts.isDisableSSLCert()); + restClientFactory.performVersionCheck(); + return restClientFactory; } catch (URISyntaxException e) { throw new ConfigException(e); } } - public static String stripValidHolders(String rule) { - String temp = rule; - for (Placeholders placeholder : Placeholders.values()) { - temp = temp.replace(placeholder.holder(), ""); + /** + * Creates rest client factory that will NOT perform an eager REST version + * check. You can call + * org.zanata.rest.client.RestClientFactory#performVersionCheck() + * afterwards. + */ + public static RestClientFactory + createClientFactoryWithoutVersionCheck( + O opts) { + checkMandatoryOptsForRequestFactory(opts); + try { + return new RestClientFactory(opts.getUrl().toURI(), + opts.getUsername(), opts.getKey(), + VersionUtility.getAPIVersionInfo(), opts.getLogHttp(), + opts.isDisableSSLCert()); + } catch (URISyntaxException e) { + throw new ConfigException(e); } - return temp; } } diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/PushPullCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/PushPullCommand.java index a7d41387..5425839d 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/PushPullCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/PushPullCommand.java @@ -35,7 +35,6 @@ import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; -import org.jboss.resteasy.client.ClientResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zanata.client.config.LocaleList; @@ -43,10 +42,9 @@ import org.zanata.client.etag.ETagCache; import org.zanata.client.etag.ETagCacheReaderWriter; import org.zanata.client.exceptions.ConfigException; -import org.zanata.rest.client.ClientUtility; -import org.zanata.rest.client.ISourceDocResource; -import org.zanata.rest.client.ITranslatedDocResource; -import org.zanata.rest.client.ZanataProxyFactory; +import org.zanata.rest.client.RestClientFactory; +import org.zanata.rest.client.SourceDocResourceClient; +import org.zanata.rest.client.TransDocResourceClient; import org.zanata.rest.dto.resource.Resource; import org.zanata.rest.dto.resource.ResourceMeta; import org.zanata.rest.dto.resource.TranslationsResource; @@ -64,35 +62,29 @@ public abstract class PushPullCommand extends protected static final String PROJECT_TYPE_OFFLINE_PO = "offlinepo"; - protected final ISourceDocResource sourceDocResource; - protected final ITranslatedDocResource translationResources; - protected URI uri; protected ETagCache eTagCache; private Marshaller marshaller; private String modulePrefix; + protected SourceDocResourceClient sourceDocResourceClient; + protected TransDocResourceClient transDocResourceClient; - public PushPullCommand(O opts, ZanataProxyFactory factory, - ISourceDocResource sourceDocResource, - ITranslatedDocResource translationResources, URI uri) { - super(opts, factory); - this.sourceDocResource = sourceDocResource; - this.translationResources = translationResources; - this.uri = uri; + public PushPullCommand(O opts, RestClientFactory clientFactory) { + super(opts, clientFactory); this.modulePrefix = opts.getEnableModules() ? getOpts().getCurrentModule() + opts.getModuleSuffix() : ""; this.loadETagCache(); - } - - private PushPullCommand(O opts, ZanataProxyFactory factory) { - this(opts, factory, factory.getSourceDocResource(opts.getProj(), - opts.getProjectVersion()), factory.getTranslatedDocResource( - opts.getProj(), opts.getProjectVersion()), factory - .getResourceURI(opts.getProj(), opts.getProjectVersion())); + sourceDocResourceClient = + getClientFactory().getSourceDocResourceClient(opts.getProj(), + opts.getProjectVersion()); + transDocResourceClient = + getClientFactory().getTransDocResourceClient(opts.getProj(), + opts.getProjectVersion()); } public PushPullCommand(O opts) { - this(opts, OptionsUtil.createRequestFactory(opts)); + this(opts, OptionsUtil.createClientFactory( + opts)); } protected void confirmWithUser(String message) throws IOException { @@ -171,11 +163,7 @@ protected List getQualifiedDocNamesForCurrentModuleFromServer() { // TODO use a cache which will be accessible to all invocations protected List getDocListForProjectIterationFromServer() { - ClientResponse> getResponse = - sourceDocResource.get(null); - ClientUtility.checkResult(getResponse, uri); - List remoteDocList = getResponse.getEntity(); - return remoteDocList; + return sourceDocResourceClient.getResourceMeta(null); } /** diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/PutProjectCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/PutProjectCommand.java index 4f1fc468..ffd8a045 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/PutProjectCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/PutProjectCommand.java @@ -1,16 +1,8 @@ package org.zanata.client.commands; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; - -import javax.xml.bind.JAXBException; - -import org.jboss.resteasy.client.ClientResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.zanata.rest.client.ClientUtility; -import org.zanata.rest.client.IProjectResource; +import org.zanata.rest.client.ProjectClient; import org.zanata.rest.dto.Project; /** @@ -26,8 +18,7 @@ public PutProjectCommand(PutProjectOptions opts) { } @Override - public void run() throws JAXBException, URISyntaxException, IOException, - Exception { + public void run() throws Exception { Project project = new Project(); project.setId(getOpts().getProjectSlug()); project.setName(getOpts().getProjectName()); @@ -45,11 +36,8 @@ public void run() throws JAXBException, URISyntaxException, IOException, log.debug("{}", project); // send project to rest api - IProjectResource projResource = - getRequestFactory().getProject(getOpts().getProjectSlug()); - URI uri = getRequestFactory().getProjectURI(getOpts().getProjectSlug()); - - ClientResponse response = projResource.put(project); - ClientUtility.checkResult(response, uri); + ProjectClient client = getClientFactory().getProjectClient( + getOpts().getProjectSlug()); + client.put(project); } } diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/PutUserCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/PutUserCommand.java index 27cba5cc..62a6e59f 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/PutUserCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/PutUserCommand.java @@ -1,16 +1,13 @@ package org.zanata.client.commands; -import java.net.URI; -import java.util.Arrays; -import java.util.HashSet; - -import org.jboss.resteasy.client.ClientResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.zanata.rest.client.ClientUtility; -import org.zanata.rest.client.IAccountResource; +import org.zanata.rest.client.AccountClient; import org.zanata.rest.dto.Account; +import com.google.common.base.Splitter; +import com.google.common.collect.Sets; + /** * @author Sean Flanigan * @@ -31,19 +28,15 @@ public void run() throws Exception { account.setPasswordHash(getOpts().getUserPasswordHash()); account.setApiKey(getOpts().getUserKey()); account.setEnabled(!getOpts().isUserDisabled()); - account.setRoles(new HashSet(Arrays.asList(getOpts() - .getUserRoles().split(",")))); - account.setTribes(new HashSet(Arrays.asList(getOpts() - .getUserLangs().split(",")))); + Splitter splitter = Splitter.on(",").trimResults().omitEmptyStrings(); + account.setRoles(Sets.newHashSet(splitter.split(getOpts().getUserRoles()))); + account.setTribes( + Sets.newHashSet(splitter.split(getOpts().getUserLangs()))); log.debug("{}", account); - IAccountResource iterResource = - getRequestFactory().getAccount(getOpts().getUserUsername()); - URI uri = - getRequestFactory().getAccountURI(getOpts().getUserUsername()); - ClientResponse response = iterResource.put(account); - ClientUtility.checkResult(response, uri); + getClientFactory().getAccountClient().put( + getOpts().getUserUsername(), account); } } diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/PutVersionCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/PutVersionCommand.java index 05335308..805b0993 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/PutVersionCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/PutVersionCommand.java @@ -1,12 +1,8 @@ package org.zanata.client.commands; -import java.net.URI; - -import org.jboss.resteasy.client.ClientResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.zanata.rest.client.ClientUtility; -import org.zanata.rest.client.IProjectIterationResource; +import org.zanata.rest.client.ProjectIterationClient; import org.zanata.rest.dto.ProjectIteration; /** @@ -35,16 +31,12 @@ public void run() throws Exception { } log.debug("{}", version); - IProjectIterationResource iterResource = - getRequestFactory().getProjectIteration( - getOpts().getVersionProject(), - getOpts().getVersionSlug()); - URI uri = - getRequestFactory().getProjectIterationURI( + ProjectIterationClient client = getClientFactory() + .getProjectIterationClient( getOpts().getVersionProject(), getOpts().getVersionSlug()); - ClientResponse response = iterResource.put(version); - ClientUtility.checkResult(response, uri); + + client.put(version); } } diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/UpdateChecker.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/UpdateChecker.java index b4d3f61f..b6f3da9b 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/UpdateChecker.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/UpdateChecker.java @@ -20,19 +20,17 @@ */ package org.zanata.client.commands; -import java.io.BufferedReader; +import static org.zanata.client.commands.ConsoleInteractorImpl.AnswerValidator; +import static org.zanata.client.commands.Messages._; +import static org.zanata.util.VersionUtility.getVersionInfo; + import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; -import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.regex.Matcher; import java.util.regex.Pattern; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.Response; import org.apache.commons.io.output.FileWriterWithEncoding; import org.fedorahosted.openprops.Properties; @@ -43,15 +41,16 @@ import org.joda.time.format.DateTimeFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Charsets; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; - -import static org.zanata.client.commands.ConsoleInteractorImpl.*; -import static org.zanata.client.commands.Messages._; -import static org.zanata.util.VersionUtility.getVersionInfo; +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.config.DefaultClientConfig; /** * This class checks whether there is newer version of client available. It will @@ -202,19 +201,23 @@ public void checkNewerVersion() { * @return latest version of client in sonatype oss */ private Optional checkLatestVersion(ConsoleInteractor console) { - Response response; + ClientResponse response; try { - Client client = ClientBuilder.newBuilder().build(); - WebTarget target = - client.target(sonatypeRestUrl) + DefaultClientConfig clientConfig = + new DefaultClientConfig(); + + Client client = com.sun.jersey.api.client.Client.create( + clientConfig); + WebResource target = + client.resource(sonatypeRestUrl) .path("artifact/maven/resolve") .queryParam("g", "org.zanata") .queryParam("a", "client") .queryParam("p", "pom") .queryParam("v", "LATEST") .queryParam("r", "releases"); - response = target.request().get(); - if (response.getStatus() != Response.Status.OK.getStatusCode()) { + response = target.get(ClientResponse.class); + if (response.getClientResponseStatus() != ClientResponse.Status.OK) { log.debug( "Failed to resolve latest client artifact [status {}]. Ignored", response.getStatus()); @@ -228,7 +231,7 @@ private Optional checkLatestVersion(ConsoleInteractor console) { } // cheap xml parsing String payload = - response.readEntity(String.class).replaceAll("\\n", ""); + response.getEntity(String.class).replaceAll("\\n", ""); Pattern pattern = Pattern.compile("^.+(.+).+"); Matcher matcher = pattern.matcher(payload); return matcher.matches() ? Optional.of(matcher.group(1)) : Optional diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/glossary/delete/GlossaryDeleteCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/glossary/delete/GlossaryDeleteCommand.java index c234ebcb..77acdf91 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/glossary/delete/GlossaryDeleteCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/glossary/delete/GlossaryDeleteCommand.java @@ -22,15 +22,13 @@ import org.apache.commons.lang.StringUtils; -import org.jboss.resteasy.client.ClientResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zanata.client.commands.ConfigurableCommand; import org.zanata.client.commands.OptionsUtil; import org.zanata.common.LocaleId; -import org.zanata.rest.client.ClientUtility; -import org.zanata.rest.client.IGlossaryResource; -import org.zanata.rest.client.ZanataProxyFactory; +import org.zanata.rest.client.GlossaryClient; +import org.zanata.rest.client.RestClientFactory; /** * @@ -41,22 +39,16 @@ public class GlossaryDeleteCommand extends ConfigurableCommand { private static final Logger log = LoggerFactory .getLogger(GlossaryDeleteCommand.class); - - private final IGlossaryResource glossaryResource; + private final GlossaryClient client; public GlossaryDeleteCommand(GlossaryDeleteOptions opts, - ZanataProxyFactory factory, IGlossaryResource glossaryResource) { - super(opts, factory); - this.glossaryResource = glossaryResource; - } - - private GlossaryDeleteCommand(GlossaryDeleteOptions opts, - ZanataProxyFactory factory) { - this(opts, factory, factory.getGlossaryResource()); + RestClientFactory clientFactory) { + super(opts, clientFactory); + client = getClientFactory().getGlossaryClient(); } public GlossaryDeleteCommand(GlossaryDeleteOptions opts) { - this(opts, OptionsUtil.createRequestFactory(opts)); + this(opts, OptionsUtil.createClientFactory(opts)); } @Override @@ -66,17 +58,13 @@ public void run() throws Exception { log.info("Locale to delete: {}", getOpts().getlang()); log.info("Delete entire glossary?: {}", getOpts().getAllGlossary()); - ClientResponse response; - if (getOpts().getAllGlossary()) { - response = glossaryResource.deleteGlossaries(); + client.deleteAll(); } else if (!StringUtils.isEmpty(getOpts().getlang())) { - response = - glossaryResource.deleteGlossary(new LocaleId(getOpts() - .getlang())); + client.delete(new LocaleId(getOpts() + .getlang())); } else { throw new RuntimeException("Option 'zanata.lang' is required."); } - ClientUtility.checkResult(response); } } diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/glossary/push/GlossaryPushCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/glossary/push/GlossaryPushCommand.java index 3fdcc8f8..c085b482 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/glossary/push/GlossaryPushCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/glossary/push/GlossaryPushCommand.java @@ -31,7 +31,6 @@ import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.StringUtils; -import org.jboss.resteasy.client.ClientResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zanata.adapter.glossary.AbstractGlossaryPushReader; @@ -41,9 +40,8 @@ import org.zanata.client.commands.OptionsUtil; import org.zanata.client.config.LocaleMapping; import org.zanata.common.LocaleId; -import org.zanata.rest.client.ClientUtility; -import org.zanata.rest.client.IGlossaryResource; -import org.zanata.rest.client.ZanataProxyFactory; +import org.zanata.rest.client.GlossaryClient; +import org.zanata.rest.client.RestClientFactory; import org.zanata.rest.dto.Glossary; /** @@ -58,21 +56,17 @@ public class GlossaryPushCommand extends private static final Map glossaryReaders = new HashMap(); - private final IGlossaryResource glossaryResource; + private final GlossaryClient client; public GlossaryPushCommand(GlossaryPushOptions opts, - ZanataProxyFactory factory, IGlossaryResource glossaryResource) { - super(opts, factory); - this.glossaryResource = glossaryResource; + RestClientFactory clientFactory) { + super(opts, clientFactory); + client = getClientFactory().getGlossaryClient(); } - private GlossaryPushCommand(GlossaryPushOptions opts, - ZanataProxyFactory factory) { - this(opts, factory, factory.getGlossaryResource()); - } public GlossaryPushCommand(GlossaryPushOptions opts) { - this(opts, OptionsUtil.createRequestFactory(opts)); + this(opts, OptionsUtil.createClientFactory(opts)); glossaryReaders.put("po", new GlossaryPoReader( getLocaleFromMap(getOpts().getSourceLang()), @@ -162,9 +156,7 @@ public void run() throws Exception { int totalDone = 0; for (Glossary glossary : glossaries) { log.debug(glossary.toString()); - ClientResponse response = glossaryResource.put(glossary); - ClientUtility.checkResult(response); - response.releaseConnection(); + client.put(glossary); totalDone = totalDone + glossary.getGlossaryEntries().size(); log.info("Pushed " + totalDone + " of " + totalEntries + " entries"); } diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/init/InitCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/init/InitCommand.java index 53a2d927..3da170e6 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/init/InitCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/init/InitCommand.java @@ -40,7 +40,6 @@ import org.apache.commons.io.FileUtils; import org.apache.log4j.Level; import org.apache.log4j.LogManager; -import org.jboss.resteasy.client.ClientResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zanata.client.commands.ConfigurableCommand; @@ -50,11 +49,13 @@ import org.zanata.client.commands.OptionsUtil; import org.zanata.client.config.ZanataConfig; import org.zanata.client.util.VersionComparator; -import org.zanata.rest.client.ZanataProxyFactory; +import org.zanata.rest.client.ProjectIterationClient; +import org.zanata.rest.client.RestClientFactory; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Strings; +import com.google.common.base.Throwables; /** * @author Patrick Huang { private static final Logger log = LoggerFactory .getLogger(InitCommand.class); - private static final ZanataProxyFactory mockFactory = - MockZanataProxyFactory.mockFactory; private static final String ITERATION_URL = "%siteration/view/%s/%s"; private ConsoleInteractor console; - private ZanataProxyFactory requestFactory; private ProjectConfigHandler projectConfigHandler; private UserConfigHandler userConfigHandler; public InitCommand(InitOptions opts) { - // we don't have all mandatory information yet. Can't create a real - // proxy factory. - super(opts, mockFactory); + super(opts); console = new ConsoleInteractorImpl(); projectConfigHandler = new ProjectConfigHandler(console, getOpts()); @@ -84,10 +80,9 @@ public InitCommand(InitOptions opts) { @VisibleForTesting protected InitCommand(InitOptions opts, ConsoleInteractor console, - ZanataProxyFactory requestFactory) { - super(opts, mockFactory); + RestClientFactory restClientFactory) { + super(opts, restClientFactory); this.console = console; - this.requestFactory = requestFactory; projectConfigHandler = new ProjectConfigHandler(console, getOpts()); userConfigHandler = new UserConfigHandler(console, getOpts()); @@ -105,9 +100,8 @@ protected void run() throws Exception { // Select or create a project and version new ProjectPrompt(console, getOpts(), - getRequestFactory(), new ProjectIterationPrompt(console, getOpts(), - getRequestFactory())) + getClientFactory()), getClientFactory()) .selectOrCreateNewProjectAndVersion(); advancedSettingsReminder(); @@ -137,7 +131,7 @@ protected void run() throws Exception { @VisibleForTesting protected void ensureServerVersion() { String serverVersion = - getRequestFactory().getServerVersionInfo().getVersionNo(); + getClientFactory().getServerVersionInfo().getVersionNo(); if (new VersionComparator().compare(serverVersion, "3.4.0") < 0) { console.printfln(Warning, _("server.incompatible")); @@ -205,24 +199,14 @@ private static String getProjectIterationUrl(URL server, String projectSlug, } - public static void offerRetryOnServerError(ClientResponse response, + public static void offerRetryOnServerError(Exception e, ConsoleInteractor consoleInteractor) { consoleInteractor.printfln(Warning, _("server.error"), - response.getEntity(String.class)); + Throwables.getRootCause(e).getMessage()); consoleInteractor.printf(Question, _("server.error.try.again")); consoleInteractor.expectYes(); } - public ZanataProxyFactory getRequestFactory() { - if (requestFactory != null) { - return requestFactory; - } else { - requestFactory = OptionsUtil.createRequestFactory(getOpts()); - console.blankLine(); - return requestFactory; - } - } - /** * Downloads the zanata.xml config file using REST api. * @@ -236,20 +220,23 @@ public ZanataProxyFactory getRequestFactory() { @VisibleForTesting protected void downloadZanataXml(String projectId, String iterationId, File configFileDest) throws IOException { - ClientResponse response = - getRequestFactory().getProjectIteration(projectId, iterationId) - .sampleConfiguration(); - if (response.getStatus() >= 399) { - offerRetryOnServerError(response, console); + ProjectIterationClient projectIterationClient = getClientFactory() + .getProjectIterationClient(projectId, iterationId); + + String content; + try { + content = projectIterationClient.sampleConfiguration(); + } catch (Exception e) { + offerRetryOnServerError(e, console); downloadZanataXml(projectId, iterationId, configFileDest); return; } + boolean created = configFileDest.createNewFile(); Preconditions.checkState(created, "Can not create %s. Make sure permission is writable.", configFileDest); - String content = (String) response.getEntity(String.class); log.debug("project config from the server:\n{}", content); FileUtils.write(configFileDest, content, UTF_8); getOpts().setProjectConfig(configFileDest); @@ -281,13 +268,4 @@ protected void writeToConfig(File srcDir, String includes, String excludes, getOpts().getProjectConfig()); } - // we don't have all mandatory information yet - private static class MockZanataProxyFactory extends ZanataProxyFactory { - private static final MockZanataProxyFactory mockFactory = - new MockZanataProxyFactory(); - - private MockZanataProxyFactory() { - super(); - } - } } diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/init/ProjectIterationPrompt.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/init/ProjectIterationPrompt.java index ae81bda1..c0ed91fb 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/init/ProjectIterationPrompt.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/init/ProjectIterationPrompt.java @@ -20,12 +20,19 @@ */ package org.zanata.client.commands.init; +import static org.zanata.client.commands.ConsoleInteractor.DisplayMode.Confirmation; +import static org.zanata.client.commands.ConsoleInteractor.DisplayMode.Hint; +import static org.zanata.client.commands.ConsoleInteractor.DisplayMode.Question; +import static org.zanata.client.commands.ConsoleInteractorImpl.AnswerValidatorImpl.expect; +import static org.zanata.client.commands.Messages._; + import java.util.List; -import org.jboss.resteasy.client.ClientResponse; import org.zanata.client.commands.ConsoleInteractor; import org.zanata.common.EntityStatus; -import org.zanata.rest.client.ZanataProxyFactory; +import org.zanata.rest.client.ProjectClient; +import org.zanata.rest.client.ProjectIterationClient; +import org.zanata.rest.client.RestClientFactory; import org.zanata.rest.dto.Project; import org.zanata.rest.dto.ProjectIteration; @@ -33,12 +40,7 @@ import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; - -import static org.zanata.client.commands.ConsoleInteractor.DisplayMode.Confirmation; -import static org.zanata.client.commands.ConsoleInteractor.DisplayMode.Hint; -import static org.zanata.client.commands.ConsoleInteractor.DisplayMode.Question; -import static org.zanata.client.commands.ConsoleInteractorImpl.AnswerValidatorImpl.expect; -import static org.zanata.client.commands.Messages._; +import com.sun.jersey.api.client.UniformInterfaceException; /** * @author Patrick Huang versionIndexes = Lists.newArrayList(); @@ -87,6 +88,7 @@ protected void selectVersion() { consoleInteractor .printf("%d)", oneBasedIndex) .printfln(Hint, iteration.getId()); + oneBasedIndex++; } consoleInteractor.printf(Question, _("select.version.prompt")); String selection = @@ -104,14 +106,13 @@ protected void createNewVersion() { String versionId = consoleInteractor.expectAnyAnswer(); ProjectIteration iteration = new ProjectIteration(versionId); iteration.setProjectType(opts.getProjectType()); - ClientResponse response = - proxyFactory.getProjectIteration(opts.getProj(), versionId) - .put(iteration); - if (response.getStatus() >= 399) { - InitCommand.offerRetryOnServerError(response, consoleInteractor); + try { + clientFactory.getProjectIterationClient(opts.getProj(), versionId) + .put(iteration); + } catch (UniformInterfaceException ex) { + InitCommand.offerRetryOnServerError(ex, consoleInteractor); createNewVersion(); } - response.releaseConnection(); opts.setProjectVersion(versionId); consoleInteractor.printfln(Confirmation, _("project.version.created")); diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/init/ProjectPrompt.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/init/ProjectPrompt.java index e707b151..8a7f95ab 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/init/ProjectPrompt.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/init/ProjectPrompt.java @@ -20,15 +20,23 @@ */ package org.zanata.client.commands.init; +import static org.zanata.client.commands.ConsoleInteractor.DisplayMode.Confirmation; +import static org.zanata.client.commands.ConsoleInteractor.DisplayMode.Hint; +import static org.zanata.client.commands.ConsoleInteractor.DisplayMode.Question; +import static org.zanata.client.commands.ConsoleInteractorImpl.AnswerValidatorImpl; +import static org.zanata.client.commands.Messages._; + import java.util.Collections; import java.util.List; -import org.jboss.resteasy.client.ClientResponse; import org.zanata.client.commands.ConsoleInteractor; import org.zanata.common.EntityStatus; import org.zanata.common.ProjectType; -import org.zanata.rest.client.ZanataProxyFactory; +import org.zanata.rest.client.ProjectClient; +import org.zanata.rest.client.ProjectsClient; +import org.zanata.rest.client.RestClientFactory; import org.zanata.rest.dto.Project; + import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Joiner; @@ -37,13 +45,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; - -import static org.zanata.client.commands.ConsoleInteractor.DisplayMode.Confirmation; -import static org.zanata.client.commands.ConsoleInteractor.DisplayMode.Hint; -import static org.zanata.client.commands.ConsoleInteractor.DisplayMode.Question; -import static org.zanata.client.commands.ConsoleInteractorImpl.*; -import static org.zanata.client.commands.Messages._; -import static org.zanata.client.commands.StringUtil.indent; +import com.sun.jersey.api.client.UniformInterfaceException; /** * @author Patrick Huang @@ -54,18 +56,18 @@ class ProjectPrompt { private final InitOptions opts; private final ProjectIterationPrompt projectIterationPrompt; - private final ZanataProxyFactory proxyFactory; + private final RestClientFactory clientFactory; // state variables private List allProjects = Collections.emptyList(); private List filteredProjects = Collections.emptyList(); ProjectPrompt(ConsoleInteractor consoleInteractor, InitOptions opts, - ZanataProxyFactory proxyFactory, - ProjectIterationPrompt projectIterationPrompt) { + ProjectIterationPrompt projectIterationPrompt, + RestClientFactory clientFactory) { this.consoleInteractor = consoleInteractor; this.opts = opts; - this.proxyFactory = proxyFactory; this.projectIterationPrompt = projectIterationPrompt; + this.clientFactory = clientFactory; } /** @@ -159,8 +161,7 @@ private void ensureActiveProjects() { // TODO add optional query param to search projects (limit return // values) Project[] projectsArray = - proxyFactory.getProjectsResource().get() - .getEntity(Project[].class); + clientFactory.getProjectsClient().getProjects(); allProjects = ImmutableList.copyOf(Iterables .filter(Lists.newArrayList(projectsArray), new Predicate() { @@ -197,13 +198,16 @@ protected void createNewProject() { String projectType = consoleInteractor.expectAnswerWithRetry( AnswerValidatorImpl.expect(projectTypeList)); - ClientResponse response = proxyFactory.getProject(projectId) - .put(new Project(projectId, projectName, projectType)); - if (response.getStatus() >= 399) { - InitCommand.offerRetryOnServerError(response, consoleInteractor); - createNewProject(); + ProjectClient projectClient = clientFactory.getProjectClient(projectId); + Project project = new Project(projectId, projectName, projectType); + try { + projectClient.put(project); + } catch (UniformInterfaceException e) { + if (e.getResponse().getStatus() >= 399) { + InitCommand.offerRetryOnServerError(e, consoleInteractor); + createNewProject(); + } } - response.releaseConnection(); consoleInteractor.printfln(Confirmation, _("project.created")); opts.setProj(projectId); opts.setProjectType(projectType); diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/init/SourceConfigPrompt.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/init/SourceConfigPrompt.java index 7407a9cc..8f7fa6fe 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/init/SourceConfigPrompt.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/init/SourceConfigPrompt.java @@ -36,9 +36,9 @@ import org.zanata.client.commands.push.PushCommand; import org.zanata.client.commands.push.PushOptions; import org.zanata.client.commands.push.PushOptionsImpl; -import org.zanata.rest.client.ZanataProxyFactory; - -import com.google.common.base.Throwables; +import org.zanata.rest.client.AsyncProcessClient; +import org.zanata.rest.client.CopyTransClient; +import org.zanata.rest.client.RestClientFactory; import static org.zanata.client.commands.ConsoleInteractor.DisplayMode.Hint; import static org.zanata.client.commands.ConsoleInteractor.DisplayMode.Question; @@ -85,13 +85,13 @@ public SourceConfigPrompt( pushOptions.setKey(opts.getKey()); pushOptions.setLocaleMapList(opts.getLocaleMapList()); - ZanataProxyFactory proxyFactory = OptionsUtil - .createRequestFactoryWithoutVersionCheck(pushOptions); + RestClientFactory clientFactory = + OptionsUtil.createClientFactoryWithoutVersionCheck(pushOptions); pushCommand = - new PushCommand(pushOptions, proxyFactory, null, - null, proxyFactory - .getResourceURI(pushOptions.getProj(), - pushOptions.getProjectVersion())); + new PushCommand(pushOptions, + clientFactory.getCopyTransClient(), + clientFactory.getAsyncProcessClient(), + clientFactory); } SourceConfigPrompt promptUser() throws Exception { diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/init/TransConfigPrompt.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/init/TransConfigPrompt.java index a516d2d7..8534d67b 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/init/TransConfigPrompt.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/init/TransConfigPrompt.java @@ -31,7 +31,7 @@ import org.zanata.client.commands.pull.PullStrategy; import org.zanata.client.config.LocaleList; import org.zanata.client.config.LocaleMapping; -import org.zanata.rest.client.ZanataProxyFactory; +import org.zanata.rest.client.RestClientFactory; import com.google.common.base.Function; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; @@ -73,11 +73,11 @@ public TransConfigPrompt(ConsoleInteractor console, pullOptions.setProjectVersion(opts.getProjectVersion()); pullOptions.setProjectType(opts.getProjectType()); pullOptions.setLocaleMapList(opts.getLocaleMapList()); - ZanataProxyFactory proxyFactory = - OptionsUtil.createRequestFactoryWithoutVersionCheck(opts); - pullCommand = new PullCommand(pullOptions, proxyFactory, null, null, - proxyFactory.getResourceURI(opts.getProj(), - opts.getProjectVersion())); + + RestClientFactory clientFactory = + OptionsUtil.createClientFactoryWithoutVersionCheck(opts); + pullCommand = new PullCommand(pullOptions, + clientFactory); } TransConfigPrompt promptUser() throws Exception { diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/pull/PullCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/pull/PullCommand.java index 81cdbb6d..ae9faddd 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/pull/PullCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/pull/PullCommand.java @@ -4,7 +4,6 @@ import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -import java.net.URI; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -12,10 +11,8 @@ import java.util.TreeSet; import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.Response; import org.apache.commons.lang.StringUtils; -import org.jboss.resteasy.client.ClientResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zanata.client.commands.PushPullCommand; @@ -27,14 +24,14 @@ import org.zanata.common.LocaleId; import org.zanata.common.io.FileDetails; import org.zanata.rest.RestUtil; -import org.zanata.rest.client.ClientUtility; -import org.zanata.rest.client.ISourceDocResource; -import org.zanata.rest.client.ITranslatedDocResource; -import org.zanata.rest.client.ZanataProxyFactory; +import org.zanata.rest.client.ClientUtil; +import org.zanata.rest.client.RestClientFactory; import org.zanata.rest.dto.resource.Resource; import org.zanata.rest.dto.resource.TranslationsResource; import org.zanata.util.HashUtil; +import com.sun.jersey.api.client.ClientResponse; + /** * @author Sean Flanigan sflaniga@redhat.com @@ -62,10 +59,8 @@ public PullCommand(PullOptions opts) { super(opts); } - public PullCommand(PullOptions opts, ZanataProxyFactory factory, - ISourceDocResource sourceDocResource, - ITranslatedDocResource translationResources, URI uri) { - super(opts, factory, sourceDocResource, translationResources, uri); + public PullCommand(PullOptions opts, RestClientFactory clientFactory) { + super(opts, clientFactory); } public PullStrategy createStrategy(PullOptions opts) @@ -219,11 +214,8 @@ && getOpts().getPullType() == PushPullType.Source) { RestUtil.convertToDocumentURIId(qualifiedDocName); boolean createSkeletons = getOpts().getCreateSkeletons(); if (strat.needsDocToWriteTrans() || pullSrc || createSkeletons) { - ClientResponse resourceResponse = - sourceDocResource.getResource(docUri, - strat.getExtensions()); - ClientUtility.checkResult(resourceResponse, uri); - doc = resourceResponse.getEntity(); + doc = sourceDocResourceClient.getResource(docUri, + strat.getExtensions()); doc.setName(localDocName); } if (pullSrc) { @@ -253,32 +245,28 @@ && getOpts().getPullType() == PushPullType.Source) { } } - ClientResponse transResponse = - translationResources.getTranslations(docUri, + ClientResponse transResponse = + transDocResourceClient.getTranslations(docUri, locale, strat.getExtensions(), createSkeletons, eTag); // ignore 404 (no translation yet for specified // document) - if (transResponse.getResponseStatus() == Response.Status.NOT_FOUND) { + if (transResponse.getClientResponseStatus() == ClientResponse.Status.NOT_FOUND) { if (!createSkeletons) { log.info( "No translations found in locale {} for document {}", locale, localDocName); - // We need to release connection. - // see - // http://stackoverflow.com/questions/4612573/exception-using-httprequest-execute-invalid-use-of-singleclientconnmanager-c - transResponse.releaseConnection(); } else { // Write the skeleton writeTargetDoc(strat, localDocName, locMapping, doc, null, - transResponse.getResponseHeaders() + transResponse.getHeaders() .getFirst(HttpHeaders.ETAG)); } } // 304 NOT MODIFIED (the document can stay the same) - else if (transResponse.getResponseStatus() == Response.Status.NOT_MODIFIED) { + else if (transResponse.getClientResponseStatus() == ClientResponse.Status.NOT_MODIFIED) { log.info( "No changes in translations for locale {} and document {}", locale, localDocName); @@ -291,26 +279,26 @@ else if (transResponse.getResponseStatus() == Response.Status.NOT_MODIFIED) { if (!fileChecksum.equals(eTagCacheEntry .getLocalFileMD5())) { transResponse = - translationResources.getTranslations( + transDocResourceClient.getTranslations( docUri, locale, strat.getExtensions(), createSkeletons, null); - ClientUtility.checkResult(transResponse, uri); + ClientUtil.checkResult(transResponse); // rewrite the target document writeTargetDoc(strat, localDocName, locMapping, - doc, transResponse.getEntity(), - transResponse.getResponseHeaders() + doc, transResponse.getEntity(TranslationsResource.class), + transResponse.getHeaders() .getFirst(HttpHeaders.ETAG)); } } else { - ClientUtility.checkResult(transResponse, uri); + ClientUtil.checkResult(transResponse); TranslationsResource targetDoc = - transResponse.getEntity(); + transResponse.getEntity(TranslationsResource.class); // Write the target document writeTargetDoc(strat, localDocName, locMapping, doc, targetDoc, - transResponse.getResponseHeaders() + transResponse.getHeaders() .getFirst(HttpHeaders.ETAG)); } } diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/pull/RawPullCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/pull/RawPullCommand.java index efaaa4d7..3880155e 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/pull/RawPullCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/pull/RawPullCommand.java @@ -22,15 +22,10 @@ import java.io.IOException; import java.io.InputStream; -import java.net.URI; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; - -import org.jboss.resteasy.client.ClientResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zanata.client.commands.PushPullCommand; @@ -39,13 +34,13 @@ import org.zanata.client.config.LocaleMapping; import org.zanata.client.exceptions.ConfigException; import org.zanata.common.LocaleId; -import org.zanata.rest.client.ClientUtility; -import org.zanata.rest.client.IFileResource; -import org.zanata.rest.client.ISourceDocResource; -import org.zanata.rest.client.ITranslatedDocResource; -import org.zanata.rest.client.ZanataProxyFactory; +import org.zanata.rest.client.ClientUtil; +import org.zanata.rest.client.FileResourceClient; +import org.zanata.rest.client.RestClientFactory; import org.zanata.rest.service.FileResource; + import com.google.common.annotations.VisibleForTesting; +import com.sun.jersey.api.client.ClientResponse; /** * @@ -57,21 +52,19 @@ public class RawPullCommand extends PushPullCommand { private static final Logger log = LoggerFactory .getLogger(RawPullCommand.class); - private IFileResource fileResource; + private FileResourceClient fileResourceClient; public RawPullCommand(PullOptions opts) { super(opts); - this.fileResource = getRequestFactory().getFileResource(); + fileResourceClient = getClientFactory().getFileResourceClient(); } @VisibleForTesting public RawPullCommand(PullOptions opts, - ZanataProxyFactory factory, - ISourceDocResource sourceDocResource, - ITranslatedDocResource translationResources, - URI uri, IFileResource fileResource) { - super(opts, factory, sourceDocResource, translationResources, uri); - this.fileResource = fileResource; + FileResourceClient fileResourceClient, + RestClientFactory clientFactory) { + super(opts, clientFactory); + this.fileResourceClient = fileResourceClient; } @Override @@ -157,20 +150,19 @@ public void run() throws IOException { if (pullSrc) { ClientResponse response = - fileResource.downloadSourceFile( + fileResourceClient.downloadSourceFile( getOpts().getProj(), getOpts() .getProjectVersion(), FileResource.FILETYPE_RAW_SOURCE_DOCUMENT, qualifiedDocName); - if (response.getResponseStatus() == Status.NOT_FOUND) { + if (response.getClientResponseStatus() == ClientResponse.Status.NOT_FOUND) { log.warn( "No source document file is available for [{}]. Skipping.", qualifiedDocName); } else { - ClientUtility.checkResult(response, uri); - InputStream srcDoc = - (InputStream) response - .getEntity(InputStream.class); + ClientUtil.checkResult(response); + InputStream srcDoc = response + .getEntity(InputStream.class); if (srcDoc != null) { try { strat.writeSrcFile(localDocName, srcDoc); @@ -194,16 +186,16 @@ public void run() throws IOException { for (LocaleMapping locMapping : locales) { LocaleId locale = new LocaleId(locMapping.getLocale()); ClientResponse response = - fileResource.downloadTranslationFile(getOpts() + fileResourceClient.downloadTranslationFile(getOpts() .getProj(), getOpts() .getProjectVersion(), locale.getId(), fileExtension, qualifiedDocName); - if (response.getResponseStatus() == Response.Status.NOT_FOUND) { + if (response.getClientResponseStatus() == ClientResponse.Status.NOT_FOUND) { log.info( "No translation document file found in locale {} for document [{}]", locale, qualifiedDocName); } else { - ClientUtility.checkResult(response, uri); + ClientUtil.checkResult(response); InputStream transDoc = (InputStream) response .getEntity(InputStream.class); diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/OfflinePoStrategy.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/OfflinePoStrategy.java index c44451d4..dda495cd 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/OfflinePoStrategy.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/OfflinePoStrategy.java @@ -22,16 +22,13 @@ import java.io.File; import java.io.IOException; -import java.net.URI; import java.util.HashSet; import java.util.List; import java.util.Set; import com.google.common.collect.ImmutableList; -import org.jboss.resteasy.client.ClientResponse; import org.zanata.adapter.po.PoReader2; -import org.zanata.rest.client.ClientUtility; -import org.zanata.rest.client.ISourceDocResource; +import org.zanata.rest.client.SourceDocResourceClient; import org.zanata.rest.dto.resource.Resource; import org.zanata.rest.dto.resource.ResourceMeta; @@ -42,15 +39,12 @@ * href="mailto:damason@redhat.com">damason@redhat.com */ public class OfflinePoStrategy extends GettextDirStrategy { - private final ISourceDocResource sourceDocResource; - private final PoReader2 poReader; + private SourceDocResourceClient client; + private final PoReader2 poReader = new PoReader2(true); - private final URI uri; - public OfflinePoStrategy(ISourceDocResource sourceDocResource, URI uri) { - this.sourceDocResource = sourceDocResource; - this.uri = uri; - poReader = new PoReader2(true); + public OfflinePoStrategy(SourceDocResourceClient client) { + this.client = client; } @Override @@ -72,10 +66,7 @@ public Set findDocNames(File srcDir, ImmutableList includes, ImmutableList excludes, boolean useDefaultExclude, boolean caseSensitive, boolean excludeLocaleFilenames) throws IOException { - ClientResponse> getResponse = - sourceDocResource.get(null); - ClientUtility.checkResult(getResponse, uri); - List remoteDocList = getResponse.getEntity(); + List remoteDocList = client.getResourceMeta(null); Set localDocNames = new HashSet(); for (ResourceMeta doc : remoteDocList) { localDocNames.add(doc.getName()); diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushCommand.java index 2125d4ce..5b5facba 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushCommand.java @@ -2,7 +2,6 @@ import java.io.File; import java.io.IOException; -import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -15,11 +14,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import javax.ws.rs.core.Response; - import org.apache.commons.lang.StringUtils; -import org.jboss.resteasy.client.ClientResponse; -import org.jboss.resteasy.client.ClientResponseFailure; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zanata.adapter.xliff.XliffCommon.ValidationType; @@ -32,21 +27,17 @@ import org.zanata.common.MergeType; import org.zanata.rest.RestUtil; import org.zanata.rest.StringSet; -import org.zanata.rest.client.ClientUtility; -import org.zanata.rest.client.ISourceDocResource; -import org.zanata.rest.client.ITranslatedDocResource; -import org.zanata.rest.client.ZanataProxyFactory; +import org.zanata.rest.client.AsyncProcessClient; +import org.zanata.rest.client.CopyTransClient; +import org.zanata.rest.client.RestClientFactory; import org.zanata.rest.dto.CopyTransStatus; import org.zanata.rest.dto.ProcessStatus; import org.zanata.rest.dto.resource.Resource; import org.zanata.rest.dto.resource.ResourceMeta; import org.zanata.rest.dto.resource.TranslationsResource; -import org.zanata.rest.service.AsynchronousProcessResource; -import org.zanata.rest.service.CopyTransResource; -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableMap; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.UniformInterfaceException; /** * @author Sean Flanigan { private static final Map strategies = new HashMap(); - private CopyTransResource copyTransResource; - private AsynchronousProcessResource asyncProcessResource; + private CopyTransClient copyTransClient; + private AsyncProcessClient asyncProcessClient; public static interface TranslationResourcesVisitor { void visit(LocaleMapping locale, TranslationsResource targetDoc); @@ -79,24 +70,26 @@ public static interface TranslationResourcesVisitor { strategies.put(PROJECT_TYPE_XML, new XmlStrategy()); strategies.put( PROJECT_TYPE_OFFLINE_PO, - new OfflinePoStrategy(getRequestFactory().getSourceDocResource( - getOpts().getProj(), getOpts().getProjectVersion()), - uri)); + new OfflinePoStrategy(getClientFactory() + .getSourceDocResourceClient(getOpts().getProj(), + getOpts() + .getProjectVersion()))); } public PushCommand(PushOptions opts) { super(opts); - copyTransResource = getRequestFactory().getCopyTransResource(); - asyncProcessResource = - getRequestFactory().getAsynchronousProcessResource(); + copyTransClient = getClientFactory().getCopyTransClient(); + asyncProcessClient = getClientFactory().getAsyncProcessClient(); } - public PushCommand(PushOptions opts, ZanataProxyFactory factory, - ISourceDocResource sourceDocResource, - ITranslatedDocResource translationResources, URI uri) { - super(opts, factory, sourceDocResource, translationResources, uri); - copyTransResource = factory.getCopyTransResource(); - asyncProcessResource = factory.getAsynchronousProcessResource(); + public PushCommand(PushOptions opts, + CopyTransClient copyTransClient, + AsyncProcessClient asyncProcessClient, + RestClientFactory clientFactory) { + super(opts, + clientFactory); + this.copyTransClient = copyTransClient; + this.asyncProcessClient = asyncProcessClient; } public AbstractPushStrategy getStrategy(PushOptions pushOptions) { @@ -504,7 +497,7 @@ private void pushSrcDocToServer(final String docUri, final Resource srcDoc, // is deprecated. // see PushCommand.copyTransForDocument ProcessStatus status = - asyncProcessResource.startSourceDocCreationOrUpdate(docUri, + asyncProcessClient.startSourceDocCreationOrUpdate(docUri, getOpts().getProj(), getOpts().getProjectVersion(), srcDoc, extensions, false); @@ -533,7 +526,7 @@ private void pushSrcDocToServer(final String docUri, final Resource srcDoc, case NotAccepted: // try to submit the process again status = - asyncProcessResource + asyncProcessClient .startSourceDocCreationOrUpdate(docUri, getOpts().getProj(), getOpts() .getProjectVersion(), @@ -544,7 +537,7 @@ private void pushSrcDocToServer(final String docUri, final Resource srcDoc, } wait(POLL_PERIOD); // Wait before retrying - status = asyncProcessResource.getProcessStatus(status.getUrl()); + status = asyncProcessClient.getProcessStatus(status.getUrl()); } ConsoleUtils.endProgressFeedback(); @@ -620,7 +613,7 @@ private void pushTargetDocToServer(final String docUri, ConsoleUtils.startProgressFeedback(); ProcessStatus status = - asyncProcessResource.startTranslatedDocCreationOrUpdate( + asyncProcessClient.startTranslatedDocCreationOrUpdate( docUri, getOpts().getProj(), getOpts() .getProjectVersion(), new LocaleId(locale.getLocale()), targetDoc, @@ -652,7 +645,7 @@ private void pushTargetDocToServer(final String docUri, case NotAccepted: // try to submit the process again status = - asyncProcessResource + asyncProcessClient .startTranslatedDocCreationOrUpdate(docUri, getOpts().getProj(), getOpts() .getProjectVersion(), @@ -665,7 +658,7 @@ targetDoc, extensions, getOpts() } wait(POLL_PERIOD); // Wait before retrying - status = asyncProcessResource.getProcessStatus(status.getUrl()); + status = asyncProcessClient.getProcessStatus(status.getUrl()); } ConsoleUtils.endProgressFeedback(); @@ -688,10 +681,7 @@ private void deleteSourceDocFromServer(String qualifiedDocName) { if (!getOpts().isDryRun()) { log.info("deleting resource {} from server", qualifiedDocName); String docUri = RestUtil.convertToDocumentURIId(qualifiedDocName); - ClientResponse deleteResponse = - sourceDocResource.deleteResource(docUri); - ClientUtility.checkResult(deleteResponse, uri); - deleteResponse.releaseConnection(); + sourceDocResourceClient.deleteResource(docUri); } else { log.info( "deleting resource {} from server (skipped due to dry run)", @@ -706,7 +696,7 @@ private void copyTransForDocument(String docName) { } log.info("Running Copy Trans for " + docName); try { - this.copyTransResource.startCopyTrans(getOpts().getProj(), + this.copyTransClient.startCopyTrans(getOpts().getProj(), getOpts().getProjectVersion(), docName); } catch (Exception ex) { log.warn("Could not start Copy Trans for above document. Proceeding"); @@ -716,12 +706,12 @@ private void copyTransForDocument(String docName) { try { copyTransStatus = - this.copyTransResource.getCopyTransStatus(getOpts() + this.copyTransClient.getCopyTransStatus(getOpts() .getProj(), getOpts().getProjectVersion(), docName); - } catch (ClientResponseFailure failure) { + } catch (UniformInterfaceException failure) { // 404 - Probably because of an old server - if (failure.getResponse().getResponseStatus() == Response.Status.NOT_FOUND) { - if (getRequestFactory() + if (failure.getResponse().getClientResponseStatus() == ClientResponse.Status.NOT_FOUND) { + if (getClientFactory() .compareToServerVersion("1.8.0-SNAPSHOT") < 0) { log.warn("Copy Trans not started (Incompatible server version.)"); return; @@ -735,8 +725,7 @@ private void copyTransForDocument(String docName) { } else { throw new RuntimeException( "Problem invoking copy trans: [Server response code:" - + failure.getResponse().getResponseStatus() - .getStatusCode() + "]"); + + failure.getResponse().getStatus() + "]"); } } ConsoleUtils.startProgressFeedback(); @@ -750,7 +739,7 @@ private void copyTransForDocument(String docName) { ConsoleUtils.setProgressFeedbackMessage(copyTransStatus .getPercentageComplete() + "%"); copyTransStatus = - this.copyTransResource.getCopyTransStatus(getOpts() + this.copyTransClient.getCopyTransStatus(getOpts() .getProj(), getOpts().getProjectVersion(), docName); } ConsoleUtils.endProgressFeedback(); diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/RawPushCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/RawPushCommand.java index 43f53d67..1086f159 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/RawPushCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/RawPushCommand.java @@ -27,20 +27,15 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; -import java.net.URI; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; -import java.util.List; import java.util.SortedSet; import java.util.TreeSet; -import com.google.common.collect.ImmutableList; import org.apache.commons.codec.binary.Hex; -import org.jboss.resteasy.client.ClientResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zanata.client.commands.PushPullCommand; @@ -51,12 +46,12 @@ import org.zanata.client.util.ConsoleUtils; import org.zanata.rest.DocumentFileUploadForm; import org.zanata.rest.StringSet; -import org.zanata.rest.client.IFileResource; -import org.zanata.rest.client.ISourceDocResource; -import org.zanata.rest.client.ITranslatedDocResource; -import org.zanata.rest.client.ZanataProxyFactory; +import org.zanata.rest.client.FileResourceClient; +import org.zanata.rest.client.RestClientFactory; import org.zanata.rest.dto.ChunkUploadResponse; +import com.google.common.collect.ImmutableList; + /** * Command to send files directly to the server without parsing on the client. * @@ -68,18 +63,16 @@ public class RawPushCommand extends PushPullCommand { private static final Logger log = LoggerFactory .getLogger(PushCommand.class); - protected final IFileResource fileResource; + private FileResourceClient client; public RawPushCommand(PushOptions opts) { super(opts); - this.fileResource = getRequestFactory().getFileResource(); + client = getClientFactory().getFileResourceClient(); } - public RawPushCommand(PushOptions opts, ZanataProxyFactory factory, - ISourceDocResource sourceDocResource, - ITranslatedDocResource translationResources, URI uri) { - super(opts, factory, sourceDocResource, translationResources, uri); - this.fileResource = factory.getFileResource(); + public RawPushCommand(PushOptions opts, RestClientFactory clientFactory) { + super(opts, clientFactory); + client = getClientFactory().getFileResourceClient(); } @Override @@ -107,9 +100,8 @@ public void run() throws IOException { ImmutableList.Builder builder = ImmutableList.builder(); - ClientResponse response = fileResource.acceptedFileTypes(); @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") - StringSet serverAcceptedTypes = new StringSet(response.getEntity()); + StringSet serverAcceptedTypes = client.acceptedFileTypes(); for (String type : getOpts().getFileTypes()) { if (serverAcceptedTypes.contains(type)) { builder.add(type); @@ -303,16 +295,14 @@ private void pushDocumentToServer(String docId, String fileType, DocumentFileUploadForm uploadForm = generateUploadForm(true, true, fileType, md5hash, docFile.length(), fileStream); - ClientResponse response = - uploadDocumentPart(docId, locale, uploadForm); - checkChunkUploadStatus(response); + uploadDocumentPart(docId, locale, uploadForm); } } else { try (StreamChunker chunker = new StreamChunker(docFile, getOpts().getChunkSize())) { log.info(" transmitting file [{}] as {} chunks", docFile.getAbsolutePath(), chunker.totalChunks()); - ClientResponse uploadResponse; + ChunkUploadResponse uploadResponse; DocumentFileUploadForm uploadForm; Long uploadId = null; @@ -332,9 +322,8 @@ private void pushDocumentToServer(String docId, String fileType, } uploadResponse = uploadDocumentPart(docId, locale, uploadForm); - checkChunkUploadStatus(uploadResponse); if (isFirst) { - uploadId = uploadResponse.getEntity().getUploadId(); + uploadId = uploadResponse.getUploadId(); if (uploadId == null) { throw new RuntimeException( "server did not return upload id"); @@ -348,15 +337,6 @@ private void pushDocumentToServer(String docId, String fileType, } } - private void checkChunkUploadStatus( - ClientResponse uploadResponse) { - if (uploadResponse.getStatus() >= 300) { - throw new RuntimeException("Server returned error status: " - + uploadResponse.getStatus() + ". Error message: " - + uploadResponse.getEntity().getErrorMessage()); - } - } - private DocumentFileUploadForm generateUploadForm(boolean isFirst, boolean isLast, String fileType, String md5hash, long streamSize, InputStream fileStream) { @@ -370,21 +350,21 @@ private DocumentFileUploadForm generateUploadForm(boolean isFirst, return uploadForm; } - private ClientResponse uploadDocumentPart( + private ChunkUploadResponse uploadDocumentPart( String docName, String locale, DocumentFileUploadForm uploadForm) { ConsoleUtils.startProgressFeedback(); - ClientResponse response; + ChunkUploadResponse response; if (locale == null) { response = - fileResource.uploadSourceFile(getOpts().getProj(), + client.uploadSourceFile(getOpts().getProj(), getOpts().getProjectVersion(), docName, uploadForm); } else { response = - fileResource.uploadTranslationFile(getOpts().getProj(), + client.uploadTranslationFile(getOpts().getProj(), getOpts().getProjectVersion(), locale, docName, getOpts().getMergeType(), uploadForm); } - log.debug("response from server: {}", response.getEntity()); + log.debug("response from server: {}", response); ConsoleUtils.endProgressFeedback(); return response; } diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/stats/GetStatisticsCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/stats/GetStatisticsCommand.java index 1e47d92b..39f06d82 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/stats/GetStatisticsCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/stats/GetStatisticsCommand.java @@ -20,16 +20,14 @@ */ package org.zanata.client.commands.stats; -import java.util.ArrayList; -import java.util.List; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zanata.client.commands.ConfigurableCommand; +import org.zanata.client.config.LocaleList; import org.zanata.client.config.LocaleMapping; import org.zanata.client.util.ConsoleUtils; +import org.zanata.rest.client.StatisticsResourceClient; import org.zanata.rest.dto.stats.ContainerTranslationStatistics; -import org.zanata.rest.service.StatisticsResource; /** * @author Carlos Munoz { private static final Logger log = LoggerFactory .getLogger(GetStatisticsCommand.class); + private final StatisticsResourceClient client; - private StatisticsResource statsResource; public GetStatisticsCommand(GetStatisticsOptions opts) { super(opts); - statsResource = getRequestFactory().getStatisticsResource(); + client = getClientFactory().getStatisticsClient(); } @Override @@ -53,13 +51,13 @@ public void run() throws Exception { String[] localeListArg = null; if (getOpts().getLocaleMapList() != null) { - List localeList = new ArrayList(); - + localeListArg = new String[getOpts().getLocaleMapList().size()]; // Get the locales from the mappings list - for (LocaleMapping locMapping : getOpts().getLocaleMapList()) { - localeList.add(locMapping.getLocale()); + LocaleList localeMapList = getOpts().getLocaleMapList(); + for (int i = 0; i < localeMapList.size(); i++) { + LocaleMapping locMapping = localeMapList.get(i); + localeListArg[i] = locMapping.getLocale(); } - localeListArg = localeList.toArray(new String[] {}); } ContainerTranslationStatistics containerStats; @@ -88,7 +86,7 @@ public void run() throws Exception { // Document Id not specified if (getOpts().getDocumentId() == null) { containerStats = - statsResource.getStatistics(getOpts().getProj(), getOpts() + client.getStatistics(getOpts().getProj(), getOpts() .getProjectVersion(), getOpts().getIncludeDetails(), getOpts() .getIncludeWordLevelStats(), localeListArg); @@ -96,7 +94,7 @@ public void run() throws Exception { // Otherwise, stats for the single document else { containerStats = - statsResource + client .getStatistics(getOpts().getProj(), getOpts() .getProjectVersion(), getOpts() .getDocumentId(), getOpts() @@ -110,17 +108,18 @@ public void run() throws Exception { // Select the format (output) ContainerStatisticsCommandOutput statsOutput; - // csv - if ("csv".equalsIgnoreCase(getOpts().getFormat())) { - statsOutput = new CsvStatisticsOutput(); - } else { - if (!"console".equalsIgnoreCase(getOpts().getFormat())) { + switch (getOpts().getFormat()) { + case "csv": + statsOutput = new CsvStatisticsOutput(); + break; + case "console": + statsOutput = new ConsoleStatisticsOutput(); + break; + default: log.warn( "Invalid format type '{}', using console format instead.", getOpts().getFormat()); - } - // Default: console - statsOutput = new ConsoleStatisticsOutput(); + statsOutput = new ConsoleStatisticsOutput(); } statsOutput.write(containerStats); diff --git a/zanata-client-commands/src/test/java/org/zanata/client/MockServerRule.java b/zanata-client-commands/src/test/java/org/zanata/client/MockitoServerRule.java similarity index 69% rename from zanata-client-commands/src/test/java/org/zanata/client/MockServerRule.java rename to zanata-client-commands/src/test/java/org/zanata/client/MockitoServerRule.java index 87da461e..dee288e1 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/MockServerRule.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/MockitoServerRule.java @@ -21,17 +21,20 @@ package org.zanata.client; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anySetOf; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import java.io.InputStream; -import java.lang.String; import java.net.URI; import java.util.Collections; import java.util.List; import java.util.Set; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.Response; - -import org.jboss.resteasy.client.ClientResponse; import org.junit.rules.ExternalResource; import org.mockito.ArgumentCaptor; import org.mockito.Captor; @@ -48,12 +51,13 @@ import org.zanata.common.LocaleId; import org.zanata.common.ProjectType; import org.zanata.rest.DocumentFileUploadForm; -import org.zanata.rest.client.IAsynchronousProcessResource; -import org.zanata.rest.client.ICopyTransResource; -import org.zanata.rest.client.IFileResource; -import org.zanata.rest.client.ISourceDocResource; -import org.zanata.rest.client.ITranslatedDocResource; -import org.zanata.rest.client.ZanataProxyFactory; +import org.zanata.rest.StringSet; +import org.zanata.rest.client.AsyncProcessClient; +import org.zanata.rest.client.CopyTransClient; +import org.zanata.rest.client.FileResourceClient; +import org.zanata.rest.client.RestClientFactory; +import org.zanata.rest.client.SourceDocResourceClient; +import org.zanata.rest.client.TransDocResourceClient; import org.zanata.rest.dto.ChunkUploadResponse; import org.zanata.rest.dto.ProcessStatus; import org.zanata.rest.dto.resource.Resource; @@ -63,44 +67,24 @@ import com.google.common.base.Joiner; import com.google.common.base.Throwables; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anySetOf; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.core.util.MultivaluedMapImpl; /** * Test rule to set up push and/or pull command(s) which will interact with a - * mock REST proxy factory and mocked REST resources. + * mockito mocked REST clients. * * @author Patrick Huang pahuang@redhat.com */ -public class MockServerRule extends ExternalResource { - private URI uri; +public class MockitoServerRule extends ExternalResource { // async process statuses private String mockProcessId = "MockServerRuleProcess"; private ProcessStatus finished = new ProcessStatus(); private ProcessStatus running = new ProcessStatus(); private PullOptionsImpl pullOpts; - @Mock - private IAsynchronousProcessResource asyncResource; - @Mock - private ICopyTransResource copyTransResource; - @Mock - private IFileResource fileResource; - @Mock - private ZanataProxyFactory factory; - @Mock - private ISourceDocResource sourceDocResource; - @Mock - private ITranslatedDocResource transDocResource; + private PushOptionsImpl pushOpts; - @Mock - private ClientResponse> remoteDocListResponse; @Captor private ArgumentCaptor resourceCaptor; @Captor @@ -112,25 +96,28 @@ public class MockServerRule extends ExternalResource { @Captor private ArgumentCaptor transResourceCaptor; @Mock - private ClientResponse resourceResponse; - @Mock - private ClientResponse transResourceResponse; - @Mock - private ClientResponse acceptedFilesResponse; - @Mock - private ClientResponse chunkUploadResponse; + private ClientResponse transResourceResponse; @Captor private ArgumentCaptor uploadFormCaptor; @Mock private ClientResponse downloadSourceResponse; @Mock private ClientResponse downloadTransResponse; + @Mock + private RestClientFactory clientFactory; + @Mock + private CopyTransClient copyTransClient; + @Mock + private AsyncProcessClient asyncClient; + @Mock + private SourceDocResourceClient sourceDocClient; + @Mock + private TransDocResourceClient transDocClient; + @Mock + private FileResourceClient fileResourceClient; - public MockServerRule() { + public MockitoServerRule() { MockitoAnnotations.initMocks(this); - when(factory.getCopyTransResource()).thenReturn(copyTransResource); - when(factory.getAsynchronousProcessResource()).thenReturn(asyncResource); - when(factory.getFileResource()).thenReturn(fileResource); // async process statuses running.setUrl(mockProcessId); running.setStatusCode(ProcessStatus.ProcessStatusCode.Running); @@ -176,34 +163,35 @@ private static URI setUrl(ConfigurableProjectOptions opts) { * successful. You should verify push afterwards and make assertion on * all/some of the captor captured values. * - * @see MockServerRule#verifyPushSource() - * @see MockServerRule#verifyPushTranslation() + * @see MockitoServerRule#verifyPushSource() + * @see MockitoServerRule#verifyPushTranslation() * @return push command */ public PushCommand createPushCommand() { - when(sourceDocResource.get(null)).thenReturn(remoteDocListResponse); - // this assumes no obsolete documents on server - when(remoteDocListResponse.getStatus()).thenReturn(200); - when(remoteDocListResponse.getEntity()).thenReturn( - Collections. emptyList()); + when(clientFactory.getSourceDocResourceClient(pushOpts.getProj(), + pullOpts.getProjectVersion())).thenReturn(sourceDocClient); + when(sourceDocClient.getResourceMeta(null)).thenReturn( + Collections.emptyList()); // this assumes async push is always success when( - asyncResource.startSourceDocCreationOrUpdate( + asyncClient.startSourceDocCreationOrUpdate( anyString(), eq(pushOpts.getProj()), eq(pushOpts.getProjectVersion()), any(Resource.class), anySetOf(String.class), eq(false))) .thenReturn(running); when( - asyncResource.startTranslatedDocCreationOrUpdate( + asyncClient.startTranslatedDocCreationOrUpdate( docIdCaptor.capture(), eq(pushOpts.getProj()), eq(pushOpts.getProjectVersion()), localeIdCaptor.capture(), transResourceCaptor.capture(), extensionCaptor.capture(), eq(pushOpts.getMergeType()))) .thenReturn(running); - when(asyncResource.getProcessStatus(mockProcessId)) + when(asyncClient.getProcessStatus(mockProcessId)) .thenReturn(finished); - return new PushCommand(pushOpts, factory, sourceDocResource, transDocResource, uri); + return new PushCommand(pushOpts, + copyTransClient, + asyncClient, clientFactory); } public PushOptionsImpl getPushOpts() { @@ -231,14 +219,14 @@ public ArgumentCaptor getTransResourceCaptor() { } public void verifyPushSource() { - verify(asyncResource).startSourceDocCreationOrUpdate( + verify(asyncClient).startSourceDocCreationOrUpdate( docIdCaptor.capture(), eq(pushOpts.getProj()), eq(pushOpts.getProjectVersion()), resourceCaptor.capture(), extensionCaptor.capture(), eq(false)); } public void verifyPushTranslation() { - verify(asyncResource).startTranslatedDocCreationOrUpdate( + verify(asyncClient).startTranslatedDocCreationOrUpdate( docIdCaptor.capture(), eq(pushOpts.getProj()), eq(pushOpts.getProjectVersion()), localeIdCaptor.capture(), transResourceCaptor.capture(), extensionCaptor.capture(), @@ -264,71 +252,71 @@ public PullOptionsImpl getPullOpts() { public PullCommand createPullCommand(List remoteDocList, Resource resourceOnServer, TranslationsResource transResourceOnServer) { + when(clientFactory.getSourceDocResourceClient(anyString(), anyString())) + .thenReturn(sourceDocClient); // return provided remote doc meta list - when(sourceDocResource.get(null)).thenReturn(remoteDocListResponse); - when(remoteDocListResponse.getEntity()).thenReturn(remoteDocList); + when(sourceDocClient.getResourceMeta(null)).thenReturn(remoteDocList); // return provided server resource - when(sourceDocResource.getResource(anyString(), anySetOf(String.class))) - .thenReturn(resourceResponse); - when(resourceResponse.getStatus()).thenReturn(200); - when(resourceResponse.getEntity()).thenReturn(resourceOnServer); + when(sourceDocClient.getResource(anyString(), anySetOf(String.class))) + .thenReturn(resourceOnServer); + when( + clientFactory.getTransDocResourceClient(pullOpts.getProj(), + pullOpts.getProjectVersion())).thenReturn( + transDocClient); // return provided server translation when( - transDocResource.getTranslations(anyString(), + transDocClient.getTranslations(anyString(), any(LocaleId.class), anySetOf(String.class), eq(getPullOpts().getCreateSkeletons()), anyString())) .thenReturn(transResourceResponse); when(transResourceResponse.getStatus()).thenReturn(200); - when(transResourceResponse.getResponseHeaders()).thenReturn( - new MultivaluedHashMap()); - when(transResourceResponse.getEntity()).thenReturn( - transResourceOnServer); - return new PullCommand(pullOpts, factory, sourceDocResource, - transDocResource, uri); + when(transResourceResponse.getHeaders()).thenReturn( + new MultivaluedMapImpl()); + when(transResourceResponse.getEntity(TranslationsResource.class)) + .thenReturn(transResourceOnServer); + return new PullCommand(pullOpts, clientFactory); } /** * Creates a raw file push command that will interact with mock REST proxy factory. * File service resource is stubbed to always return successful result. * - * @see MockServerRule#verifyPushRawFileSource(int) - * @see MockServerRule#verifyPushRawFileTranslation(int) + * @see MockitoServerRule#verifyPushRawFileSource(int) + * @see MockitoServerRule#verifyPushRawFileTranslation(int) * @return raw push command */ public RawPushCommand createRawPushCommand() { - when(fileResource.acceptedFileTypes()) - .thenReturn(acceptedFilesResponse); + when(clientFactory.getFileResourceClient()).thenReturn( + fileResourceClient); List fileTypes = ProjectType.getSupportedSourceFileTypes(ProjectType.File); - when(acceptedFilesResponse.getEntity()).thenReturn( - Joiner.on(";").join(fileTypes)); + when(fileResourceClient.acceptedFileTypes()) + .thenReturn(new StringSet(Joiner.on(";").join(fileTypes))); + ChunkUploadResponse uploadResponse = + new ChunkUploadResponse(1L, 1, false, "Upload successful"); // push source - when(fileResource.uploadSourceFile(eq(pushOpts.getProj()), + when(fileResourceClient.uploadSourceFile(eq(pushOpts.getProj()), eq(pushOpts.getProjectVersion()), anyString(), any( - DocumentFileUploadForm.class))).thenReturn(chunkUploadResponse); + DocumentFileUploadForm.class))).thenReturn(uploadResponse); // push translation when( - fileResource.uploadTranslationFile(eq(pushOpts.getProj()), + fileResourceClient.uploadTranslationFile(eq(pushOpts.getProj()), eq(pushOpts.getProjectVersion()), anyString(), anyString(), anyString(), any(DocumentFileUploadForm.class))).thenReturn( - chunkUploadResponse); - when(chunkUploadResponse.getStatus()).thenReturn(201); - when(chunkUploadResponse.getEntity()).thenReturn( - new ChunkUploadResponse(1L, 1, false, "Upload successful")); - return new RawPushCommand(pushOpts, factory, sourceDocResource, - transDocResource, uri); + uploadResponse); + return new RawPushCommand(pushOpts, clientFactory); } public void verifyPushRawFileSource(int numOfSource) { - verify(fileResource, times(numOfSource)).uploadSourceFile( + verify(fileResourceClient, times(numOfSource)).uploadSourceFile( eq(pushOpts.getProj()), eq(pushOpts.getProjectVersion()), docIdCaptor.capture(), uploadFormCaptor.capture()); } public void verifyPushRawFileTranslation(int numOfTrans) { - verify(fileResource, times(numOfTrans)).uploadTranslationFile( + verify(fileResourceClient, times(numOfTrans)).uploadTranslationFile( eq(pushOpts.getProj()), eq(pushOpts.getProjectVersion()), anyString(), docIdCaptor.capture(), @@ -350,29 +338,32 @@ public void verifyPushRawFileTranslation(int numOfTrans) { public RawPullCommand createRawPullCommand( List remoteDocList, InputStream sourceFileStream, InputStream transFileStream) { + when( + clientFactory.getSourceDocResourceClient(pullOpts.getProj(), + pullOpts.getProjectVersion())).thenReturn( + sourceDocClient); + when(clientFactory.getFileResourceClient()).thenReturn(fileResourceClient); // return provided remote doc meta list - when(sourceDocResource.get(null)).thenReturn(remoteDocListResponse); - when(remoteDocListResponse.getEntity()).thenReturn(remoteDocList); + when(sourceDocClient.getResourceMeta(null)).thenReturn(remoteDocList); // return provided source stream - when(fileResource.downloadSourceFile( + when(fileResourceClient.downloadSourceFile( eq(pullOpts.getProj()), eq(pullOpts.getProjectVersion()), eq(FileResource.FILETYPE_RAW_SOURCE_DOCUMENT), anyString())).thenReturn(downloadSourceResponse); - when(downloadSourceResponse.getResponseStatus()).thenReturn( - Response.Status.OK); + when(downloadSourceResponse.getClientResponseStatus()).thenReturn( + ClientResponse.Status.OK); when(downloadSourceResponse.getStatus()).thenReturn(200); when(downloadSourceResponse.getEntity(InputStream.class)) .thenReturn(sourceFileStream); // return provide translation stream - when(fileResource.downloadTranslationFile(eq(pullOpts.getProj()), + when(fileResourceClient.downloadTranslationFile(eq(pullOpts.getProj()), eq(pullOpts.getProjectVersion()), anyString(), anyString(), anyString())).thenReturn(downloadTransResponse); when(downloadTransResponse.getStatus()).thenReturn(200); - when(downloadTransResponse.getResponseStatus()).thenReturn( - Response.Status.OK); + when(downloadTransResponse.getClientResponseStatus()).thenReturn( + ClientResponse.Status.OK); when(downloadTransResponse.getEntity(InputStream.class)) .thenReturn(transFileStream); - return new RawPullCommand(pullOpts, factory, sourceDocResource, - transDocResource, uri, fileResource); + return new RawPullCommand(pullOpts, fileResourceClient, clientFactory); } } diff --git a/zanata-client-commands/src/test/java/org/zanata/client/TestProjectGenerator.java b/zanata-client-commands/src/test/java/org/zanata/client/TestProjectGenerator.java index 193b6c5e..f9039f0b 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/TestProjectGenerator.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/TestProjectGenerator.java @@ -13,12 +13,12 @@ import org.zanata.client.commands.ConfigurableProjectOptions; import org.zanata.client.commands.OptionsUtil; import org.zanata.common.ProjectType; -import org.zanata.rest.client.ClientUtility; -import org.zanata.rest.client.IProjectIterationResource; -import org.zanata.rest.client.IProjectResource; -import org.zanata.rest.client.ZanataProxyFactory; +import org.zanata.rest.client.ProjectClient; +import org.zanata.rest.client.ProjectIterationClient; +import org.zanata.rest.client.RestClientFactory; import org.zanata.rest.dto.Project; import org.zanata.rest.dto.ProjectIteration; + import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableMap; @@ -94,8 +94,8 @@ public void ensureProjectOnServer(ConfigurableProjectOptions opts, opts.setUrl(new URI(instance.getUrl()).toURL()); opts.setUsername(instance.getUsername()); opts.setKey(instance.getKey()); - ZanataProxyFactory requestFactory = - OptionsUtil.createRequestFactory(opts); + + RestClientFactory clientFactory = OptionsUtil.createClientFactory(opts); Project projectDTO = createProjectDTO(projectRootMap.get(projectType)); String projectSlug = projectDTO.getId(); @@ -103,14 +103,9 @@ public void ensureProjectOnServer(ConfigurableProjectOptions opts, String iterationSlug = iteration.getId(); // create project and version - IProjectResource projectResource = - requestFactory.getProject(projectSlug); - ClientUtility.checkResultAndReleaseConnection( - projectResource.put(projectDTO)); - IProjectIterationResource iterationResource = - requestFactory.getProjectIteration(projectSlug, iterationSlug); - ClientUtility.checkResultAndReleaseConnection( - iterationResource.put(iteration)); + clientFactory.getProjectClient(projectSlug).put(projectDTO); + clientFactory.getProjectIterationClient(projectSlug, iterationSlug) + .put(iteration); } /** diff --git a/zanata-client-commands/src/test/java/org/zanata/client/TestUtils.java b/zanata-client-commands/src/test/java/org/zanata/client/TestUtils.java index 79cd870a..ee05172f 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/TestUtils.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/TestUtils.java @@ -21,9 +21,16 @@ package org.zanata.client; +import java.io.File; +import java.io.IOException; +import java.net.URL; + +import org.apache.commons.codec.Charsets; +import org.apache.commons.io.IOUtils; import org.zanata.client.commands.ConfigurableProjectOptions; import org.zanata.client.config.LocaleMapping; import com.google.common.base.Optional; +import com.google.common.base.Preconditions; /** * @author Patrick Huang @@ -43,4 +50,24 @@ public static LocaleMapping createAndAddLocaleMapping(String localeId, opts.getLocaleMapList().add(mapping); return mapping; } + + public static String readFromClasspath(String relativePath) + throws IOException { + URL resource = loadFromClasspath(relativePath); + return IOUtils.toString(resource, Charsets.UTF_8); + } + + public static File fileFromClasspath(String relativePath) { + URL url = loadFromClasspath(relativePath); + return new File(url.getFile()); + } + + private static URL loadFromClasspath(String relativePath) { + URL resource = + Thread.currentThread().getContextClassLoader() + .getResource(relativePath); + Preconditions.checkArgument(resource != null, "%s not found", + relativePath); + return resource; + } } diff --git a/zanata-client-commands/src/test/java/org/zanata/client/commands/DummyResponse.java b/zanata-client-commands/src/test/java/org/zanata/client/commands/DummyResponse.java deleted file mode 100644 index 38695e24..00000000 --- a/zanata-client-commands/src/test/java/org/zanata/client/commands/DummyResponse.java +++ /dev/null @@ -1,233 +0,0 @@ -package org.zanata.client.commands; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; -import java.net.URI; -import java.util.Date; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import javax.ws.rs.core.EntityTag; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.NewCookie; - -import org.jboss.resteasy.client.ClientResponse; -import org.jboss.resteasy.spi.Link; -import org.jboss.resteasy.spi.LinkHeader; -import org.jboss.resteasy.util.GenericType; - -/** - * @author Sean Flanigan sflaniga@redhat.com - * - * @param - */ -public class DummyResponse extends ClientResponse { - private final Status status; - private final T entity; - - public DummyResponse(Status status, T entity) { - super(); - this.status = status; - this.entity = entity; - } - - @Override - public T getEntity() { - return entity; - } - - @Override - public T2 getEntity(Class arg0) { - return null; - } - - @Override - public T2 getEntity(GenericType arg0) { - return null; - } - - @Override - public T2 getEntity(Class arg0, Type arg1) { - return null; - } - - @Override - public T2 getEntity(GenericType arg0, Annotation[] arg1) { - return null; - } - - @Override - public T2 getEntity(Class arg0, Type arg1, Annotation[] arg2) { - return null; - } - - @Override - public Link getHeaderAsLink(String arg0) { - return null; - } - - @Override - public MultivaluedMap getHeaders() { - return null; - } - - @Override - public MultivaluedMap getResponseHeaders() { - return null; - } - - @Override - public Link getLocationLink() { - return null; - } - - @Override - public StatusType getStatusInfo() { - return null; - } - - @Override - public T readEntity(Class entityType) { - return null; - } - - @Override - public T readEntity(javax.ws.rs.core.GenericType entityType) { - return null; - } - - @Override - public T readEntity(Class entityType, Annotation[] annotations) { - return null; - } - - @Override - public T readEntity(javax.ws.rs.core.GenericType entityType, - Annotation[] annotations) { - return null; - } - - @Override - public boolean hasEntity() { - return false; - } - - @Override - public boolean bufferEntity() { - return false; - } - - @Override - public void close() { - } - - @Override - public MediaType getMediaType() { - return null; - } - - @Override - public Locale getLanguage() { - return null; - } - - @Override - public int getLength() { - return 0; - } - - @Override - public Set getAllowedMethods() { - return null; - } - - @Override - public Map getCookies() { - return null; - } - - @Override - public EntityTag getEntityTag() { - return null; - } - - @Override - public Date getDate() { - return null; - } - - @Override - public Date getLastModified() { - return null; - } - - @Override - public Set getLinks() { - return null; - } - - @Override - public boolean hasLink(String relation) { - return false; - } - - @Override - public javax.ws.rs.core.Link getLink(String relation) { - return null; - } - - @Override - public javax.ws.rs.core.Link.Builder getLinkBuilder(String relation) { - return null; - } - - @Override - public MultivaluedMap getStringHeaders() { - return null; - } - - @Override - public String getHeaderString(String name) { - return null; - } - - @Override - public LinkHeader getLinkHeader() { - return null; - } - - @Override - public URI getLocation() { - return null; - } - - @Override - public Status getResponseStatus() { - return status; - } - - @Override - public void releaseConnection() { - } - - @Override - public int getStatus() { - return status.getStatusCode(); - } - - @Override - public MultivaluedMap getMetadata() { - return null; - } - - @Override - public Map getAttributes() { - return null; - } - - @Override - public void resetStream() { - } -} diff --git a/zanata-client-commands/src/test/java/org/zanata/client/commands/HTTPMockContainer.java b/zanata-client-commands/src/test/java/org/zanata/client/commands/HTTPMockContainer.java index 61eb2d7d..aede63e0 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/commands/HTTPMockContainer.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/commands/HTTPMockContainer.java @@ -106,15 +106,6 @@ public HTTPMockContainer build() { return new HTTPMockContainer(mapBuilder.build()); } - public static String readFromClasspath(String relativePath) - throws IOException { - URL resource = - Thread.currentThread().getContextClassLoader() - .getResource(relativePath); - Preconditions.checkArgument(resource != null, "%s not found", - relativePath); - return IOUtils.toString(resource, Charsets.UTF_8); - } } private static class StatusAndContent { diff --git a/zanata-client-commands/src/test/java/org/zanata/client/commands/init/InitCommandTest.java b/zanata-client-commands/src/test/java/org/zanata/client/commands/init/InitCommandTest.java index 61f82335..1da8eecf 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/commands/init/InitCommandTest.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/commands/init/InitCommandTest.java @@ -2,17 +2,14 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.when; -import static org.zanata.client.commands.HTTPMockContainer.Builder.readFromClasspath; +import static org.zanata.client.TestUtils.readFromClasspath; import java.io.File; import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.URI; import java.util.List; import org.apache.commons.io.FileUtils; import org.hamcrest.Matchers; -import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -20,15 +17,12 @@ import org.junit.rules.TemporaryFolder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.simpleframework.http.core.Container; -import org.simpleframework.http.core.ContainerServer; -import org.simpleframework.transport.connect.SocketConnection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zanata.client.commands.ConsoleInteractor; -import org.zanata.client.commands.HTTPMockContainer; import org.zanata.client.commands.Messages; -import org.zanata.rest.client.ZanataProxyFactory; +import org.zanata.rest.client.ProjectIterationClient; +import org.zanata.rest.client.RestClientFactory; import org.zanata.rest.dto.VersionInfo; import com.google.common.base.Charsets; @@ -46,53 +40,25 @@ public class InitCommandTest { private InitCommand command; private InitOptionsImpl opts; - private SocketConnection connection; @Mock private ConsoleInteractor console; @Mock - private ZanataProxyFactory requestFactory; + private RestClientFactory clientFactory; + @Mock + private ProjectIterationClient projectIterationClient; @Before public void setUp() throws IOException { MockitoAnnotations.initMocks(this); opts = new InitOptionsImpl(); - command = new InitCommand(opts, console, null); - } - - @After - public void cleanUp() throws IOException { - if (connection != null) { - connection.close(); - } - } - - private void startMockServer(Container container) throws IOException { - ContainerServer server = new ContainerServer(container); - connection = new SocketConnection(server); - InetSocketAddress address = (InetSocketAddress) connection - .connect(new InetSocketAddress(0)); - int port = address.getPort(); - - opts.setUrl(URI.create("http://localhost:" + port).toURL()); - opts.setUsername("admin"); - opts.setKey("abcde"); - opts.setLogHttp(false); + command = new InitCommand(opts, console, clientFactory); } @Test public void willDownloadProjectConfigFromServer() throws IOException { - String configContent = - readFromClasspath("serverresponse/projectConfig.xml"); - HTTPMockContainer container = - HTTPMockContainer.Builder - .builder() - .onPathReturnOk( - Matchers.endsWith("/version"), - readFromClasspath("serverresponse/version.xml")) - .onPathReturnOk( - Matchers.endsWith("/config"), - configContent).build(); - startMockServer(container); + when(clientFactory.getProjectIterationClient("gcc", "master")).thenReturn(projectIterationClient); + when(projectIterationClient.sampleConfiguration()).thenReturn( + readFromClasspath("serverresponse/projectConfig.xml")); File configFileDest = new File(tempFolder.getRoot(), "zanata.xml"); command.downloadZanataXml("gcc", "master", configFileDest); @@ -100,7 +66,7 @@ public void willDownloadProjectConfigFromServer() throws IOException { assertThat(configFileDest.exists(), Matchers.is(true)); List lines = FileUtils.readLines(configFileDest, Charsets.UTF_8); String content = Joiner.on("\n").join(lines); - assertThat(content, Matchers.equalTo(configContent)); + assertThat(content, Matchers.containsString("")); assertThat(opts.getProjectConfig(), Matchers.equalTo(configFileDest)); } @@ -130,9 +96,9 @@ public void willQuitIfServerApiVersionDoesNotSupportInit() expectException.expectMessage(Matchers.equalTo(Messages ._("server.incompatible"))); - when(requestFactory.getServerVersionInfo()).thenReturn( + when(clientFactory.getServerVersionInfo()).thenReturn( new VersionInfo("3.3.1", "unknown", "unknown")); - command = new InitCommand(opts, console, requestFactory); + command = new InitCommand(opts, console, clientFactory); command.ensureServerVersion(); } diff --git a/zanata-client-commands/src/test/java/org/zanata/client/commands/init/ProjectIterationPromptTest.java b/zanata-client-commands/src/test/java/org/zanata/client/commands/init/ProjectIterationPromptTest.java index cda88046..1ad5d581 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/commands/init/ProjectIterationPromptTest.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/commands/init/ProjectIterationPromptTest.java @@ -1,9 +1,12 @@ package org.zanata.client.commands.init; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import java.io.IOException; import org.hamcrest.Matchers; -import org.jboss.resteasy.client.ClientResponse; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; @@ -13,39 +16,32 @@ import org.zanata.client.commands.ConsoleInteractor; import org.zanata.client.commands.MockConsoleInteractor; import org.zanata.common.EntityStatus; -import org.zanata.rest.client.IProjectIterationResource; -import org.zanata.rest.client.IProjectResource; -import org.zanata.rest.client.ZanataProxyFactory; +import org.zanata.rest.client.ProjectClient; +import org.zanata.rest.client.ProjectIterationClient; +import org.zanata.rest.client.RestClientFactory; import org.zanata.rest.dto.Project; import org.zanata.rest.dto.ProjectIteration; import com.google.common.collect.Lists; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - public class ProjectIterationPromptTest { private ProjectIterationPrompt prompt; private InitOptionsImpl opts; - @Mock - private ZanataProxyFactory requestFactory; - @Mock - private IProjectIterationResource iterationResource; - @Mock - private ClientResponse response; + @Captor private ArgumentCaptor iterationCaptor; @Mock - private IProjectResource projectResource; + private RestClientFactory clientFactory; + @Mock + private ProjectIterationClient projectIterationClient; + @Mock + private ProjectClient projectClient; @Before public void setUp() { MockitoAnnotations.initMocks(this); opts = new InitOptionsImpl(); prompt = null; - } @Test @@ -62,19 +58,19 @@ public void willGuideUserToSelectVersion() { opts.setProj(projectId); opts.setProjectType(projectType); - when(requestFactory.getProject(projectId)) - .thenReturn(projectResource); - when(projectResource.get()).thenReturn(response); - when(response.getEntity(Project.class)).thenReturn(project); - + when(clientFactory.getProjectClient(opts.getProj())) + .thenReturn(projectClient); + when(projectClient.get()).thenReturn(project); + when(clientFactory.getProjectIterationClient(opts.getProj(), "4.8.2")) + .thenReturn(projectIterationClient); // we want to select the second active version ConsoleInteractor console = MockConsoleInteractor.predefineAnswers("2"); - prompt = new ProjectIterationPrompt(console, opts, requestFactory); + prompt = new ProjectIterationPrompt(console, opts, clientFactory); prompt.selectVersion(); - verify(projectResource).get(); + verify(projectClient).get(); assertThat(opts.getProjectVersion(), Matchers.equalTo("4.8.2")); } @@ -94,17 +90,13 @@ public void willGuideUserToCreateNewVersion() opts.setProjectType(projectType); ConsoleInteractor console = MockConsoleInteractor.predefineAnswers(versionId); - prompt = new ProjectIterationPrompt(console, opts, requestFactory); - - when(requestFactory.getProjectIteration(projectId, versionId)) - .thenReturn(iterationResource); - when(iterationResource.put(iterationCaptor.capture())).thenReturn( - response); - when(response.getStatus()).thenReturn(201); + prompt = new ProjectIterationPrompt(console, opts, clientFactory); + when(clientFactory.getProjectIterationClient(opts.getProj(), versionId)) + .thenReturn(projectIterationClient); prompt.createNewVersion(); - verify(iterationResource).put(iterationCaptor.capture()); + verify(projectIterationClient).put(iterationCaptor.capture()); ProjectIteration iteration = iterationCaptor.getValue(); assertThat(iteration.getId(), Matchers.equalTo(versionId)); assertThat(iteration.getProjectType(), Matchers.equalTo(projectType)); diff --git a/zanata-client-commands/src/test/java/org/zanata/client/commands/init/ProjectPromptTest.java b/zanata-client-commands/src/test/java/org/zanata/client/commands/init/ProjectPromptTest.java index 7abc5358..4c4c4bda 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/commands/init/ProjectPromptTest.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/commands/init/ProjectPromptTest.java @@ -1,106 +1,74 @@ package org.zanata.client.commands.init; import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static org.zanata.client.commands.HTTPMockContainer.Builder.readFromClasspath; import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.URI; import java.util.List; import org.hamcrest.Matchers; -import org.jboss.resteasy.client.ClientResponse; -import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.mockito.Answers; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.simpleframework.http.core.Container; -import org.simpleframework.http.core.ContainerServer; -import org.simpleframework.transport.connect.Connection; -import org.simpleframework.transport.connect.SocketConnection; import org.zanata.client.commands.ConsoleInteractor; -import org.zanata.client.commands.HTTPMockContainer; import org.zanata.client.commands.MockConsoleInteractor; -import org.zanata.client.commands.OptionsUtil; -import org.zanata.rest.client.IProjectResource; -import org.zanata.rest.client.IProjectsResource; -import org.zanata.rest.client.ZanataProxyFactory; +import org.zanata.common.EntityStatus; +import org.zanata.rest.client.ProjectClient; +import org.zanata.rest.client.ProjectsClient; +import org.zanata.rest.client.RestClientFactory; import org.zanata.rest.dto.Project; +import org.zanata.rest.dto.ProjectIteration; + import com.google.common.collect.Lists; public class ProjectPromptTest { private ProjectPrompt prompt; - private Connection connection; private InitOptions opts; - private ZanataProxyFactory proxyFactory; @Mock private ProjectIterationPrompt iterationPrompt; - @Mock - private ClientResponse response; - @Mock - private IProjectResource projectResource; + @Captor private ArgumentCaptor projectCaptor; + @Mock + private RestClientFactory clientFactory; + @Mock + private ProjectsClient projectsClient; + @Mock + private ProjectClient projectClient; @Before public void setUp() { MockitoAnnotations.initMocks(this); opts = new InitOptionsImpl(); + when(clientFactory.getProjectsClient()).thenReturn(projectsClient); } - @After - public void cleanUp() throws IOException { - if (connection != null) { - connection.close(); - } - } - - private void startMockServer(Container container) throws IOException { - ContainerServer server = new ContainerServer(container); - connection = new SocketConnection(server); - InetSocketAddress address = (InetSocketAddress) connection - .connect(new InetSocketAddress(0)); - int port = address.getPort(); - - opts.setUrl(URI.create("http://localhost:" + port).toURL()); - opts.setUsername("admin"); - opts.setKey("abcde"); - opts.setLogHttp(false); - proxyFactory = OptionsUtil.createRequestFactory(opts); - } - - // this test sets up a localhost mock server and simulate full REST round - // trip. @Test public void willShowAllActiveProjectsIfUserChooseToSelect() throws IOException { - HTTPMockContainer container = - HTTPMockContainer.Builder - .builder() - .onPathReturnOk( - Matchers.endsWith("/version"), - readFromClasspath("serverresponse/version.xml")) - .onPathReturnOk( - Matchers.endsWith("/projects"), - readFromClasspath("serverresponse/projects.xml")) - .onPathReturnOk( - Matchers.endsWith("/projects/p/gcc"), - readFromClasspath("serverresponse/iteration.xml")) - .build(); - startMockServer(container); + Project project = new Project("gcc", "gnu C compiler", "gettext"); + ProjectIteration iteration = new ProjectIteration("master"); + iteration.setStatus(EntityStatus.ACTIVE); + project.getIterations(true).add(iteration); + when(projectsClient.getProjects()).thenReturn( + new Project[] { project }); + when(clientFactory.getProjectClient("gcc")).thenReturn(projectClient); + when(projectClient.get()).thenReturn(project); + ConsoleInteractor console = MockConsoleInteractor.predefineAnswers("1", "1", "1", "1"); prompt = - new ProjectPrompt(console, opts, proxyFactory, - new ProjectIterationPrompt(console, opts, proxyFactory)); + new ProjectPrompt(console, opts, + new ProjectIterationPrompt(console, opts, + clientFactory), + clientFactory); prompt.selectOrCreateNewProjectAndVersion(); @@ -111,12 +79,7 @@ public void willShowAllActiveProjectsIfUserChooseToSelect() @Test public void willFilterAllProjectsIfUserTypeLetters() { - proxyFactory = mock(ZanataProxyFactory.class); - - IProjectsResource projectsResource = mock(IProjectsResource.class, - Answers.RETURNS_DEEP_STUBS.get()); - when(proxyFactory.getProjectsResource()).thenReturn(projectsResource); - when(projectsResource.get().getEntity(Project[].class)) + when(projectsClient.getProjects()) .thenReturn(new Project[] { makeProject("project-1", "project one"), makeProject("project-2", "project two"), @@ -128,8 +91,8 @@ public void willFilterAllProjectsIfUserTypeLetters() { "99", // part of project name "1"); prompt = - new ProjectPrompt(console, opts, proxyFactory, - mock(ProjectIterationPrompt.class)); + new ProjectPrompt(console, opts, + mock(ProjectIterationPrompt.class), clientFactory); prompt.selectProject(); assertThat(opts.getProj(), Matchers.equalTo("project-99")); @@ -148,8 +111,7 @@ private static Project makeProject(String slug, String name) { public void canFilterProject() { prompt = new ProjectPrompt(mock(ConsoleInteractor.class), opts, - mock(ZanataProxyFactory.class), - mock(ProjectIterationPrompt.class)); + mock(ProjectIterationPrompt.class), clientFactory); Project gcc = makeProject("gcc", "gnu c compiler"); Project aboutFedora = makeProject("about-fedora", "about fedora"); @@ -178,19 +140,15 @@ public void willGuideUserIfUserChooseToCreateNewProjectAndVersion() MockConsoleInteractor.predefineAnswers(projectId, "C compiler", projectType, versionId); - proxyFactory = mock(ZanataProxyFactory.class); - - when(proxyFactory.getProject(projectId)).thenReturn(projectResource); - when(projectResource.put(projectCaptor.capture())).thenReturn(response); - when(response.getStatus()).thenReturn(201); + when(clientFactory.getProjectClient("gcc")).thenReturn(projectClient); + doNothing().when(projectClient).put(projectCaptor.capture()); prompt = - new ProjectPrompt(console, opts, proxyFactory, - iterationPrompt); + new ProjectPrompt(console, opts, + iterationPrompt, clientFactory); prompt.createNewProject(); - verify(proxyFactory).getProject(projectId); - verify(projectResource).put(projectCaptor.capture()); + verify(projectClient).put(projectCaptor.capture()); verify(iterationPrompt).createNewVersion(); Project project = projectCaptor.getValue(); assertThat(project.getId(), Matchers.equalTo(projectId)); diff --git a/zanata-client-commands/src/test/java/org/zanata/client/commands/push/PushCommandTest.java b/zanata-client-commands/src/test/java/org/zanata/client/commands/push/PushCommandTest.java index 74645101..d80257bf 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/commands/push/PushCommandTest.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/commands/push/PushCommandTest.java @@ -1,34 +1,31 @@ package org.zanata.client.commands.push; import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; -import static org.mockito.Matchers.notNull; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; +import static org.zanata.client.TestUtils.fileFromClasspath; import java.io.File; -import java.net.URI; import java.util.ArrayList; import java.util.List; -import javax.ws.rs.core.Response.Status; - -import org.jboss.resteasy.client.ClientResponse; +import org.junit.Before; import org.junit.Test; import org.mockito.Mock; -import org.zanata.client.commands.DummyResponse; +import org.zanata.client.TestUtils; import org.zanata.client.commands.OptionsUtil; import org.zanata.client.commands.ZanataCommand; import org.zanata.client.config.LocaleList; import org.zanata.client.config.LocaleMapping; import org.zanata.common.LocaleId; import org.zanata.rest.StringSet; -import org.zanata.rest.client.IAsynchronousProcessResource; -import org.zanata.rest.client.ICopyTransResource; -import org.zanata.rest.client.ISourceDocResource; -import org.zanata.rest.client.ITranslatedDocResource; -import org.zanata.rest.client.ZanataProxyFactory; +import org.zanata.rest.client.AsyncProcessClient; +import org.zanata.rest.client.CopyTransClient; +import org.zanata.rest.client.RestClientFactory; +import org.zanata.rest.client.SourceDocResourceClient; import org.zanata.rest.dto.CopyTransStatus; import org.zanata.rest.dto.ProcessStatus; import org.zanata.rest.dto.resource.Resource; @@ -38,18 +35,22 @@ public class PushCommandTest { @Mock - ZanataProxyFactory mockRequestFactory; - @Mock - ISourceDocResource mockSourceDocResource; + private RestClientFactory clientFactory; @Mock - ITranslatedDocResource mockTranslationResources; + private SourceDocResourceClient sourceDocResourceClient; @Mock - ICopyTransResource mockCopyTransResource; + private AsyncProcessClient asyncProcessClient; @Mock - IAsynchronousProcessResource mockAsynchronousProcessResource; + private CopyTransClient copyTransClient; - public PushCommandTest() throws Exception { + @Before + public void setUp() { initMocks(this); + when(clientFactory.getSourceDocResourceClient(anyString(), anyString())) + .thenReturn(sourceDocResourceClient); + when(clientFactory.getAsyncProcessClient()).thenReturn( + asyncProcessClient); + when(clientFactory.getCopyTransClient()).thenReturn(copyTransClient); } @Test @@ -130,13 +131,13 @@ private void checkSplitResult(int listSize, int batchSize) throws Exception { opts.setProj(projectSlug); String versionSlug = "1.0"; opts.setProjectVersion(versionSlug); - opts.setSrcDir(new File("src/test/resources/test1/pot")); + opts.setSrcDir(fileFromClasspath("test1/pot")); if (pushTrans) { opts.setPushType("both"); } else { opts.setPushType("source"); } - opts.setTransDir(new File("src/test/resources/test1")); + opts.setTransDir(fileFromClasspath("test1")); opts.setProjectType("podir"); // opts.setNoCopyTrans(false); opts.setCopyTrans(true); @@ -153,27 +154,19 @@ private void checkSplitResult(int listSize, int batchSize) throws Exception { opts.setLocaleMapList(locales); OptionsUtil.applyConfigFiles(opts); - when(mockRequestFactory.getCopyTransResource()).thenReturn( - mockCopyTransResource); - when(mockRequestFactory.getAsynchronousProcessResource()).thenReturn( - mockAsynchronousProcessResource); - - return new PushCommand(opts, mockRequestFactory, mockSourceDocResource, - mockTranslationResources, new URI("http://example.com/")); + return new PushCommand(opts, + clientFactory.getCopyTransClient(), + clientFactory.getAsyncProcessClient(), clientFactory); } private void push(boolean pushTrans, boolean mapLocale) throws Exception { List resourceMetaList = new ArrayList(); resourceMetaList.add(new ResourceMeta("obsolete")); resourceMetaList.add(new ResourceMeta("RPM")); - when(mockSourceDocResource.get(null)).thenReturn( - new DummyResponse>(Status.OK, - resourceMetaList)); - - final ClientResponse okResponse = - new DummyResponse(Status.OK, null); - when(mockSourceDocResource.deleteResource("obsolete")).thenReturn( - okResponse); + when(sourceDocResourceClient.getResourceMeta(null)).thenReturn( + resourceMetaList); + when(sourceDocResourceClient.deleteResource("obsolete")).thenReturn( + null); StringSet extensionSet = new StringSet("gettext;comment"); // TODO These calls now use a false copyTrans value (2.0) but they // invoke the copy Trans resource. Still need to add Copy Trans resource @@ -186,23 +179,23 @@ private void push(boolean pushTrans, boolean mapLocale) throws Exception { mockStatus.setStatusCode(ProcessStatus.ProcessStatusCode.Finished); mockStatus.setMessages(new ArrayList()); when( - mockAsynchronousProcessResource.startSourceDocCreationOrUpdate( + asyncProcessClient.startSourceDocCreationOrUpdate( eq("RPM"), anyString(), anyString(), - (Resource) notNull(), eq(extensionSet), eq(false))) + any(Resource.class), eq(extensionSet), eq(false))) .thenReturn(mockStatus); when( - mockAsynchronousProcessResource.startSourceDocCreationOrUpdate( + asyncProcessClient.startSourceDocCreationOrUpdate( eq("sub,RPM"), anyString(), anyString(), - (Resource) notNull(), eq(extensionSet), eq(false))) + any(Resource.class), eq(extensionSet), eq(false))) .thenReturn(mockStatus); - when(mockAsynchronousProcessResource.getProcessStatus(anyString())) + when(asyncProcessClient.getProcessStatus(anyString())) .thenReturn(mockStatus); CopyTransStatus mockCopyTransStatus = new CopyTransStatus(); mockCopyTransStatus.setInProgress(false); mockCopyTransStatus.setPercentageComplete(100); when( - mockCopyTransResource.getCopyTransStatus(anyString(), + copyTransClient.getCopyTransStatus(anyString(), anyString(), anyString())).thenReturn( mockCopyTransStatus); @@ -214,11 +207,11 @@ private void push(boolean pushTrans, boolean mapLocale) throws Exception { expectedLocale = new LocaleId("ja-JP"); } when( - mockAsynchronousProcessResource + asyncProcessClient .startTranslatedDocCreationOrUpdate(eq("RPM"), anyString(), anyString(), eq(expectedLocale), - (TranslationsResource) notNull(), + any(TranslationsResource.class), eq(extensionSet), eq("auto"))).thenReturn( mockStatus); // when(mockTranslationResources.putTranslations(eq("RPM"), diff --git a/zanata-client-commands/src/test/java/org/zanata/client/commands/push/XliffPushStrategyTest.java b/zanata-client-commands/src/test/java/org/zanata/client/commands/push/XliffPushStrategyTest.java index e5780aa5..5a4726fa 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/commands/push/XliffPushStrategyTest.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/commands/push/XliffPushStrategyTest.java @@ -18,6 +18,7 @@ import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.zanata.client.TestUtils; import org.zanata.client.commands.push.PushCommand.TranslationResourcesVisitor; import org.zanata.client.config.LocaleList; import org.zanata.client.config.LocaleMapping; @@ -34,8 +35,8 @@ public class XliffPushStrategyTest { private ImmutableList include; private ImmutableList exclude; - private final File sourceDir = new File("src/test/resources/xliffDir"); - private final File sourceDir2 = new File("src/test/resources/xliffDir2"); + private final File sourceDir = TestUtils.fileFromClasspath("xliffDir"); + private final File sourceDir2 = TestUtils.fileFromClasspath("xliffDir2"); private static final String sourceLocale = "en-US"; diff --git a/zanata-client-commands/src/test/java/org/zanata/client/config/ConfigUtilTest.java b/zanata-client-commands/src/test/java/org/zanata/client/config/ConfigUtilTest.java index 3d535110..475506d0 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/config/ConfigUtilTest.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/config/ConfigUtilTest.java @@ -5,6 +5,7 @@ import org.apache.commons.configuration.HierarchicalINIConfiguration; import org.apache.commons.configuration.SubnodeConfiguration; import org.junit.Test; +import org.zanata.client.TestUtils; import static org.junit.Assert.assertEquals; @@ -12,8 +13,8 @@ public class ConfigUtilTest { @Test public void testReadUser() throws Exception { HierarchicalINIConfiguration config = - new HierarchicalINIConfiguration( - "src/test/resources/zanata.ini"); + new HierarchicalINIConfiguration(TestUtils.fileFromClasspath( + "zanata.ini").getAbsolutePath()); SubnodeConfiguration servers = config.getSection("servers"); String url = "https://translate.jboss.org/"; String username = "joe"; diff --git a/zanata-client-commands/src/test/java/org/zanata/client/integraion/FileProjectITCase.java b/zanata-client-commands/src/test/java/org/zanata/client/integraion/FileProjectITCase.java deleted file mode 100644 index fadb401b..00000000 --- a/zanata-client-commands/src/test/java/org/zanata/client/integraion/FileProjectITCase.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2014, Red Hat, Inc. and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.zanata.client.integraion; - -import java.io.File; -import java.io.IOException; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.zanata.client.TestProjectGenerator; -import org.zanata.client.commands.ConfigurableProjectOptions; -import org.zanata.client.commands.push.PushOptionsImpl; -import org.zanata.client.commands.push.RawPushCommand; -import org.zanata.client.config.LocaleList; -import org.zanata.client.config.LocaleMapping; -import org.zanata.common.ProjectType; - -/** - * @author Patrick Huang - * pahuang@redhat.com - */ -public class FileProjectITCase { - private static final Logger log = - LoggerFactory.getLogger(FileProjectITCase.class); - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); - - private TestProjectGenerator testProjectGenerator = - new TestProjectGenerator(); - private PushOptionsImpl opts; - - @Before - public void setUp() throws Exception { - opts = new PushOptionsImpl(); - TestProjectGenerator.ServerInstance instance = - TestProjectGenerator.ServerInstance.FunctionalTestCargo; - opts.setUrl(instance.getURL()); - opts.setUsername(instance.getUsername()); - opts.setKey(instance.getKey()); - testProjectGenerator.ensureProjectOnServer(opts, - ProjectType.File, instance); - opts.setLocaleMapList(new LocaleList()); - opts.getLocaleMapList().add(new LocaleMapping("zh-CN")); - opts.setBatchMode(true); - } - - @Test - public void manualTest() throws IOException { - File baseDir = - testProjectGenerator.getProjectBaseDir(ProjectType.File); - log.debug("testing project is at: {}", baseDir); - opts.setFileTypes("odt,ods"); - opts.setSrcDir(new File(baseDir, "src")); - opts.setTransDir(baseDir); - opts.setProj(testProjectGenerator.sampleProjectSlug(baseDir)); - opts.setProjectVersion(testProjectGenerator.sampleIterationSlug()); - opts.setProjectType("file"); - opts.setFileTypes("odt"); - - RawPushCommand pushCommand = new RawPushCommand(opts); - - pushCommand.run(); - } -} diff --git a/zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullFileProjectITCase.java b/zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullFileProjectITCase.java index 2d9c5cf5..e8710f82 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullFileProjectITCase.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullFileProjectITCase.java @@ -21,11 +21,8 @@ package org.zanata.client.integraion; -import java.io.BufferedInputStream; import java.io.File; import java.io.InputStream; -import java.io.StringBufferInputStream; -import java.io.StringReader; import java.util.ArrayList; import org.apache.commons.codec.Charsets; @@ -36,23 +33,17 @@ import org.junit.rules.TemporaryFolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.zanata.client.MockServerRule; +import org.zanata.client.MockitoServerRule; import org.zanata.client.TestProjectGenerator; import org.zanata.client.commands.ConfigurableProjectOptions; -import org.zanata.client.commands.pull.PullCommand; import org.zanata.client.commands.pull.PullOptionsImpl; import org.zanata.client.commands.pull.RawPullCommand; import org.zanata.client.commands.push.PushOptionsImpl; import org.zanata.client.commands.push.RawPushCommand; import org.zanata.client.config.FileMappingRule; import org.zanata.client.config.LocaleMapping; -import org.zanata.common.LocaleId; import org.zanata.common.ProjectType; -import org.zanata.rest.dto.resource.Resource; import org.zanata.rest.dto.resource.ResourceMeta; -import org.zanata.rest.dto.resource.TextFlow; -import org.zanata.rest.dto.resource.TextFlowTarget; -import org.zanata.rest.dto.resource.TranslationsResource; import com.google.common.collect.Lists; import static org.hamcrest.MatcherAssert.assertThat; @@ -69,7 +60,7 @@ public class PushPullFileProjectITCase { private static final Logger log = LoggerFactory .getLogger(PushPullGettextITCase.class); @Rule - public MockServerRule mockServerRule = new MockServerRule(); + public MockitoServerRule mockitoServerRule = new MockitoServerRule(); @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @@ -78,18 +69,18 @@ public class PushPullFileProjectITCase { @Before public void setUp() { - ConfigurableProjectOptions pullOpts = mockServerRule.getPullOpts(); + ConfigurableProjectOptions pullOpts = mockitoServerRule.getPullOpts(); pullOpts.getLocaleMapList().add(new LocaleMapping("zh-CN")); pullOpts.setProjectType("file"); - ConfigurableProjectOptions pushOpts = mockServerRule.getPushOpts(); + ConfigurableProjectOptions pushOpts = mockitoServerRule.getPushOpts(); pushOpts.getLocaleMapList().add(new LocaleMapping("zh-CN")); pushOpts.setProjectType("file"); } @Test public void pushFileTypeProject() throws Exception { - PushOptionsImpl opts = mockServerRule.getPushOpts(); + PushOptionsImpl opts = mockitoServerRule.getPushOpts(); opts.setPushType("both"); File baseDir = testProjectGenerator.getProjectBaseDir(ProjectType.File); @@ -98,23 +89,23 @@ public void pushFileTypeProject() throws Exception { opts.setSrcDir(new File(baseDir, "src")); opts.setTransDir(baseDir); - RawPushCommand pushCommand = mockServerRule.createRawPushCommand(); + RawPushCommand pushCommand = mockitoServerRule.createRawPushCommand(); pushCommand.run(); - mockServerRule.verifyPushRawFileSource(2); - assertThat(mockServerRule.getDocIdCaptor().getAllValues(), + mockitoServerRule.verifyPushRawFileSource(2); + assertThat(mockitoServerRule.getDocIdCaptor().getAllValues(), contains("test-ods.ods", "test-odt.odt")); - mockServerRule.verifyPushRawFileTranslation(1); - assertThat(mockServerRule.getDocIdCaptor().getValue(), + mockitoServerRule.verifyPushRawFileTranslation(1); + assertThat(mockitoServerRule.getDocIdCaptor().getValue(), equalTo("test-odt.odt")); } @Test public void pushFileProjectUsingFileMapping() throws Exception { - PushOptionsImpl opts = mockServerRule.getPushOpts(); + PushOptionsImpl opts = mockitoServerRule.getPushOpts(); opts.setPushType("trans"); File baseDir = testProjectGenerator.getProjectBaseDir(ProjectType.File); @@ -125,18 +116,18 @@ public void pushFileProjectUsingFileMapping() throws Exception { opts.setFileMappingRules(Lists.newArrayList(new FileMappingRule( "{locale}/{path}/{filename}.{extension}"))); - RawPushCommand pushCommand = mockServerRule.createRawPushCommand(); + RawPushCommand pushCommand = mockitoServerRule.createRawPushCommand(); pushCommand.run(); - mockServerRule.verifyPushRawFileTranslation(1); - assertThat(mockServerRule.getDocIdCaptor().getValue(), + mockitoServerRule.verifyPushRawFileTranslation(1); + assertThat(mockitoServerRule.getDocIdCaptor().getValue(), equalTo("test-odt.odt")); } @Test public void pullFileProject() throws Exception { - PullOptionsImpl opts = mockServerRule.getPullOpts(); + PullOptionsImpl opts = mockitoServerRule.getPullOpts(); opts.setPullType("both"); File pullBaseDir = tempFolder.newFolder("file-pull-test"); opts.setSrcDir(pullBaseDir); @@ -151,7 +142,7 @@ public void pullFileProject() throws Exception { Lists.newArrayList(new ResourceMeta("test-ods.ods"), new ResourceMeta("test-odt.odt")); - RawPullCommand pullCommand = mockServerRule.createRawPullCommand( + RawPullCommand pullCommand = mockitoServerRule.createRawPullCommand( remoteDocList, sourceFileStream, transFileStream); pullCommand.run(); @@ -164,7 +155,7 @@ public void pullFileProject() throws Exception { @Test public void pullFileProjectUsingFileMapping() throws Exception { - PullOptionsImpl opts = mockServerRule.getPullOpts(); + PullOptionsImpl opts = mockitoServerRule.getPullOpts(); opts.setPullType("trans"); File pullBaseDir = tempFolder.newFolder("file-pull-test"); opts.setSrcDir(pullBaseDir); @@ -184,7 +175,7 @@ public void pullFileProjectUsingFileMapping() throws Exception { Lists.newArrayList(new ResourceMeta("test-ods.ods"), new ResourceMeta("test-odt.odt")); - RawPullCommand pullCommand = mockServerRule.createRawPullCommand( + RawPullCommand pullCommand = mockitoServerRule.createRawPullCommand( remoteDocList, sourceFileStream, transFileStream); pullCommand.run(); diff --git a/zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullGettextITCase.java b/zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullGettextITCase.java index 1290cb02..75cdab49 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullGettextITCase.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullGettextITCase.java @@ -1,7 +1,6 @@ package org.zanata.client.integraion; import java.io.File; -import java.io.IOException; import java.util.Set; import org.hamcrest.Matchers; @@ -11,7 +10,7 @@ import org.junit.rules.TemporaryFolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.zanata.client.MockServerRule; +import org.zanata.client.MockitoServerRule; import org.zanata.client.TestProjectGenerator; import org.zanata.client.commands.ConfigurableProjectOptions; import org.zanata.client.commands.pull.PullCommand; @@ -42,7 +41,7 @@ public class PushPullGettextITCase { private static final Logger log = LoggerFactory .getLogger(PushPullGettextITCase.class); @Rule - public MockServerRule mockServerRule = new MockServerRule(); + public MockitoServerRule mockitoServerRule = new MockitoServerRule(); @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @@ -51,18 +50,18 @@ public class PushPullGettextITCase { @Before public void setUp() { - ConfigurableProjectOptions pullOpts = mockServerRule.getPullOpts(); + ConfigurableProjectOptions pullOpts = mockitoServerRule.getPullOpts(); pullOpts.getLocaleMapList().add(new LocaleMapping("zh-CN")); pullOpts.setProjectType("gettext"); - ConfigurableProjectOptions pushOpts = mockServerRule.getPushOpts(); + ConfigurableProjectOptions pushOpts = mockitoServerRule.getPushOpts(); pushOpts.getLocaleMapList().add(new LocaleMapping("zh-CN")); pushOpts.setProjectType("gettext"); } @Test public void pushGettextProject() throws Exception { - PushOptionsImpl opts = mockServerRule.getPushOpts(); + PushOptionsImpl opts = mockitoServerRule.getPushOpts(); opts.setPushType("both"); File baseDir = testProjectGenerator.getProjectBaseDir(ProjectType.Gettext); @@ -70,31 +69,31 @@ public void pushGettextProject() throws Exception { opts.setSrcDir(new File(baseDir, "po")); opts.setTransDir(new File(baseDir, "po")); - PushCommand pushCommand = mockServerRule.createPushCommand(); + PushCommand pushCommand = mockitoServerRule.createPushCommand(); pushCommand.run(); - mockServerRule.verifyPushSource(); - String docId = mockServerRule.getDocIdCaptor().getValue(); + mockitoServerRule.verifyPushSource(); + String docId = mockitoServerRule.getDocIdCaptor().getValue(); assertThat(docId, equalTo("tar")); - assertThat(mockServerRule.getExtensionCaptor().getValue(), + assertThat(mockitoServerRule.getExtensionCaptor().getValue(), Matchers. equalTo(new StringSet("gettext;comment"))); - Resource resource = mockServerRule.getResourceCaptor().getValue(); + Resource resource = mockitoServerRule.getResourceCaptor().getValue(); assertThat(resource.getTextFlows(), hasSize(2)); - mockServerRule.verifyPushTranslation(); - LocaleId localeId = mockServerRule.getLocaleIdCaptor().getValue(); + mockitoServerRule.verifyPushTranslation(); + LocaleId localeId = mockitoServerRule.getLocaleIdCaptor().getValue(); assertThat(localeId, equalTo(new LocaleId("zh-CN"))); TranslationsResource transResource = - mockServerRule.getTransResourceCaptor().getValue(); + mockitoServerRule.getTransResourceCaptor().getValue(); assertThat(transResource.getTextFlowTargets(), hasSize(2)); } @Test public void pushGettextProjectUsingFileMapping() throws Exception { - PushOptionsImpl opts = mockServerRule.getPushOpts(); + PushOptionsImpl opts = mockitoServerRule.getPushOpts(); opts.setPushType("trans"); File baseDir = testProjectGenerator.getProjectBaseDir(ProjectType.Gettext); @@ -104,22 +103,22 @@ public void pushGettextProjectUsingFileMapping() throws Exception { opts.setFileMappingRules(Lists.newArrayList(new FileMappingRule( "{path}/{locale_with_underscore}.po"))); - PushCommand pushCommand = mockServerRule.createPushCommand(); + PushCommand pushCommand = mockitoServerRule.createPushCommand(); pushCommand.run(); - mockServerRule.verifyPushTranslation(); - LocaleId localeId = mockServerRule.getLocaleIdCaptor().getValue(); + mockitoServerRule.verifyPushTranslation(); + LocaleId localeId = mockitoServerRule.getLocaleIdCaptor().getValue(); assertThat(localeId, equalTo(new LocaleId("zh-CN"))); TranslationsResource transResource = - mockServerRule.getTransResourceCaptor().getValue(); + mockitoServerRule.getTransResourceCaptor().getValue(); assertThat(transResource.getTextFlowTargets(), hasSize(2)); } @Test public void pullGettextProject() throws Exception { - PullOptionsImpl opts = mockServerRule.getPullOpts(); + PullOptionsImpl opts = mockitoServerRule.getPullOpts(); opts.setPullType("both"); File pullBaseDir = tempFolder.newFolder("gettext-pull-test"); opts.setSrcDir(pullBaseDir); @@ -134,7 +133,7 @@ public void pullGettextProject() throws Exception { target.setContents("hello world translated"); transResourceOnServer.getTextFlowTargets().add(target); - PullCommand pullCommand = mockServerRule.createPullCommand( + PullCommand pullCommand = mockitoServerRule.createPullCommand( Lists.newArrayList(new ResourceMeta("tar")), resourceOnServer, transResourceOnServer); @@ -146,7 +145,7 @@ public void pullGettextProject() throws Exception { @Test public void pullGettextProjectUsingFileMapping() throws Exception { - PullOptionsImpl opts = mockServerRule.getPullOpts(); + PullOptionsImpl opts = mockitoServerRule.getPullOpts(); opts.setPullType("trans"); File pullBaseDir = tempFolder.newFolder("gettext-pull-test"); opts.setSrcDir(pullBaseDir); @@ -164,7 +163,7 @@ public void pullGettextProjectUsingFileMapping() throws Exception { target.setContents("hello world translated"); transResourceOnServer.getTextFlowTargets().add(target); - PullCommand pullCommand = mockServerRule.createPullCommand( + PullCommand pullCommand = mockitoServerRule.createPullCommand( Lists.newArrayList(new ResourceMeta("tar")), resourceOnServer, transResourceOnServer); diff --git a/zanata-rest-client/pom.xml b/zanata-rest-client/pom.xml index 3aedfd7d..3919d9a7 100644 --- a/zanata-rest-client/pom.xml +++ b/zanata-rest-client/pom.xml @@ -20,28 +20,15 @@ + + + org.jboss.resteasy + jaxrs-api + test + org.zanata zanata-common-api - - - - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - jaxrs-api - - - org.jboss.resteasy - resteasy-multipart-provider - - org.zanata @@ -49,7 +36,6 @@ - org.zanata mock-server ${project.version} @@ -59,17 +45,17 @@ com.sun.jersey jersey-core - 1.17.1 + ${jersey.version} com.sun.jersey jersey-client - 1.17.1 + ${jersey.version} com.sun.jersey.contribs jersey-multipart - 1.17.1 + ${jersey.version} @@ -149,4 +135,17 @@ + + + + com.ning.maven.plugins + maven-duplicate-finder-plugin + 1.0.7 + + false + + + + + diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/AccountClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/AccountClient.java index aa879759..940892aa 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/AccountClient.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/AccountClient.java @@ -36,7 +36,7 @@ public class AccountClient { private final RestClientFactory factory; private final URI baseUri; - public AccountClient(RestClientFactory factory) { + AccountClient(RestClientFactory factory) { this.factory = factory; this.baseUri = factory.getBaseUri(); } diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/AsyncProcessClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/AsyncProcessClient.java index 8411b585..985584de 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/AsyncProcessClient.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/AsyncProcessClient.java @@ -24,6 +24,7 @@ import java.net.URI; import java.util.Set; import javax.ws.rs.DefaultValue; +import javax.ws.rs.core.UriBuilder; import org.zanata.common.LocaleId; import org.zanata.rest.dto.ProcessStatus; @@ -31,16 +32,19 @@ import org.zanata.rest.dto.resource.TranslationsResource; import org.zanata.rest.service.AsynchronousProcessResource; import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.WebResource; + +import static org.zanata.rest.client.ClientUtil.resolvePath; /** - * @author Patrick Huang - * pahuang@redhat.com + * @author Patrick Huang pahuang@redhat.com */ public class AsyncProcessClient implements AsynchronousProcessResource { private final RestClientFactory factory; private final URI baseUri; - public AsyncProcessClient(RestClientFactory factory) { + AsyncProcessClient(RestClientFactory factory) { this.factory = factory; baseUri = factory.getBaseUri(); } @@ -49,7 +53,8 @@ public AsyncProcessClient(RestClientFactory factory) { public ProcessStatus startSourceDocCreation(String idNoSlash, String projectSlug, String iterationSlug, Resource resource, Set extensions, @DefaultValue("true") boolean copytrans) { - throw new UnsupportedOperationException("Not supported. Use startSourceDocCreationOrUpdate instead."); + throw new UnsupportedOperationException( + "Not supported. Use startSourceDocCreationOrUpdate instead."); } @Override @@ -59,11 +64,13 @@ public ProcessStatus startSourceDocCreationOrUpdate(String idNoSlash, Client client = factory.getClient(); CacheResponseFilter filter = new CacheResponseFilter(); client.addFilter(filter); - client.resource(baseUri) - .path(AsynchronousProcessResource.SERVICE_PATH) - .path("projects").path("p").path(projectSlug) - .path("iterations").path("i").path(iterationSlug) - .path("r").path(idNoSlash) + WebResource webResource = client.resource(baseUri); + String path = + resolvePath(webResource, AsynchronousProcessResource.class, + "startSourceDocCreationOrUpdate", projectSlug, + iterationSlug, idNoSlash); + + webResource.path(path) .queryParams(ClientUtil.asMultivaluedMap("ext", extensions)) .queryParam("copyTrans", String.valueOf(copytrans)) .put(resource); @@ -79,12 +86,12 @@ public ProcessStatus startTranslatedDocCreationOrUpdate(String idNoSlash, Client client = factory.getClient(); CacheResponseFilter filter = new CacheResponseFilter(); client.addFilter(filter); - client.resource(baseUri) - .path(AsynchronousProcessResource.SERVICE_PATH) - .path("projects").path("p").path(projectSlug) - .path("iterations").path("i").path(iterationSlug) - .path("r").path(idNoSlash) - .path("translations").path(locale.getId()) + WebResource webResource = client.resource(baseUri); + String path = + resolvePath(webResource, AsynchronousProcessResource.class, + "startTranslatedDocCreationOrUpdate", projectSlug, + iterationSlug, idNoSlash, locale); + webResource.path(path) .queryParams(ClientUtil.asMultivaluedMap("ext", extensions)) .queryParam("merge", merge) .put(translatedDoc); diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/CacheResponseFilter.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/CacheResponseFilter.java index bee5a842..eb92abfd 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/CacheResponseFilter.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/CacheResponseFilter.java @@ -36,7 +36,7 @@ * @author Patrick Huang pahuang@redhat.com */ -public class CacheResponseFilter extends ClientFilter { +class CacheResponseFilter extends ClientFilter { private Optional cachedClientResponse = Optional.absent(); @Override diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/ClientUtil.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ClientUtil.java index f367956f..8463502f 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/ClientUtil.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/ClientUtil.java @@ -21,36 +21,68 @@ package org.zanata.rest.client; +import java.lang.reflect.Field; import java.lang.reflect.Method; -import java.util.Set; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import com.google.common.base.Strings; import com.google.common.base.Throwables; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; /** - * @author Patrick Huang - * pahuang@redhat.com + * @author Patrick Huang pahuang@redhat.com */ public class ClientUtil { - - static Method getMethod(Class resourceClass, - String methodName, Class... paramTypes) { + /** + * Resolve a REST resource path to a method. + * + * @param webResource + * web resource + * @param resourceInterface + * Zanata REST api interface + * @param methodName + * the method name we want to call which is annotated by @Path + * @param pathParams + * path param values + * @param + * interface type + * @return resolved path + */ + static String resolvePath(WebResource webResource, + Class resourceInterface, String methodName, + Object... pathParams) { try { - return resourceClass.getMethod(methodName, paramTypes); - } catch (NoSuchMethodException e) { + // Zanata API always define SERVICE_PATH field + Field servicePathField = resourceInterface.getField("SERVICE_PATH"); + String servicePath = servicePathField.get(null).toString(); + Method method = getMethod(resourceInterface, methodName); + return webResource.getUriBuilder().path(servicePath).path(method) + .build(pathParams).getPath(); + } catch (NoSuchFieldException | IllegalAccessException e) { throw Throwables.propagate(e); } } - static Class[] arrayOf(int number, Class type) { - Class[] result = new Class[number]; - for (int i = 0; i < number; i++) { - result[i] = type; + private static Method getMethod(Class resourceClass, + String methodName) { + Method[] methods = resourceClass.getDeclaredMethods(); + for (Method method : methods) { + if (method.getName().equals(methodName)) { + return method; + } } - return result; + throw new IllegalArgumentException(methodName + " not found in " + + resourceClass); } static MultivaluedMap asMultivaluedMap( @@ -64,4 +96,61 @@ static MultivaluedMap asMultivaluedMap( } return map; } + + public static void checkResult(ClientResponse response) { + ClientResponse.Status responseStatus = + response.getClientResponseStatus(); + int statusCode = response.getStatus(); + + if (responseStatus == ClientResponse.Status.UNAUTHORIZED) { + throw new RuntimeException("Incorrect username/password"); + } else if (responseStatus == ClientResponse.Status.SERVICE_UNAVAILABLE) { + throw new RuntimeException("Service is currently unavailable. " + + "Please check outage notification or try again later."); + } else if (responseStatus == ClientResponse.Status.MOVED_PERMANENTLY + || statusCode == 302) { + // if server returns a redirect (most likely due to http to https + // redirect), we don't want to bury this information in a xml + // marshalling exception. + String movedTo = response.getHeaders().getFirst("Location"); + + String message; + if (!Strings.isNullOrEmpty(movedTo)) { + String baseUrl = getBaseURL(movedTo); + message = "Server returned a redirect to:" + baseUrl + + ". You must change your url option or config file."; + } else { + message = + "Server returned a redirect. You must change your url option or config file."; + } + throw new RuntimeException(message); + } else if (statusCode >= 399) { + String annotString = ""; + String uriString = ""; + String entity = ""; + try { + entity = ": " + response.getEntity(String.class); + } finally { + // ignore + } + String msg = + "operation returned " + + statusCode + + " (" + + Response.Status.fromStatusCode(statusCode) + ")" + + entity + uriString + + annotString; + throw new RuntimeException(msg); + } + } + + public static String getBaseURL(String movedTo) { + try { + URL url = new URI(movedTo).toURL(); + int pathIndex = movedTo.lastIndexOf(url.getPath()); + return movedTo.substring(0, pathIndex) + "/"; + } catch (MalformedURLException | URISyntaxException e) { + return movedTo; + } + } } diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/ClientUtility.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ClientUtility.java deleted file mode 100644 index aa4c8e04..00000000 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/ClientUtility.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.zanata.rest.client; - -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.Arrays; - -import javax.ws.rs.core.Response; - -import org.jboss.resteasy.client.ClientResponse; -import org.jboss.resteasy.client.core.BaseClientResponse; -import com.google.common.base.Strings; - -public class ClientUtility { - public static void checkResult(ClientResponse response) { - checkResult(response, null); - } - - public static void checkResult(ClientResponse response, URI uri) { - Response.Status responseStatus = response.getResponseStatus(); - int statusCode = response.getStatus(); - - if (responseStatus == Response.Status.UNAUTHORIZED) { - throw new RuntimeException("Incorrect username/password"); - } else if (responseStatus == Response.Status.SERVICE_UNAVAILABLE) { - throw new RuntimeException("Service is currently unavailable. " + - "Please check outage notification or try again later."); - } else if (responseStatus == Response.Status.MOVED_PERMANENTLY - || statusCode == 302 ) { - // if server returns a redirect (most likely due to http to https - // redirect), we don't want to bury this information in a xml - // marshalling exception. - String movedTo = "FIX ME"; - - String message; - if (!Strings.isNullOrEmpty(movedTo)) { - String baseUrl = getBaseURL(movedTo); - message = "Server returned a redirect to:" + baseUrl + - ". You must change your url option or config file."; - } else { - message = "Server returned a redirect. You must change your url option or config file."; - } - throw new RuntimeException(message); - } else if (statusCode >= 399) { - String annotString = ""; - String uriString = ""; - String entity = ""; - if (response instanceof BaseClientResponse) { - BaseClientResponse resp = (BaseClientResponse) response; - annotString = - ", annotations: " - + Arrays.asList(resp.getAnnotations()) - .toString(); - } - if (uri != null) { - uriString = ", uri: " + uri; - } - try { - entity = ": " + response.getEntity(String.class); - } finally { - // ignore - } - String msg = - "operation returned " - + statusCode - + " (" - + Response.Status.fromStatusCode(statusCode) + ")" - + entity + uriString - + annotString; - throw new RuntimeException(msg); - } - } - - public static String getBaseURL(String movedTo) { - try { - URL url = new URI(movedTo).toURL(); - int pathIndex = movedTo.lastIndexOf(url.getPath()); - return movedTo.substring(0, pathIndex) + "/"; - } - catch (MalformedURLException | URISyntaxException e) { - return movedTo; - } - } - - public static void checkResultAndReleaseConnection( - ClientResponse clientResponse) { - checkResult(clientResponse, null); - clientResponse.releaseConnection(); - } -} diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/CopyTransClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/CopyTransClient.java index 74a7dca1..7932bbff 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/CopyTransClient.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/CopyTransClient.java @@ -28,6 +28,8 @@ import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; +import static org.zanata.rest.client.ClientUtil.resolvePath; + /** * @author Patrick Huang pahuang@redhat.com @@ -36,7 +38,7 @@ public class CopyTransClient implements CopyTransResource { private final RestClientFactory factory; private final URI baseUri; - public CopyTransClient(RestClientFactory factory) { + CopyTransClient(RestClientFactory factory) { this.factory = factory; baseUri = factory.getBaseUri(); } @@ -56,11 +58,11 @@ public CopyTransStatus startCopyTrans(String projectSlug, private WebResource webResource(Client client, String projectSlug, String iterationSlug, String docId) { - return client.resource(baseUri) - .path(CopyTransResource.SERVICE_PATH) - .path("proj").path(projectSlug) - .path("iter").path(iterationSlug) - .path("doc").path(docId); + WebResource webResource = client.resource(baseUri); + String path = + resolvePath(webResource, CopyTransResource.class, + "startCopyTrans", projectSlug, iterationSlug, docId); + return webResource.path(path); } @Override diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/FileResourceClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/FileResourceClient.java index 84d56d0c..a99bdfe7 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/FileResourceClient.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/FileResourceClient.java @@ -21,21 +21,22 @@ package org.zanata.rest.client; -import java.io.InputStream; +import static org.zanata.rest.client.ClientUtil.resolvePath; + import java.net.URI; + import javax.ws.rs.core.MediaType; import org.zanata.rest.DocumentFileUploadForm; import org.zanata.rest.StringSet; import org.zanata.rest.dto.ChunkUploadResponse; import org.zanata.rest.service.FileResource; + 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.multipart.FormDataMultiPart; -import static org.zanata.rest.client.ClientUtil.arrayOf; -import static org.zanata.rest.client.ClientUtil.getMethod; - /** * @author Patrick Huang pahuang@redhat.com @@ -45,7 +46,7 @@ public class FileResourceClient { private final URI baseUri; - public FileResourceClient(RestClientFactory restClientFactory) { + FileResourceClient(RestClientFactory restClientFactory) { this.factory = restClientFactory; baseUri = restClientFactory.getBaseUri(); @@ -129,41 +130,28 @@ public ChunkUploadResponse uploadTranslationFile( return chunkUploadResponse; } - public InputStream downloadSourceFile(String projectSlug, + public ClientResponse downloadSourceFile(String projectSlug, String iterationSlug, String fileType, String docId) { WebResource webResource = factory.getClient().resource(baseUri); - URI uri = - webResource - .getUriBuilder() - .path(FileResource.SERVICE_PATH) - .path(getMethod(FileResource.class, - "downloadSourceFile", - arrayOf(4, String.class))) - .build(projectSlug, iterationSlug, fileType); - return webResource - .path(uri.getPath()) + String path = resolvePath(webResource, FileResource.class, + "downloadSourceFile", projectSlug, iterationSlug, fileType); + return webResource.path(path) .queryParam("docId", docId) - .get(InputStream.class); + .get(ClientResponse.class); } - public InputStream downloadTranslationFile(String projectSlug, + public ClientResponse downloadTranslationFile(String projectSlug, String iterationSlug, String locale, String fileExtension, String docId) { WebResource webResource = factory.getClient().resource(baseUri); - URI uri = - webResource - .getUriBuilder() - .path(FileResource.SERVICE_PATH) - .path(getMethod(FileResource.class, - "downloadTranslationFile", - arrayOf(5, String.class))) - .build(projectSlug, iterationSlug, locale, - fileExtension); - return webResource - .path(uri.getPath()) + String path = + resolvePath(webResource, FileResource.class, + "downloadTranslationFile", + projectSlug, iterationSlug, locale, fileExtension); + return webResource.path(path) .queryParam("docId", docId) - .get(InputStream.class); + .get(ClientResponse.class); } diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/GlossaryClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/GlossaryClient.java index 673e6470..93233325 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/GlossaryClient.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/GlossaryClient.java @@ -36,7 +36,7 @@ public class GlossaryClient { private final RestClientFactory factory; private final URI baseUri; - public GlossaryClient(RestClientFactory factory) { + GlossaryClient(RestClientFactory factory) { this.factory = factory; baseUri = factory.getBaseUri(); } diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectClient.java index c88566a0..695a812e 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectClient.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectClient.java @@ -22,6 +22,7 @@ package org.zanata.rest.client; import org.zanata.rest.dto.Project; +import org.zanata.rest.service.ProjectResource; import com.sun.jersey.api.client.WebResource; /** @@ -32,7 +33,7 @@ public class ProjectClient { private final RestClientFactory factory; private final String projectSlug; - public ProjectClient(RestClientFactory factory, String projectSlug) { + ProjectClient(RestClientFactory factory, String projectSlug) { this.factory = factory; this.projectSlug = projectSlug; } diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectIterationClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectIterationClient.java index 3b7e5224..e0051472 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectIterationClient.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectIterationClient.java @@ -36,7 +36,7 @@ public class ProjectIterationClient { private final String versionSlug; private URI baseUri; - public ProjectIterationClient(RestClientFactory factory, String projectSlug, String versionSlug) { + ProjectIterationClient(RestClientFactory factory, String projectSlug, String versionSlug) { this.factory = factory; this.projectSlug = projectSlug; this.versionSlug = versionSlug; diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectsClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectsClient.java index 4f25408f..24eca02b 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectsClient.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectsClient.java @@ -32,7 +32,7 @@ public class ProjectsClient { private final RestClientFactory factory; - public ProjectsClient(RestClientFactory factory) { + ProjectsClient(RestClientFactory factory) { this.factory = factory; } diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/RestClientFactory.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/RestClientFactory.java index 75ede466..1c2c15e9 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/RestClientFactory.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/RestClientFactory.java @@ -36,9 +36,11 @@ import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; +import org.apache.maven.artifact.versioning.DefaultArtifactVersion; import org.codehaus.jackson.jaxrs.JacksonJsonProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.zanata.rest.RestConstant; import org.zanata.rest.dto.VersionInfo; import com.google.common.base.Throwables; @@ -55,6 +57,7 @@ public class RestClientFactory { private static final Logger log = LoggerFactory.getLogger(RestClientFactory.class); + private String serverVersion; private String clientVersion; private VersionInfo clientApiVersion; @@ -119,6 +122,30 @@ public VersionInfo getServerVersionInfo() { .get(VersionInfo.class); } + public void performVersionCheck() { + clientVersion = clientApiVersion.getVersionNo(); + String clientScm = clientApiVersion.getScmDescribe(); + + VersionInfo serverVersionInfo = getServerVersionInfo(); + serverVersion = serverVersionInfo.getVersionNo(); + String serverScm = serverVersionInfo.getScmDescribe(); + log.info("client API version: {}, server API version: {}", + clientVersion, serverVersion); + warnMismatchAPIVersion(clientScm, serverScm); + } + + private void warnMismatchAPIVersion(String clientScm, String serverScm) { + if (!serverVersion.equals(clientVersion)) { + log.warn("client API version is {}, but server API version is {}", + clientVersion, serverVersion); + } else if (serverVersion.contains(RestConstant.SNAPSHOT_VERSION) + && !serverScm.equalsIgnoreCase(clientScm)) { + log.warn( + "client API SCM id is {}, but server API SCM id is {}", + clientScm, serverScm); + } + } + private URL getBaseUrl() { try { return new URL(fixBase(baseURI).toString() + getUrlPrefix()); @@ -160,6 +187,71 @@ protected Client getClient() { return client; } + /** + * Compares a given version identifier with the server version. + * + * @param version + * The version to against which to compare the server version. + * @return A positive integer if the server version is greater than the + * given version. A negative integer if the server version is less + * than the given version. 0 if both versions are the same. + */ + public int compareToServerVersion(String version) { + DefaultArtifactVersion srvVersion = + new DefaultArtifactVersion(serverVersion); + DefaultArtifactVersion providedVersion = + new DefaultArtifactVersion(version); + + return srvVersion.compareTo(providedVersion); + } + + public AccountClient getAccountClient() { + return new AccountClient(this); + } + + public AsyncProcessClient getAsyncProcessClient() { + return new AsyncProcessClient(this); + } + + public CopyTransClient getCopyTransClient() { + return new CopyTransClient(this); + } + + public FileResourceClient getFileResourceClient() { + return new FileResourceClient(this); + } + + public GlossaryClient getGlossaryClient() { + return new GlossaryClient(this); + } + + public ProjectClient getProjectClient(String projectSlug) { + return new ProjectClient(this, projectSlug); + } + + public ProjectIterationClient getProjectIterationClient(String projectSlug, + String versionSlug) { + return new ProjectIterationClient(this, projectSlug, versionSlug); + } + + public ProjectsClient getProjectsClient() { + return new ProjectsClient(this); + } + + public SourceDocResourceClient getSourceDocResourceClient( + String projectSlug, String versionSlug) { + return new SourceDocResourceClient(this, projectSlug, versionSlug); + } + + public StatisticsResourceClient getStatisticsClient() { + return new StatisticsResourceClient(this); + } + + public TransDocResourceClient getTransDocResourceClient(String projectSlug, + String versionSlug) { + return new TransDocResourceClient(this, projectSlug, versionSlug); + } + private static class AcceptAllX509TrustManager implements X509TrustManager { public X509Certificate[] getAcceptedIssuers() { return null; diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/SourceDocResourceClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/SourceDocResourceClient.java index 11946f89..e6553fb9 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/SourceDocResourceClient.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/SourceDocResourceClient.java @@ -48,7 +48,7 @@ public class SourceDocResourceClient { private final String projectVersion; private final URI baseUri; - public SourceDocResourceClient(RestClientFactory factory, String project, + SourceDocResourceClient(RestClientFactory factory, String project, String projectVersion) { this.factory = factory; this.project = project; diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/StatisticsResourceClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/StatisticsResourceClient.java index 7c877c5b..7bc6a071 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/StatisticsResourceClient.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/StatisticsResourceClient.java @@ -40,7 +40,7 @@ public class StatisticsResourceClient implements StatisticsResource { private final RestClientFactory factory; private final URI baseUri; - public StatisticsResourceClient(RestClientFactory factory) { + StatisticsResourceClient(RestClientFactory factory) { this.factory = factory; baseUri = factory.getBaseUri(); } diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/TransDocResourceClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/TransDocResourceClient.java index 60a67afe..dd9fe2f2 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/TransDocResourceClient.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/TransDocResourceClient.java @@ -31,6 +31,7 @@ import org.zanata.common.LocaleId; import org.zanata.rest.dto.resource.TranslationsResource; import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import static org.zanata.rest.client.ClientUtil.asMultivaluedMap; @@ -47,7 +48,7 @@ public class TransDocResourceClient { private final String projectVersion; private final URI baseUri; - public TransDocResourceClient(RestClientFactory factory, String project, + TransDocResourceClient(RestClientFactory factory, String project, String projectVersion) { this.factory = factory; this.project = project; @@ -55,7 +56,7 @@ public TransDocResourceClient(RestClientFactory factory, String project, baseUri = factory.getBaseUri(); } - public TranslationsResource getTranslations( + public ClientResponse getTranslations( @PathParam("id") String idNoSlash, @PathParam("locale") LocaleId locale, @QueryParam("ext") Set extensions, @@ -68,7 +69,7 @@ public TranslationsResource getTranslations( .queryParams(asMultivaluedMap("ext", extensions)) .queryParam("skeletons", String.valueOf(createSkeletons)) .header(HttpHeaders.IF_NONE_MATCH, eTag) - .get(TranslationsResource.class); + .get(ClientResponse.class); } private WebResource getBaseServiceResource(Client client) { diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/ZanataProxyFactory.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ZanataProxyFactory.java deleted file mode 100644 index afc0b096..00000000 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/ZanataProxyFactory.java +++ /dev/null @@ -1,462 +0,0 @@ -package org.zanata.rest.client; - -import java.io.IOException; -import java.lang.reflect.Method; -import java.net.ConnectException; -import java.net.InetSocketAddress; -import java.net.MalformedURLException; -import java.net.Socket; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.UnknownHostException; -import java.security.SecureRandom; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; - -import org.apache.commons.beanutils.PropertyUtils; -import org.apache.commons.lang.SystemUtils; -import org.apache.http.HttpHost; -import org.apache.http.client.HttpClient; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.conn.ConnectTimeoutException; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.conn.ssl.X509HostnameVerifier; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.params.HttpParams; -import org.apache.http.protocol.HttpContext; -import org.apache.maven.artifact.versioning.DefaultArtifactVersion; -import org.jboss.resteasy.client.ClientExecutor; -import org.jboss.resteasy.client.ClientRequestFactory; -import org.jboss.resteasy.client.ClientResponse; -import org.jboss.resteasy.client.core.ClientInterceptorRepository; -import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor; -import org.jboss.resteasy.client.exception.ResteasyIOException; -import org.jboss.resteasy.plugins.providers.RegisterBuiltin; -import org.jboss.resteasy.spi.ResteasyProviderFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.zanata.rest.RestConstant; -import org.zanata.rest.dto.VersionInfo; -import com.google.common.base.Throwables; - -// TODO fix deprecation warnings -public class ZanataProxyFactory { - private static final Logger log = LoggerFactory - .getLogger(ZanataProxyFactory.class); - - static { - ResteasyProviderFactory instance = - ResteasyProviderFactory.getInstance(); - RegisterBuiltin.register(instance); - - if (!SystemUtils.isJavaVersionAtLeast(1.7f)) { - log.warn("Please upgrade to Java 1.7 or later, or you may have trouble connecting to some secure hosts."); - } - } - - private VersionInfo clientApiVersion; - - private String clientVersion; - private String serverVersion; - - private ClientRequestFactory crf; - - /** - * see org.zanata.client.commands.init.InitCommand.MockZanataProxyFactory - */ - protected ZanataProxyFactory() { - } - - /** - * This will by default pass a null ClientExecutor to the - * ClientRequestFactory which in turn create default client executor. If - * sslCertDisabled is true, we will create our customized ClientExecutor. - * - * @param base - * base url - * @param username - * username - * @param apiKey - * api key - * @param clientApiVersion - * client API version - * @param logHttp - * whether to log http output - * @param sslCertDisabled - * whether to disable SSL certificate verification - */ - public ZanataProxyFactory(URI base, String username, String apiKey, - VersionInfo clientApiVersion, boolean logHttp, - boolean sslCertDisabled) { - this(base, username, apiKey, clientApiVersion, logHttp, - sslCertDisabled, true); - } - - /** - * Same as - * org.zanata.rest.client.ZanataProxyFactory#ZanataProxyFactory(java. - * net.URI, java.lang.String, java.lang.String, - * org.zanata.rest.dto.VersionInfo, boolean, boolean) except it allows to - * configure whether to do an eager REST version check to the server. - * - * @param eagerVersionCheck - * whether or not to perform an eager REST version call - */ - public ZanataProxyFactory(URI base, String username, String apiKey, - VersionInfo clientApiVersion, boolean logHttp, - boolean sslCertDisabled, boolean eagerVersionCheck) { - this.clientApiVersion = clientApiVersion; - ClientExecutor clientExecutor = createClientExecutor(sslCertDisabled); - - crf = new ClientRequestFactory(clientExecutor, null, fixBase(base)); - // This is not doing anything. - // There is no easy way to handle redirect with resteasy at the moment. - // See https://issues.jboss.org/browse/RESTEASY-1075 - // See org.zanata.rest.client.ClientUtility.checkResult(org.jboss.resteasy.client.ClientResponse, java.net.URI)() - crf.setFollowRedirects(true); -// registerPrefixInterceptor(new TraceDebugInterceptor(logHttp)); -// registerPrefixInterceptor(new ApiKeyHeaderDecorator(username, apiKey, -// clientApiVersion.getVersionNo())); - if (eagerVersionCheck) { - performVersionCheck(); - } - } - - - public void performVersionCheck() { - clientVersion = clientApiVersion.getVersionNo(); - String clientScm = clientApiVersion.getScmDescribe(); - - VersionInfo serverVersionInfo = getServerVersionInfo(); - serverVersion = serverVersionInfo.getVersionNo(); - String serverScm = serverVersionInfo.getScmDescribe(); - log.info("client API version: {}, server API version: {}", - clientVersion, serverVersion); - warnMismatchAPIVersion(clientScm, serverScm); - } - - public VersionInfo getServerVersionInfo() { - IVersionResource iversion = createIVersionResource(); - ClientResponse versionResp; - try { - versionResp = iversion.get(); - } catch (ResteasyIOException e) { - Throwable rootCause = Throwables.getRootCause(e); - if (rootCause instanceof ConnectException) { - throw new RuntimeException("Can not connect to the server [" + crf.getBase() + "]. Please check server is up."); - } else { - throw e; - } - } - ClientUtility.checkResult(versionResp); - return versionResp.getEntity(); - } - - private void warnMismatchAPIVersion(String clientScm, String serverScm) { - if (!serverVersion.equals(clientVersion)) { - log.warn("client API version is {}, but server API version is {}", - clientVersion, serverVersion); - } else if (serverVersion.contains(RestConstant.SNAPSHOT_VERSION) - && !serverScm.equalsIgnoreCase(clientScm)) { - log.warn( - "client API SCM id is {}, but server API SCM id is {}", - clientScm, serverScm); - } - } - - private static ClientExecutor createClientExecutor(boolean sslCertDisabled) { - try { - final SSLContext sslContext = SSLContext.getInstance("TLS"); - - // Create a trust manager that does not validate certificate chains - // against our server - final TrustManager[] trustAllCerts; - if (sslCertDisabled) { - trustAllCerts = - new TrustManager[]{ new AcceptAllX509TrustManager() }; - } else { - trustAllCerts = null; - } - - sslContext.init(null, trustAllCerts, new SecureRandom()); - - // NB: This factory is a workaround to enable SNI with - // httpcomponents-client 4.2; not needed for 4.3 - SSLSocketFactory factory; - if (sslCertDisabled) { - // avoid triggering the problem described here: - // https://stackoverflow.com/questions/7615645/ssl-handshake-alert-unrecognized-name-error-since-upgrade-to-java-1-7-0 - factory = new SSLSocketFactory(sslContext); - } else { - factory = new SSLSocketFactory(sslContext) { - @Override - public Socket connectSocket(Socket socket, - InetSocketAddress remoteAddress, - InetSocketAddress localAddress, - HttpParams params) - throws IOException, UnknownHostException, - ConnectTimeoutException { - if (socket instanceof SSLSocket) { - try { - PropertyUtils.setProperty(socket, "host", - remoteAddress.getHostName()); - } catch (Exception ex) { - log.warn( - "Unable to enable SNI; you may have trouble connecting to some secure hosts. Please ensure that you are running Java 1.7 or later."); - } - } - return super.connectSocket(socket, remoteAddress, - localAddress, params); - } - }; - } - - HttpClient client = new DefaultHttpClient(); - - if (sslCertDisabled) { - X509HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; - factory.setHostnameVerifier(hostnameVerifier); - } - - ClientConnectionManager manager = client.getConnectionManager(); - manager.getSchemeRegistry().register( - new Scheme("https", 443, factory)); - return new ApacheHttpClient4Executor(client); - - } catch (Exception e) { - log.warn("error creating SSL client", e); - } - return null; - } - - /** - * Returns the Base url to be used for rest Requests. - */ - private URL getBaseUrl() { - try { - return new URL(fixBase(crf.getBase()).toString() + getUrlPrefix()); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } - } - - private URI getBaseUri() { - try { - return getBaseUrl().toURI(); - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } - } - - protected String getUrlPrefix() { - return "rest/"; - } - - public T createProxy(Class clazz, URI baseUri) { - log.debug("{} proxy uri: {}", clazz.getSimpleName(), baseUri); - T proxy = crf.createProxy(clazz, baseUri); - // CacheFactory.makeCacheable(proxy); - return proxy; - } - - /** - * Returns a client proxy, provided all information is on the proxied - * interface. (i.e. The interface is marked with a {@link javax.ws.rs.Path} - * annotation.) - * - * @param clazz - * Client interface to proxy. - * @return Client proxy for the class. - * @see {@link ZanataProxyFactory#createProxy(Class, java.net.URI)} - */ - public T createProxy(Class clazz) { - return createProxy(clazz, getBaseUri()); - } - - private static URI fixBase(URI base) { - if (base != null) { - String baseString = base.toString(); - if (!baseString.endsWith("/")) { - try { - URI result = new URI(baseString + "/"); - log.warn("Appending '/' to base URL '{}': using '{}'", - baseString, result); - return result; - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } - } - } - return base; - } - - public IGlossaryResource getGlossaryResource() { - return createProxy(IGlossaryResource.class); - } - - public IAccountResource getAccount(String username) { - return createProxy(IAccountResource.class, getAccountURI(username)); - } - - public URI getAccountURI(String username) { - try { - URL url = new URL(getBaseUrl(), "accounts/u/" + username); - return url.toURI(); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } - } - - public IProjectResource getProject(String proj) { - return createProxy(IProjectResource.class, getProjectURI(proj)); - } - - public URI getProjectURI(String proj) { - try { - URL url = new URL(getBaseUrl(), "projects/p/" + proj); - return url.toURI(); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } - } - - public IProjectIterationResource getProjectIteration(String proj, - String iter) { - return createProxy(IProjectIterationResource.class, - getProjectIterationURI(proj, iter)); - } - - public URI getProjectIterationURI(String proj, String iter) { - try { - URL url = - new URL(getBaseUrl(), "projects/p/" + proj - + "/iterations/i/" + iter); - return url.toURI(); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } - } - - // NB IProjectsResource is not currently used in Java - public IProjectsResource getProjectsResource() { - return createProxy(IProjectsResource.class); - } - - public ITranslatedDocResource getTranslatedDocResource(String projectSlug, - String versionSlug) { - return createProxy(ITranslatedDocResource.class, - getResourceURI(projectSlug, versionSlug)); - } - - public ISourceDocResource getSourceDocResource(String projectSlug, - String versionSlug) { - return createProxy(ISourceDocResource.class, - getResourceURI(projectSlug, versionSlug)); - } - - public IFileResource getFileResource() { - return createProxy(IFileResource.class); - } - - public IStatisticsResource getStatisticsResource() { - return createProxy(IStatisticsResource.class); - } - - public ICopyTransResource getCopyTransResource() { - return createProxy(ICopyTransResource.class); - } - - public IAsynchronousProcessResource getAsynchronousProcessResource() { - return createProxy(IAsynchronousProcessResource.class); - } - - public URI getResourceURI(String projectSlug, String versionSlug) { - String spec = - "projects/p/" + projectSlug + "/iterations/i/" + versionSlug - + "/r"; - try { - return new URL(getBaseUrl(), spec).toURI(); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } catch (URISyntaxException e) { - String msg = - "URI Syntax error. Please make sure your project (project ID) and version are correct."; - log.error(msg); - log.error("part of your url: {}", spec); - throw new RuntimeException(msg); - } - } - - /** - * @see org.jboss.resteasy.client.core.ClientInterceptorRepositoryImpl#registerInterceptor(Object) - * @param interceptor - */ - public void registerPrefixInterceptor(Object interceptor) { - ClientInterceptorRepository repo = getPrefixInterceptors(); - repo.registerInterceptor(interceptor); - } - - /** - * Workaround for signature incompatibility between RESTEasy 2.x and 3.x - * @return - */ - private ClientInterceptorRepository getPrefixInterceptors() { - try { - Method m = crf.getClass().getMethod("getPrefixInterceptors"); - return (ClientInterceptorRepository) m.invoke(crf); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - protected IVersionResource createIVersionResource() { - return createProxy(IVersionResource.class, getBaseUri()); - } - - /** - * Compares a given version identifier with the server version. - * - * @param version - * The version to against which to compare the server version. - * @return A positive integer if the server version is greater than the - * given version. A negative integer if the server version is less - * than the given version. 0 if both versions are the same. - */ - public int compareToServerVersion(String version) { - DefaultArtifactVersion srvVersion = - new DefaultArtifactVersion(serverVersion); - DefaultArtifactVersion providedVersion = - new DefaultArtifactVersion(version); - - return srvVersion.compareTo(providedVersion); - } - - private static class AcceptAllX509TrustManager implements X509TrustManager { - public X509Certificate[] getAcceptedIssuers() { - return null; - } - - public void - checkClientTrusted(X509Certificate[] certs, String authType) - throws CertificateException { - } - - public void - checkServerTrusted(X509Certificate[] certs, String authType) - throws CertificateException { - } - } -} diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/FileResourceClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/FileResourceClientTest.java index bcf208ec..557372fe 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/FileResourceClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/FileResourceClientTest.java @@ -75,8 +75,6 @@ public void testServerAcceptedType() { } @Test -// @Ignore -// @ManualTest("I can't create a Jersey server endpoint that can parse multipart form data embedded in DocumentFileUploadForm") public void testSourceFileUpload() throws Exception { // client = clientTalkingToRealServer(); @@ -149,7 +147,7 @@ private String calculateFileHash(File srcFile) { public void testDownloadSourceFile() throws IOException { InputStream inputStream = client.downloadSourceFile("about-fedora", "master", "pot", - "About-Fedora"); + "About-Fedora").getEntity(InputStream.class); PoReader2 reader = new PoReader2(); Resource resource = reader.extractTemplate(new InputSource(inputStream), @@ -161,7 +159,7 @@ public void testDownloadSourceFile() throws IOException { public void testDownloadTranslationFile() { InputStream inputStream = client.downloadTranslationFile("about-fedora", "master", "es", - "po", "About-Fedora"); + "po", "About-Fedora").getEntity(InputStream.class); PoReader2 reader = new PoReader2(); TranslationsResource translationsResource = reader.extractTarget(new InputSource(inputStream)); diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/TransDocResourceClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/TransDocResourceClientTest.java index d59bb3fa..ac43cbcc 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/TransDocResourceClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/TransDocResourceClientTest.java @@ -50,7 +50,8 @@ public void setUp() { public void testGetTranslations() { TranslationsResource translations = client.getTranslations("test", LocaleId.DE, - Sets.newHashSet("gettext", "comment"), true, "abc"); + Sets.newHashSet("gettext", "comment"), true, "abc") + .getEntity(TranslationsResource.class); assertThat(translations.getTextFlowTargets(), Matchers.hasSize(1)); } From 8eb617005432e6a7ecf7f3693919e7ff2e68055d Mon Sep 17 00:00:00 2001 From: Patrick Huang Date: Mon, 1 Dec 2014 15:15:35 +1000 Subject: [PATCH 09/55] rhbz1124630 - fix according review comments --- mock-server/pom.xml | 12 ++- pom.xml | 3 +- .../client/commands/ListRemoteCommand.java | 4 +- .../delete/GlossaryDeleteCommand.java | 9 +- zanata-rest-client/pom.xml | 8 +- .../rest/client/ApiKeyHeaderFilter.java | 7 ++ .../zanata/rest/client/AccountClientTest.java | 3 +- .../client/ApiKeyHeaderDecoratorTest.java | 69 --------------- .../rest/client/ApiKeyHeaderFilterTest.java | 83 +++++++++++++++++++ .../rest/client/AsyncProcessClientTest.java | 3 +- .../rest/client/CopyTransClientTest.java | 3 +- .../rest/client/FileResourceClientTest.java | 3 +- .../rest/client/GlossaryClientTest.java | 3 +- .../zanata/rest/client/ProjectClientTest.java | 3 +- .../client/ProjectIterationClientTest.java | 3 +- .../rest/client/ProjectsClientTest.java | 3 +- .../rest/client/RestClientFactoryTest.java | 3 +- .../client/SourceDocResourceClientTest.java | 3 +- .../client/StatisticsResourceClientTest.java | 3 +- .../client/TransDocResourceClientTest.java | 3 +- 20 files changed, 140 insertions(+), 91 deletions(-) delete mode 100644 zanata-rest-client/src/test/java/org/zanata/rest/client/ApiKeyHeaderDecoratorTest.java create mode 100644 zanata-rest-client/src/test/java/org/zanata/rest/client/ApiKeyHeaderFilterTest.java diff --git a/mock-server/pom.xml b/mock-server/pom.xml index 7d14d182..e2248680 100644 --- a/mock-server/pom.xml +++ b/mock-server/pom.xml @@ -152,12 +152,20 @@ com.ning.maven.plugins maven-duplicate-finder-plugin - 1.0.7 - + + + + + about.html + + + true + + diff --git a/pom.xml b/pom.xml index c052562f..2c4d7ccf 100644 --- a/pom.xml +++ b/pom.xml @@ -225,4 +225,5 @@ zanata-maven-plugin zanata-rest-client - \ No newline at end of file + + diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/ListRemoteCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/ListRemoteCommand.java index 9f7a9f9f..059294e1 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/ListRemoteCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/ListRemoteCommand.java @@ -50,10 +50,10 @@ public void run() throws Exception { getOpts().getProj(), getOpts().getProjectVersion()); List list = client.getResourceMeta(null); - ConsoleInteractor console = new ConsoleInteractorImpl(); for (ResourceMeta doc : list) { - console.printfln(doc.getName()); + System.out.println(doc.getName()); } } } + diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/glossary/delete/GlossaryDeleteCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/glossary/delete/GlossaryDeleteCommand.java index 77acdf91..da6c98e6 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/glossary/delete/GlossaryDeleteCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/glossary/delete/GlossaryDeleteCommand.java @@ -39,12 +39,12 @@ public class GlossaryDeleteCommand extends ConfigurableCommand { private static final Logger log = LoggerFactory .getLogger(GlossaryDeleteCommand.class); - private final GlossaryClient client; + private final GlossaryClient glossaryClient; public GlossaryDeleteCommand(GlossaryDeleteOptions opts, RestClientFactory clientFactory) { super(opts, clientFactory); - client = getClientFactory().getGlossaryClient(); + glossaryClient = getClientFactory().getGlossaryClient(); } public GlossaryDeleteCommand(GlossaryDeleteOptions opts) { @@ -59,12 +59,13 @@ public void run() throws Exception { log.info("Delete entire glossary?: {}", getOpts().getAllGlossary()); if (getOpts().getAllGlossary()) { - client.deleteAll(); + glossaryClient.deleteAll(); } else if (!StringUtils.isEmpty(getOpts().getlang())) { - client.delete(new LocaleId(getOpts() + glossaryClient.delete(new LocaleId(getOpts() .getlang())); } else { throw new RuntimeException("Option 'zanata.lang' is required."); } } } + diff --git a/zanata-rest-client/pom.xml b/zanata-rest-client/pom.xml index 3919d9a7..f851da1c 100644 --- a/zanata-rest-client/pom.xml +++ b/zanata-rest-client/pom.xml @@ -133,6 +133,12 @@ guava + + org.mockito + mockito-core + test + + @@ -140,7 +146,6 @@ com.ning.maven.plugins maven-duplicate-finder-plugin - 1.0.7 false @@ -149,3 +154,4 @@ + diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/ApiKeyHeaderFilter.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ApiKeyHeaderFilter.java index 9be0d28e..77c67af4 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/ApiKeyHeaderFilter.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/ApiKeyHeaderFilter.java @@ -26,6 +26,7 @@ import org.zanata.rest.RestConstant; +import com.google.common.annotations.VisibleForTesting; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.ClientRequest; import com.sun.jersey.api.client.ClientResponse; @@ -50,6 +51,11 @@ public ClientResponse handle(ClientRequest cr) headers.add(RestConstant.HEADER_USERNAME, username); headers.add(RestConstant.HEADER_API_KEY, apiKey); headers.add(RestConstant.HEADER_VERSION_NO, ver); + return handleNext(cr); + } + + @VisibleForTesting + protected ClientResponse handleNext(ClientRequest cr) { return getNext().handle(cr); } @@ -61,3 +67,4 @@ public void setUsername(String username) { this.username = username; } } + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/AccountClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/AccountClientTest.java index 7f9a8d67..5df88a9a 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/AccountClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/AccountClientTest.java @@ -55,4 +55,5 @@ public void testPut() throws Exception { MockServerTestUtil.verifyServerRespondSuccessStatus(); } -} \ No newline at end of file +} + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/ApiKeyHeaderDecoratorTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/ApiKeyHeaderDecoratorTest.java deleted file mode 100644 index 9d19af15..00000000 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/ApiKeyHeaderDecoratorTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2011, Red Hat, Inc. and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.zanata.rest.client; - -import javax.ws.rs.core.MultivaluedMap; - -import org.jboss.resteasy.client.ClientRequest; -import org.jboss.resteasy.client.ClientResponse; -import org.jboss.resteasy.spi.interception.ClientExecutionContext; -import org.junit.Test; -import org.zanata.rest.RestConstant; - -import static org.junit.Assert.assertEquals; - -/** - * @author Sean Flanigan sflaniga@redhat.com - * - */ -public class ApiKeyHeaderDecoratorTest { - @Test - public void testHeaders() throws Exception { -// String username = "username"; -// String apiKey = "apiKey"; -// String ver = "ver"; -// ApiKeyHeaderDecorator decorator = -// new ApiKeyHeaderDecorator(username, apiKey, ver); -// -// final ClientRequest mockRequest = -// new ClientRequest("http://uri.example.com/"); -// ClientExecutionContext mockCtx = new ClientExecutionContext() { -// -// @SuppressWarnings("rawtypes") -// @Override -// public ClientResponse proceed() throws Exception { -// return null; -// } -// -// @Override -// public ClientRequest getRequest() { -// return mockRequest; -// } -// }; -// decorator.execute(mockCtx); -// MultivaluedMap headers = mockRequest.getHeaders(); -// assertEquals(username, headers.getFirst(RestConstant.HEADER_USERNAME)); -// assertEquals(apiKey, headers.getFirst(RestConstant.HEADER_API_KEY)); -// assertEquals(ver, headers.getFirst(RestConstant.HEADER_VERSION_NO)); - } -} diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/ApiKeyHeaderFilterTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/ApiKeyHeaderFilterTest.java new file mode 100644 index 00000000..8a3fc60a --- /dev/null +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/ApiKeyHeaderFilterTest.java @@ -0,0 +1,83 @@ +/* + * Copyright 2011, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.Mockito.when; + +import javax.ws.rs.core.MultivaluedHashMap; + +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.zanata.rest.RestConstant; +import com.sun.jersey.api.client.ClientRequest; +import com.sun.jersey.api.client.ClientResponse; + +/** + * @author Sean Flanigan sflaniga@redhat.com + * + */ +public class ApiKeyHeaderFilterTest { + @Mock + private ClientRequest mockRequest; + @Mock + private ClientResponse response; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testHeaders() throws Exception { + String username = "username"; + String apiKey = "apiKey"; + String ver = "ver"; + ApiKeyHeaderFilter filter = + new ApiKeyHeaderFilter(username, apiKey, ver) { + @Override + protected ClientResponse handleNext( + ClientRequest cr) { + return response; + } + }; + + MultivaluedHashMap headerMap = + new MultivaluedHashMap<>(); + when(mockRequest.getHeaders()).thenReturn(headerMap); + // + + filter.handle(mockRequest); + + assertThat(headerMap.getFirst(RestConstant.HEADER_USERNAME).toString(), + Matchers.equalTo(username)); + assertThat(headerMap.getFirst(RestConstant.HEADER_API_KEY).toString(), + Matchers.equalTo(apiKey)); + assertThat(headerMap.getFirst(RestConstant.HEADER_VERSION_NO) + .toString(), Matchers.equalTo(ver)); + } +} + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/AsyncProcessClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/AsyncProcessClientTest.java index c6d34499..287396f6 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/AsyncProcessClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/AsyncProcessClientTest.java @@ -79,4 +79,5 @@ public void testGetProcessStatus() throws Exception { assertThat(processStatus.getStatusCode(), Matchers.equalTo( ProcessStatus.ProcessStatusCode.Finished)); } -} \ No newline at end of file +} + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/CopyTransClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/CopyTransClientTest.java index 698d63c8..7da743ee 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/CopyTransClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/CopyTransClientTest.java @@ -54,4 +54,5 @@ public void testGetCopyTransStatus() throws Exception { client.getCopyTransStatus("about-fedora", "master", "Authors"); assertThat(copyTransStatus.isInProgress(), Matchers.is(false)); } -} \ No newline at end of file +} + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/FileResourceClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/FileResourceClientTest.java index 557372fe..cc7be9d4 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/FileResourceClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/FileResourceClientTest.java @@ -167,4 +167,5 @@ public void testDownloadTranslationFile() { Matchers.hasSize(1)); } -} \ No newline at end of file +} + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/GlossaryClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/GlossaryClientTest.java index ff80ac6b..3cbc6c06 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/GlossaryClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/GlossaryClientTest.java @@ -57,4 +57,5 @@ public void testDeleteAll() throws Exception { client.deleteAll(); MockServerTestUtil.verifyServerRespondSuccessStatus(); } -} \ No newline at end of file +} + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectClientTest.java index 39f9a5c9..b7cc56fb 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectClientTest.java @@ -56,4 +56,5 @@ public void testPut() throws Exception { MockServerTestUtil.verifyServerRespondSuccessStatus(); } -} \ No newline at end of file +} + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectIterationClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectIterationClientTest.java index d894aebe..88d86798 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectIterationClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectIterationClientTest.java @@ -61,4 +61,5 @@ public void testSampleConfig() { assertThat(config, Matchers.containsString("")); } -} \ No newline at end of file +} + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectsClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectsClientTest.java index 34ea513f..74fa26e4 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectsClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectsClientTest.java @@ -49,4 +49,5 @@ public void canGetProjects() { assertThat(projects[0].getId(), Matchers.equalTo("about-fedora")); } -} \ No newline at end of file +} + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/RestClientFactoryTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/RestClientFactoryTest.java index a98d7839..b4082bef 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/RestClientFactoryTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/RestClientFactoryTest.java @@ -43,4 +43,5 @@ public void testGetVersion() { Matchers.equalTo("3.6.0-SNAPSHOT")); } -} \ No newline at end of file +} + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/SourceDocResourceClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/SourceDocResourceClientTest.java index 40007e08..c0f945fb 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/SourceDocResourceClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/SourceDocResourceClientTest.java @@ -76,4 +76,5 @@ public void testDeleteResource() { String result = client.deleteResource("test"); assertThat(result, Matchers.isEmptyOrNullString()); } -} \ No newline at end of file +} + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/StatisticsResourceClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/StatisticsResourceClientTest.java index c28478b8..d437639e 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/StatisticsResourceClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/StatisticsResourceClientTest.java @@ -75,4 +75,5 @@ public void testGetContributorStatistics() { assertThat(statistics, Matchers.hasKey("pahuang")); } -} \ No newline at end of file +} + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/TransDocResourceClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/TransDocResourceClientTest.java index ac43cbcc..91c31df3 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/TransDocResourceClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/TransDocResourceClientTest.java @@ -56,4 +56,5 @@ public void testGetTranslations() { assertThat(translations.getTextFlowTargets(), Matchers.hasSize(1)); } -} \ No newline at end of file +} + From 9c6ea3e91de9d96b23f285d35840ecf60c60d104 Mon Sep 17 00:00:00 2001 From: Patrick Huang Date: Mon, 1 Dec 2014 15:27:50 +1000 Subject: [PATCH 10/55] rhbz1124630 - rename mock-server module to stub-server --- pom.xml | 3 ++- {mock-server => stub-server}/pom.xml | 5 +++-- .../org/zanata/rest/service/MockAccountResource.java | 1 + .../rest/service/MockAsynchronousProcessResource.java | 1 + .../org/zanata/rest/service/MockCopyTransResource.java | 1 + .../java/org/zanata/rest/service/MockFileResource.java | 1 + .../org/zanata/rest/service/MockGlossaryResource.java | 1 + .../rest/service/MockProjectIterationResource.java | 1 + .../org/zanata/rest/service/MockProjectResource.java | 1 + .../org/zanata/rest/service/MockProjectsResource.java | 1 + .../java/org/zanata/rest/service/MockResourceUtil.java | 1 + .../zanata/rest/service/MockResourcesApplication.java | 1 + .../org/zanata/rest/service/MockSourceDocResource.java | 1 + .../org/zanata/rest/service/MockStatisticsResource.java | 1 + .../zanata/rest/service/MockTranslatedDocResource.java | 1 + .../org/zanata/rest/service/MockVersionResource.java | 1 + .../java/org/zanata/rest/service/StubbingServerRule.java | 5 +++-- zanata-rest-client/pom.xml | 5 +++-- .../java/org/zanata/rest/client/AccountClientTest.java | 8 +++++--- .../org/zanata/rest/client/AsyncProcessClientTest.java | 8 +++++--- .../java/org/zanata/rest/client/CopyTransClientTest.java | 8 +++++--- .../org/zanata/rest/client/FileResourceClientTest.java | 8 +++++--- .../java/org/zanata/rest/client/GlossaryClientTest.java | 8 +++++--- .../java/org/zanata/rest/client/ProjectClientTest.java | 8 +++++--- .../zanata/rest/client/ProjectIterationClientTest.java | 8 +++++--- .../java/org/zanata/rest/client/ProjectsClientTest.java | 8 +++++--- .../org/zanata/rest/client/RestClientFactoryTest.java | 7 ++++--- .../zanata/rest/client/SourceDocResourceClientTest.java | 9 ++++++--- .../zanata/rest/client/StatisticsResourceClientTest.java | 9 ++++++--- .../zanata/rest/client/TransDocResourceClientTest.java | 8 +++++--- 30 files changed, 86 insertions(+), 43 deletions(-) rename {mock-server => stub-server}/pom.xml (98%) rename {mock-server => stub-server}/src/main/java/org/zanata/rest/service/MockAccountResource.java (99%) rename {mock-server => stub-server}/src/main/java/org/zanata/rest/service/MockAsynchronousProcessResource.java (99%) rename {mock-server => stub-server}/src/main/java/org/zanata/rest/service/MockCopyTransResource.java (99%) rename {mock-server => stub-server}/src/main/java/org/zanata/rest/service/MockFileResource.java (99%) rename {mock-server => stub-server}/src/main/java/org/zanata/rest/service/MockGlossaryResource.java (99%) rename {mock-server => stub-server}/src/main/java/org/zanata/rest/service/MockProjectIterationResource.java (99%) rename {mock-server => stub-server}/src/main/java/org/zanata/rest/service/MockProjectResource.java (99%) rename {mock-server => stub-server}/src/main/java/org/zanata/rest/service/MockProjectsResource.java (99%) rename {mock-server => stub-server}/src/main/java/org/zanata/rest/service/MockResourceUtil.java (99%) rename {mock-server => stub-server}/src/main/java/org/zanata/rest/service/MockResourcesApplication.java (99%) rename {mock-server => stub-server}/src/main/java/org/zanata/rest/service/MockSourceDocResource.java (99%) rename {mock-server => stub-server}/src/main/java/org/zanata/rest/service/MockStatisticsResource.java (99%) rename {mock-server => stub-server}/src/main/java/org/zanata/rest/service/MockTranslatedDocResource.java (99%) rename {mock-server => stub-server}/src/main/java/org/zanata/rest/service/MockVersionResource.java (99%) rename mock-server/src/main/java/org/zanata/rest/service/MockServerRule.java => stub-server/src/main/java/org/zanata/rest/service/StubbingServerRule.java (96%) diff --git a/pom.xml b/pom.xml index 2c4d7ccf..41deda4d 100644 --- a/pom.xml +++ b/pom.xml @@ -219,7 +219,7 @@ - mock-server + stub-server zanata-cli zanata-client-commands zanata-maven-plugin @@ -227,3 +227,4 @@ + diff --git a/mock-server/pom.xml b/stub-server/pom.xml similarity index 98% rename from mock-server/pom.xml rename to stub-server/pom.xml index e2248680..3d054d53 100644 --- a/mock-server/pom.xml +++ b/stub-server/pom.xml @@ -9,8 +9,8 @@ client 3.6.0-SNAPSHOT - mock-server - mock-server + stub-server + stub-server @@ -169,3 +169,4 @@ + diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockAccountResource.java b/stub-server/src/main/java/org/zanata/rest/service/MockAccountResource.java similarity index 99% rename from mock-server/src/main/java/org/zanata/rest/service/MockAccountResource.java rename to stub-server/src/main/java/org/zanata/rest/service/MockAccountResource.java index c8089cd1..74ea22b6 100644 --- a/mock-server/src/main/java/org/zanata/rest/service/MockAccountResource.java +++ b/stub-server/src/main/java/org/zanata/rest/service/MockAccountResource.java @@ -50,3 +50,4 @@ public Response put(Account account) { return Response.created(uriInfo.getRequestUri()).build(); } } + diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockAsynchronousProcessResource.java b/stub-server/src/main/java/org/zanata/rest/service/MockAsynchronousProcessResource.java similarity index 99% rename from mock-server/src/main/java/org/zanata/rest/service/MockAsynchronousProcessResource.java rename to stub-server/src/main/java/org/zanata/rest/service/MockAsynchronousProcessResource.java index 1b014096..197e7763 100644 --- a/mock-server/src/main/java/org/zanata/rest/service/MockAsynchronousProcessResource.java +++ b/stub-server/src/main/java/org/zanata/rest/service/MockAsynchronousProcessResource.java @@ -76,3 +76,4 @@ public ProcessStatus getProcessStatus(String processId) { return processStatus; } } + diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockCopyTransResource.java b/stub-server/src/main/java/org/zanata/rest/service/MockCopyTransResource.java similarity index 99% rename from mock-server/src/main/java/org/zanata/rest/service/MockCopyTransResource.java rename to stub-server/src/main/java/org/zanata/rest/service/MockCopyTransResource.java index 87a68b4e..965cac0a 100644 --- a/mock-server/src/main/java/org/zanata/rest/service/MockCopyTransResource.java +++ b/stub-server/src/main/java/org/zanata/rest/service/MockCopyTransResource.java @@ -49,3 +49,4 @@ public CopyTransStatus getCopyTransStatus(String projectSlug, return copyTransStatus; } } + diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockFileResource.java b/stub-server/src/main/java/org/zanata/rest/service/MockFileResource.java similarity index 99% rename from mock-server/src/main/java/org/zanata/rest/service/MockFileResource.java rename to stub-server/src/main/java/org/zanata/rest/service/MockFileResource.java index 78be7b1d..0ce64ded 100644 --- a/mock-server/src/main/java/org/zanata/rest/service/MockFileResource.java +++ b/stub-server/src/main/java/org/zanata/rest/service/MockFileResource.java @@ -157,3 +157,4 @@ public void write(OutputStream output) .entity(output).build(); } } + diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockGlossaryResource.java b/stub-server/src/main/java/org/zanata/rest/service/MockGlossaryResource.java similarity index 99% rename from mock-server/src/main/java/org/zanata/rest/service/MockGlossaryResource.java rename to stub-server/src/main/java/org/zanata/rest/service/MockGlossaryResource.java index d281fc6f..dfae97bd 100644 --- a/mock-server/src/main/java/org/zanata/rest/service/MockGlossaryResource.java +++ b/stub-server/src/main/java/org/zanata/rest/service/MockGlossaryResource.java @@ -63,3 +63,4 @@ public Response deleteGlossaries() { return Response.ok().build(); } } + diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockProjectIterationResource.java b/stub-server/src/main/java/org/zanata/rest/service/MockProjectIterationResource.java similarity index 99% rename from mock-server/src/main/java/org/zanata/rest/service/MockProjectIterationResource.java rename to stub-server/src/main/java/org/zanata/rest/service/MockProjectIterationResource.java index c4db4cd2..ff16612e 100644 --- a/mock-server/src/main/java/org/zanata/rest/service/MockProjectIterationResource.java +++ b/stub-server/src/main/java/org/zanata/rest/service/MockProjectIterationResource.java @@ -68,3 +68,4 @@ public Response sampleConfiguration() { return Response.ok(config, MediaType.TEXT_PLAIN_TYPE).build(); } } + diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockProjectResource.java b/stub-server/src/main/java/org/zanata/rest/service/MockProjectResource.java similarity index 99% rename from mock-server/src/main/java/org/zanata/rest/service/MockProjectResource.java rename to stub-server/src/main/java/org/zanata/rest/service/MockProjectResource.java index d7198684..4ee00f04 100644 --- a/mock-server/src/main/java/org/zanata/rest/service/MockProjectResource.java +++ b/stub-server/src/main/java/org/zanata/rest/service/MockProjectResource.java @@ -54,3 +54,4 @@ public Response put(Project project) { return Response.created(uriInfo.getRequestUri()).build(); } } + diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockProjectsResource.java b/stub-server/src/main/java/org/zanata/rest/service/MockProjectsResource.java similarity index 99% rename from mock-server/src/main/java/org/zanata/rest/service/MockProjectsResource.java rename to stub-server/src/main/java/org/zanata/rest/service/MockProjectsResource.java index d23cfefc..f911eed1 100644 --- a/mock-server/src/main/java/org/zanata/rest/service/MockProjectsResource.java +++ b/stub-server/src/main/java/org/zanata/rest/service/MockProjectsResource.java @@ -49,3 +49,4 @@ public Response get() { return Response.ok(genericEntity).build(); } } + diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockResourceUtil.java b/stub-server/src/main/java/org/zanata/rest/service/MockResourceUtil.java similarity index 99% rename from mock-server/src/main/java/org/zanata/rest/service/MockResourceUtil.java rename to stub-server/src/main/java/org/zanata/rest/service/MockResourceUtil.java index 78cfca37..4960825a 100644 --- a/mock-server/src/main/java/org/zanata/rest/service/MockResourceUtil.java +++ b/stub-server/src/main/java/org/zanata/rest/service/MockResourceUtil.java @@ -44,3 +44,4 @@ static T notUsedByClient() { } + diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockResourcesApplication.java b/stub-server/src/main/java/org/zanata/rest/service/MockResourcesApplication.java similarity index 99% rename from mock-server/src/main/java/org/zanata/rest/service/MockResourcesApplication.java rename to stub-server/src/main/java/org/zanata/rest/service/MockResourcesApplication.java index 3c56f80d..cdb63d31 100644 --- a/mock-server/src/main/java/org/zanata/rest/service/MockResourcesApplication.java +++ b/stub-server/src/main/java/org/zanata/rest/service/MockResourcesApplication.java @@ -52,3 +52,4 @@ public Set> getClasses() { return services; } } + diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockSourceDocResource.java b/stub-server/src/main/java/org/zanata/rest/service/MockSourceDocResource.java similarity index 99% rename from mock-server/src/main/java/org/zanata/rest/service/MockSourceDocResource.java rename to stub-server/src/main/java/org/zanata/rest/service/MockSourceDocResource.java index c0563c5e..e4f9b807 100644 --- a/mock-server/src/main/java/org/zanata/rest/service/MockSourceDocResource.java +++ b/stub-server/src/main/java/org/zanata/rest/service/MockSourceDocResource.java @@ -91,3 +91,4 @@ public Response putResourceMeta(String idNoSlash, ResourceMeta resourceMeta, return MockResourceUtil.notUsedByClient(); } } + diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockStatisticsResource.java b/stub-server/src/main/java/org/zanata/rest/service/MockStatisticsResource.java similarity index 99% rename from mock-server/src/main/java/org/zanata/rest/service/MockStatisticsResource.java rename to stub-server/src/main/java/org/zanata/rest/service/MockStatisticsResource.java index 89bd18a5..f6de9387 100644 --- a/mock-server/src/main/java/org/zanata/rest/service/MockStatisticsResource.java +++ b/stub-server/src/main/java/org/zanata/rest/service/MockStatisticsResource.java @@ -79,3 +79,4 @@ public ContributionStatistics getContributionStatistics(String projectSlug, return contributionStatistics; } } + diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockTranslatedDocResource.java b/stub-server/src/main/java/org/zanata/rest/service/MockTranslatedDocResource.java similarity index 99% rename from mock-server/src/main/java/org/zanata/rest/service/MockTranslatedDocResource.java rename to stub-server/src/main/java/org/zanata/rest/service/MockTranslatedDocResource.java index 7a4d3e47..a3de7f45 100644 --- a/mock-server/src/main/java/org/zanata/rest/service/MockTranslatedDocResource.java +++ b/stub-server/src/main/java/org/zanata/rest/service/MockTranslatedDocResource.java @@ -62,3 +62,4 @@ public Response putTranslations(String idNoSlash, LocaleId locale, return Response.ok().build(); } } + diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockVersionResource.java b/stub-server/src/main/java/org/zanata/rest/service/MockVersionResource.java similarity index 99% rename from mock-server/src/main/java/org/zanata/rest/service/MockVersionResource.java rename to stub-server/src/main/java/org/zanata/rest/service/MockVersionResource.java index 2d3d518d..27791933 100644 --- a/mock-server/src/main/java/org/zanata/rest/service/MockVersionResource.java +++ b/stub-server/src/main/java/org/zanata/rest/service/MockVersionResource.java @@ -42,3 +42,4 @@ public Response get() { .build(); } } + diff --git a/mock-server/src/main/java/org/zanata/rest/service/MockServerRule.java b/stub-server/src/main/java/org/zanata/rest/service/StubbingServerRule.java similarity index 96% rename from mock-server/src/main/java/org/zanata/rest/service/MockServerRule.java rename to stub-server/src/main/java/org/zanata/rest/service/StubbingServerRule.java index 05d030c4..5179b1fc 100644 --- a/mock-server/src/main/java/org/zanata/rest/service/MockServerRule.java +++ b/stub-server/src/main/java/org/zanata/rest/service/StubbingServerRule.java @@ -40,10 +40,10 @@ * @author Patrick Huang pahuang@redhat.com */ -public class MockServerRule implements TestRule { +public class StubbingServerRule implements TestRule { private static Server server; - public MockServerRule() { + public StubbingServerRule() { startServerIfRequired(); } @@ -78,3 +78,4 @@ public URI getServerBaseUri() { return server.getURI(); } } + diff --git a/zanata-rest-client/pom.xml b/zanata-rest-client/pom.xml index f851da1c..4cd18ffe 100644 --- a/zanata-rest-client/pom.xml +++ b/zanata-rest-client/pom.xml @@ -21,7 +21,7 @@ - + org.jboss.resteasy jaxrs-api test @@ -37,7 +37,7 @@ org.zanata - mock-server + stub-server ${project.version} test @@ -155,3 +155,4 @@ + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/AccountClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/AccountClientTest.java index 5df88a9a..b726c5f4 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/AccountClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/AccountClientTest.java @@ -26,19 +26,20 @@ import org.junit.ClassRule; import org.junit.Test; import org.zanata.rest.dto.Account; -import org.zanata.rest.service.MockServerRule; +import org.zanata.rest.service.StubbingServerRule; import static org.junit.Assert.*; public class AccountClientTest { @ClassRule - public static MockServerRule mockServerRule = new MockServerRule(); + public static StubbingServerRule + stubbingServerRule = new StubbingServerRule(); private AccountClient client; @Before public void setUp() throws Exception { client = new AccountClient(MockServerTestUtil - .createClientFactory(mockServerRule.getServerBaseUri())); + .createClientFactory(stubbingServerRule.getServerBaseUri())); } @@ -57,3 +58,4 @@ public void testPut() throws Exception { } } + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/AsyncProcessClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/AsyncProcessClientTest.java index 287396f6..71c0690a 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/AsyncProcessClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/AsyncProcessClientTest.java @@ -29,7 +29,7 @@ import org.zanata.rest.dto.ProcessStatus; import org.zanata.rest.dto.resource.Resource; import org.zanata.rest.dto.resource.TranslationsResource; -import org.zanata.rest.service.MockServerRule; +import org.zanata.rest.service.StubbingServerRule; import com.google.common.collect.Sets; @@ -37,13 +37,14 @@ public class AsyncProcessClientTest { @ClassRule - public static MockServerRule mockServerRule = new MockServerRule(); + public static StubbingServerRule + stubbingServerRule = new StubbingServerRule(); private AsyncProcessClient client; @Before public void setUp() throws Exception { client = new AsyncProcessClient(MockServerTestUtil - .createClientFactory(mockServerRule.getServerBaseUri())); + .createClientFactory(stubbingServerRule.getServerBaseUri())); } @Test @@ -81,3 +82,4 @@ public void testGetProcessStatus() throws Exception { } } + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/CopyTransClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/CopyTransClientTest.java index 7da743ee..183d3a50 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/CopyTransClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/CopyTransClientTest.java @@ -26,19 +26,20 @@ import org.junit.ClassRule; import org.junit.Test; import org.zanata.rest.dto.CopyTransStatus; -import org.zanata.rest.service.MockServerRule; +import org.zanata.rest.service.StubbingServerRule; import static org.junit.Assert.*; public class CopyTransClientTest { @ClassRule - public static MockServerRule mockServerRule = new MockServerRule(); + public static StubbingServerRule + stubbingServerRule = new StubbingServerRule(); private CopyTransClient client; @Before public void setUp() throws Exception { client = new CopyTransClient(MockServerTestUtil - .createClientFactory(mockServerRule.getServerBaseUri())); + .createClientFactory(stubbingServerRule.getServerBaseUri())); } @Test @@ -56,3 +57,4 @@ public void testGetCopyTransStatus() throws Exception { } } + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/FileResourceClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/FileResourceClientTest.java index cc7be9d4..b4d3cc6d 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/FileResourceClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/FileResourceClientTest.java @@ -45,7 +45,7 @@ import org.zanata.rest.dto.ChunkUploadResponse; import org.zanata.rest.dto.resource.Resource; import org.zanata.rest.dto.resource.TranslationsResource; -import org.zanata.rest.service.MockServerRule; +import org.zanata.rest.service.StubbingServerRule; import static org.junit.Assert.*; @@ -55,12 +55,13 @@ public class FileResourceClientTest { private FileResourceClient client; @ClassRule - public static MockServerRule mockServerRule = new MockServerRule(); + public static StubbingServerRule + stubbingServerRule = new StubbingServerRule(); @Before public void setUp() throws URISyntaxException { RestClientFactory restClientFactory = MockServerTestUtil - .createClientFactory(mockServerRule.getServerBaseUri()); + .createClientFactory(stubbingServerRule.getServerBaseUri()); client = new FileResourceClient(restClientFactory); } @@ -169,3 +170,4 @@ public void testDownloadTranslationFile() { } + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/GlossaryClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/GlossaryClientTest.java index 3cbc6c06..a7767ecc 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/GlossaryClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/GlossaryClientTest.java @@ -26,17 +26,18 @@ import org.junit.Test; import org.zanata.common.LocaleId; import org.zanata.rest.dto.Glossary; -import org.zanata.rest.service.MockServerRule; +import org.zanata.rest.service.StubbingServerRule; public class GlossaryClientTest { @ClassRule - public static MockServerRule mockServerRule = new MockServerRule(); + public static StubbingServerRule + stubbingServerRule = new StubbingServerRule(); private GlossaryClient client; @Before public void setUp() throws Exception { client = new GlossaryClient(MockServerTestUtil - .createClientFactory(mockServerRule.getServerBaseUri())); + .createClientFactory(stubbingServerRule.getServerBaseUri())); } @Test @@ -59,3 +60,4 @@ public void testDeleteAll() throws Exception { } } + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectClientTest.java index b7cc56fb..0a52d9b0 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectClientTest.java @@ -26,19 +26,20 @@ import org.junit.ClassRule; import org.junit.Test; import org.zanata.rest.dto.Project; -import org.zanata.rest.service.MockServerRule; +import org.zanata.rest.service.StubbingServerRule; import static org.junit.Assert.*; public class ProjectClientTest { @ClassRule - public static MockServerRule mockServerRule = new MockServerRule(); + public static StubbingServerRule + stubbingServerRule = new StubbingServerRule(); private ProjectClient client; @Before public void setUp() throws Exception { client = new ProjectClient(MockServerTestUtil - .createClientFactory(mockServerRule.getServerBaseUri()), + .createClientFactory(stubbingServerRule.getServerBaseUri()), "about-fedora"); } @@ -58,3 +59,4 @@ public void testPut() throws Exception { } + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectIterationClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectIterationClientTest.java index 88d86798..3538161d 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectIterationClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectIterationClientTest.java @@ -26,19 +26,20 @@ import org.junit.ClassRule; import org.junit.Test; import org.zanata.rest.dto.ProjectIteration; -import org.zanata.rest.service.MockServerRule; +import org.zanata.rest.service.StubbingServerRule; import static org.junit.Assert.*; public class ProjectIterationClientTest { @ClassRule - public static MockServerRule mockServerRule = new MockServerRule(); + public static StubbingServerRule + stubbingServerRule = new StubbingServerRule(); private ProjectIterationClient client; @Before public void setUp() throws Exception { client = new ProjectIterationClient(MockServerTestUtil - .createClientFactory(mockServerRule.getServerBaseUri()), + .createClientFactory(stubbingServerRule.getServerBaseUri()), "about-fedora", "master"); } @@ -63,3 +64,4 @@ public void testSampleConfig() { } } + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectsClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectsClientTest.java index 74fa26e4..806dba35 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectsClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/ProjectsClientTest.java @@ -26,19 +26,20 @@ import org.junit.ClassRule; import org.junit.Test; import org.zanata.rest.dto.Project; -import org.zanata.rest.service.MockServerRule; +import org.zanata.rest.service.StubbingServerRule; import static org.junit.Assert.*; public class ProjectsClientTest { @ClassRule - public static MockServerRule mockServerRule = new MockServerRule(); + public static StubbingServerRule + stubbingServerRule = new StubbingServerRule(); private ProjectsClient client; @Before public void setUp() { client = new ProjectsClient(MockServerTestUtil - .createClientFactory(mockServerRule.getServerBaseUri())); + .createClientFactory(stubbingServerRule.getServerBaseUri())); } @Test @@ -51,3 +52,4 @@ public void canGetProjects() { } + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/RestClientFactoryTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/RestClientFactoryTest.java index b4082bef..62c4bdf7 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/RestClientFactoryTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/RestClientFactoryTest.java @@ -26,17 +26,17 @@ import org.junit.Rule; import org.junit.Test; import org.zanata.rest.dto.VersionInfo; -import org.zanata.rest.service.MockServerRule; +import org.zanata.rest.service.StubbingServerRule; public class RestClientFactoryTest { @Rule - public MockServerRule mockServerRule = new MockServerRule(); + public StubbingServerRule stubbingServerRule = new StubbingServerRule(); @Test public void testGetVersion() { VersionInfo serverVersionInfo = MockServerTestUtil.createClientFactory( - mockServerRule.getServerBaseUri()) + stubbingServerRule.getServerBaseUri()) .getServerVersionInfo(); MatcherAssert.assertThat(serverVersionInfo.getVersionNo(), @@ -45,3 +45,4 @@ public void testGetVersion() { } + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/SourceDocResourceClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/SourceDocResourceClientTest.java index c0f945fb..eb4e1619 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/SourceDocResourceClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/SourceDocResourceClientTest.java @@ -32,12 +32,13 @@ import org.junit.Test; import org.zanata.rest.dto.resource.Resource; import org.zanata.rest.dto.resource.ResourceMeta; -import org.zanata.rest.service.MockServerRule; +import org.zanata.rest.service.StubbingServerRule; import com.google.common.collect.Sets; public class SourceDocResourceClientTest { @ClassRule - public static MockServerRule mockServerRule = new MockServerRule(); + public static StubbingServerRule + stubbingServerRule = new StubbingServerRule(); private SourceDocResourceClient client; @@ -45,7 +46,8 @@ public class SourceDocResourceClientTest { public void setUp() throws URISyntaxException { client = new SourceDocResourceClient( - MockServerTestUtil.createClientFactory(mockServerRule.getServerBaseUri()), "about-fedora", + MockServerTestUtil.createClientFactory( + stubbingServerRule.getServerBaseUri()), "about-fedora", "master"); } @@ -78,3 +80,4 @@ public void testDeleteResource() { } } + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/StatisticsResourceClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/StatisticsResourceClientTest.java index d437639e..78a64608 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/StatisticsResourceClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/StatisticsResourceClientTest.java @@ -31,11 +31,12 @@ import org.junit.Test; import org.zanata.rest.dto.stats.ContainerTranslationStatistics; import org.zanata.rest.dto.stats.contribution.ContributionStatistics; -import org.zanata.rest.service.MockServerRule; +import org.zanata.rest.service.StubbingServerRule; public class StatisticsResourceClientTest { @ClassRule - public static MockServerRule mockServerRule = new MockServerRule(); + public static StubbingServerRule + stubbingServerRule = new StubbingServerRule(); private StatisticsResourceClient client; @@ -43,7 +44,8 @@ public class StatisticsResourceClientTest { public void setUp() throws URISyntaxException { client = new StatisticsResourceClient( - MockServerTestUtil.createClientFactory(mockServerRule.getServerBaseUri())); + MockServerTestUtil.createClientFactory( + stubbingServerRule.getServerBaseUri())); } @Test @@ -77,3 +79,4 @@ public void testGetContributorStatistics() { } + diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/TransDocResourceClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/TransDocResourceClientTest.java index 91c31df3..2ad03c99 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/TransDocResourceClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/TransDocResourceClientTest.java @@ -27,7 +27,7 @@ import org.junit.Test; import org.zanata.common.LocaleId; import org.zanata.rest.dto.resource.TranslationsResource; -import org.zanata.rest.service.MockServerRule; +import org.zanata.rest.service.StubbingServerRule; import com.google.common.collect.Sets; @@ -35,14 +35,15 @@ public class TransDocResourceClientTest { @ClassRule - public static MockServerRule mockServerRule = new MockServerRule(); + public static StubbingServerRule + stubbingServerRule = new StubbingServerRule(); private TransDocResourceClient client; @Before public void setUp() { client = new TransDocResourceClient( - MockServerTestUtil.createClientFactory(mockServerRule.getServerBaseUri()), "about-fedora", + MockServerTestUtil.createClientFactory(stubbingServerRule.getServerBaseUri()), "about-fedora", "master"); } @@ -58,3 +59,4 @@ public void testGetTranslations() { } + From 31a21853d3ca837ed078ad1887c710f933578dbb Mon Sep 17 00:00:00 2001 From: Patrick Huang Date: Mon, 1 Dec 2014 15:28:32 +1000 Subject: [PATCH 11/55] rename MockitoServerRule to MockServerRule --- ...itoServerRule.java => MockServerRule.java} | 13 +++--- .../integraion/PushPullFileProjectITCase.java | 37 +++++++-------- .../integraion/PushPullGettextITCase.java | 45 ++++++++++--------- 3 files changed, 49 insertions(+), 46 deletions(-) rename zanata-client-commands/src/test/java/org/zanata/client/{MockitoServerRule.java => MockServerRule.java} (97%) diff --git a/zanata-client-commands/src/test/java/org/zanata/client/MockitoServerRule.java b/zanata-client-commands/src/test/java/org/zanata/client/MockServerRule.java similarity index 97% rename from zanata-client-commands/src/test/java/org/zanata/client/MockitoServerRule.java rename to zanata-client-commands/src/test/java/org/zanata/client/MockServerRule.java index dee288e1..d2c06ba1 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/MockitoServerRule.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/MockServerRule.java @@ -77,7 +77,7 @@ * @author Patrick Huang pahuang@redhat.com */ -public class MockitoServerRule extends ExternalResource { +public class MockServerRule extends ExternalResource { // async process statuses private String mockProcessId = "MockServerRuleProcess"; private ProcessStatus finished = new ProcessStatus(); @@ -116,7 +116,7 @@ public class MockitoServerRule extends ExternalResource { @Mock private FileResourceClient fileResourceClient; - public MockitoServerRule() { + public MockServerRule() { MockitoAnnotations.initMocks(this); // async process statuses running.setUrl(mockProcessId); @@ -163,8 +163,8 @@ private static URI setUrl(ConfigurableProjectOptions opts) { * successful. You should verify push afterwards and make assertion on * all/some of the captor captured values. * - * @see MockitoServerRule#verifyPushSource() - * @see MockitoServerRule#verifyPushTranslation() + * @see MockServerRule#verifyPushSource() + * @see MockServerRule#verifyPushTranslation() * @return push command */ public PushCommand createPushCommand() { @@ -281,8 +281,8 @@ public PullCommand createPullCommand(List remoteDocList, * Creates a raw file push command that will interact with mock REST proxy factory. * File service resource is stubbed to always return successful result. * - * @see MockitoServerRule#verifyPushRawFileSource(int) - * @see MockitoServerRule#verifyPushRawFileTranslation(int) + * @see MockServerRule#verifyPushRawFileSource(int) + * @see MockServerRule#verifyPushRawFileTranslation(int) * @return raw push command */ public RawPushCommand createRawPushCommand() { @@ -367,3 +367,4 @@ public RawPullCommand createRawPullCommand( return new RawPullCommand(pullOpts, fileResourceClient, clientFactory); } } + diff --git a/zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullFileProjectITCase.java b/zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullFileProjectITCase.java index e8710f82..a5974127 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullFileProjectITCase.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullFileProjectITCase.java @@ -33,7 +33,7 @@ import org.junit.rules.TemporaryFolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.zanata.client.MockitoServerRule; +import org.zanata.client.MockServerRule; import org.zanata.client.TestProjectGenerator; import org.zanata.client.commands.ConfigurableProjectOptions; import org.zanata.client.commands.pull.PullOptionsImpl; @@ -60,7 +60,7 @@ public class PushPullFileProjectITCase { private static final Logger log = LoggerFactory .getLogger(PushPullGettextITCase.class); @Rule - public MockitoServerRule mockitoServerRule = new MockitoServerRule(); + public MockServerRule mockServerRule = new MockServerRule(); @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @@ -69,18 +69,18 @@ public class PushPullFileProjectITCase { @Before public void setUp() { - ConfigurableProjectOptions pullOpts = mockitoServerRule.getPullOpts(); + ConfigurableProjectOptions pullOpts = mockServerRule.getPullOpts(); pullOpts.getLocaleMapList().add(new LocaleMapping("zh-CN")); pullOpts.setProjectType("file"); - ConfigurableProjectOptions pushOpts = mockitoServerRule.getPushOpts(); + ConfigurableProjectOptions pushOpts = mockServerRule.getPushOpts(); pushOpts.getLocaleMapList().add(new LocaleMapping("zh-CN")); pushOpts.setProjectType("file"); } @Test public void pushFileTypeProject() throws Exception { - PushOptionsImpl opts = mockitoServerRule.getPushOpts(); + PushOptionsImpl opts = mockServerRule.getPushOpts(); opts.setPushType("both"); File baseDir = testProjectGenerator.getProjectBaseDir(ProjectType.File); @@ -89,23 +89,23 @@ public void pushFileTypeProject() throws Exception { opts.setSrcDir(new File(baseDir, "src")); opts.setTransDir(baseDir); - RawPushCommand pushCommand = mockitoServerRule.createRawPushCommand(); + RawPushCommand pushCommand = mockServerRule.createRawPushCommand(); pushCommand.run(); - mockitoServerRule.verifyPushRawFileSource(2); - assertThat(mockitoServerRule.getDocIdCaptor().getAllValues(), + mockServerRule.verifyPushRawFileSource(2); + assertThat(mockServerRule.getDocIdCaptor().getAllValues(), contains("test-ods.ods", "test-odt.odt")); - mockitoServerRule.verifyPushRawFileTranslation(1); - assertThat(mockitoServerRule.getDocIdCaptor().getValue(), + mockServerRule.verifyPushRawFileTranslation(1); + assertThat(mockServerRule.getDocIdCaptor().getValue(), equalTo("test-odt.odt")); } @Test public void pushFileProjectUsingFileMapping() throws Exception { - PushOptionsImpl opts = mockitoServerRule.getPushOpts(); + PushOptionsImpl opts = mockServerRule.getPushOpts(); opts.setPushType("trans"); File baseDir = testProjectGenerator.getProjectBaseDir(ProjectType.File); @@ -116,18 +116,18 @@ public void pushFileProjectUsingFileMapping() throws Exception { opts.setFileMappingRules(Lists.newArrayList(new FileMappingRule( "{locale}/{path}/{filename}.{extension}"))); - RawPushCommand pushCommand = mockitoServerRule.createRawPushCommand(); + RawPushCommand pushCommand = mockServerRule.createRawPushCommand(); pushCommand.run(); - mockitoServerRule.verifyPushRawFileTranslation(1); - assertThat(mockitoServerRule.getDocIdCaptor().getValue(), + mockServerRule.verifyPushRawFileTranslation(1); + assertThat(mockServerRule.getDocIdCaptor().getValue(), equalTo("test-odt.odt")); } @Test public void pullFileProject() throws Exception { - PullOptionsImpl opts = mockitoServerRule.getPullOpts(); + PullOptionsImpl opts = mockServerRule.getPullOpts(); opts.setPullType("both"); File pullBaseDir = tempFolder.newFolder("file-pull-test"); opts.setSrcDir(pullBaseDir); @@ -142,7 +142,7 @@ public void pullFileProject() throws Exception { Lists.newArrayList(new ResourceMeta("test-ods.ods"), new ResourceMeta("test-odt.odt")); - RawPullCommand pullCommand = mockitoServerRule.createRawPullCommand( + RawPullCommand pullCommand = mockServerRule.createRawPullCommand( remoteDocList, sourceFileStream, transFileStream); pullCommand.run(); @@ -155,7 +155,7 @@ public void pullFileProject() throws Exception { @Test public void pullFileProjectUsingFileMapping() throws Exception { - PullOptionsImpl opts = mockitoServerRule.getPullOpts(); + PullOptionsImpl opts = mockServerRule.getPullOpts(); opts.setPullType("trans"); File pullBaseDir = tempFolder.newFolder("file-pull-test"); opts.setSrcDir(pullBaseDir); @@ -175,7 +175,7 @@ public void pullFileProjectUsingFileMapping() throws Exception { Lists.newArrayList(new ResourceMeta("test-ods.ods"), new ResourceMeta("test-odt.odt")); - RawPullCommand pullCommand = mockitoServerRule.createRawPullCommand( + RawPullCommand pullCommand = mockServerRule.createRawPullCommand( remoteDocList, sourceFileStream, transFileStream); pullCommand.run(); @@ -184,3 +184,4 @@ public void pullFileProjectUsingFileMapping() throws Exception { assertThat(new File(pullBaseDir, "ods/zh_CN/test-ods.ods").exists(), is(true)); } } + diff --git a/zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullGettextITCase.java b/zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullGettextITCase.java index 75cdab49..2449ea8a 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullGettextITCase.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullGettextITCase.java @@ -10,7 +10,7 @@ import org.junit.rules.TemporaryFolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.zanata.client.MockitoServerRule; +import org.zanata.client.MockServerRule; import org.zanata.client.TestProjectGenerator; import org.zanata.client.commands.ConfigurableProjectOptions; import org.zanata.client.commands.pull.PullCommand; @@ -41,7 +41,7 @@ public class PushPullGettextITCase { private static final Logger log = LoggerFactory .getLogger(PushPullGettextITCase.class); @Rule - public MockitoServerRule mockitoServerRule = new MockitoServerRule(); + public MockServerRule mockServerRule = new MockServerRule(); @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @@ -50,18 +50,18 @@ public class PushPullGettextITCase { @Before public void setUp() { - ConfigurableProjectOptions pullOpts = mockitoServerRule.getPullOpts(); + ConfigurableProjectOptions pullOpts = mockServerRule.getPullOpts(); pullOpts.getLocaleMapList().add(new LocaleMapping("zh-CN")); pullOpts.setProjectType("gettext"); - ConfigurableProjectOptions pushOpts = mockitoServerRule.getPushOpts(); + ConfigurableProjectOptions pushOpts = mockServerRule.getPushOpts(); pushOpts.getLocaleMapList().add(new LocaleMapping("zh-CN")); pushOpts.setProjectType("gettext"); } @Test public void pushGettextProject() throws Exception { - PushOptionsImpl opts = mockitoServerRule.getPushOpts(); + PushOptionsImpl opts = mockServerRule.getPushOpts(); opts.setPushType("both"); File baseDir = testProjectGenerator.getProjectBaseDir(ProjectType.Gettext); @@ -69,31 +69,31 @@ public void pushGettextProject() throws Exception { opts.setSrcDir(new File(baseDir, "po")); opts.setTransDir(new File(baseDir, "po")); - PushCommand pushCommand = mockitoServerRule.createPushCommand(); + PushCommand pushCommand = mockServerRule.createPushCommand(); pushCommand.run(); - mockitoServerRule.verifyPushSource(); - String docId = mockitoServerRule.getDocIdCaptor().getValue(); + mockServerRule.verifyPushSource(); + String docId = mockServerRule.getDocIdCaptor().getValue(); assertThat(docId, equalTo("tar")); - assertThat(mockitoServerRule.getExtensionCaptor().getValue(), + assertThat(mockServerRule.getExtensionCaptor().getValue(), Matchers. equalTo(new StringSet("gettext;comment"))); - Resource resource = mockitoServerRule.getResourceCaptor().getValue(); + Resource resource = mockServerRule.getResourceCaptor().getValue(); assertThat(resource.getTextFlows(), hasSize(2)); - mockitoServerRule.verifyPushTranslation(); - LocaleId localeId = mockitoServerRule.getLocaleIdCaptor().getValue(); + mockServerRule.verifyPushTranslation(); + LocaleId localeId = mockServerRule.getLocaleIdCaptor().getValue(); assertThat(localeId, equalTo(new LocaleId("zh-CN"))); TranslationsResource transResource = - mockitoServerRule.getTransResourceCaptor().getValue(); + mockServerRule.getTransResourceCaptor().getValue(); assertThat(transResource.getTextFlowTargets(), hasSize(2)); } @Test public void pushGettextProjectUsingFileMapping() throws Exception { - PushOptionsImpl opts = mockitoServerRule.getPushOpts(); + PushOptionsImpl opts = mockServerRule.getPushOpts(); opts.setPushType("trans"); File baseDir = testProjectGenerator.getProjectBaseDir(ProjectType.Gettext); @@ -103,22 +103,22 @@ public void pushGettextProjectUsingFileMapping() throws Exception { opts.setFileMappingRules(Lists.newArrayList(new FileMappingRule( "{path}/{locale_with_underscore}.po"))); - PushCommand pushCommand = mockitoServerRule.createPushCommand(); + PushCommand pushCommand = mockServerRule.createPushCommand(); pushCommand.run(); - mockitoServerRule.verifyPushTranslation(); - LocaleId localeId = mockitoServerRule.getLocaleIdCaptor().getValue(); + mockServerRule.verifyPushTranslation(); + LocaleId localeId = mockServerRule.getLocaleIdCaptor().getValue(); assertThat(localeId, equalTo(new LocaleId("zh-CN"))); TranslationsResource transResource = - mockitoServerRule.getTransResourceCaptor().getValue(); + mockServerRule.getTransResourceCaptor().getValue(); assertThat(transResource.getTextFlowTargets(), hasSize(2)); } @Test public void pullGettextProject() throws Exception { - PullOptionsImpl opts = mockitoServerRule.getPullOpts(); + PullOptionsImpl opts = mockServerRule.getPullOpts(); opts.setPullType("both"); File pullBaseDir = tempFolder.newFolder("gettext-pull-test"); opts.setSrcDir(pullBaseDir); @@ -133,7 +133,7 @@ public void pullGettextProject() throws Exception { target.setContents("hello world translated"); transResourceOnServer.getTextFlowTargets().add(target); - PullCommand pullCommand = mockitoServerRule.createPullCommand( + PullCommand pullCommand = mockServerRule.createPullCommand( Lists.newArrayList(new ResourceMeta("tar")), resourceOnServer, transResourceOnServer); @@ -145,7 +145,7 @@ public void pullGettextProject() throws Exception { @Test public void pullGettextProjectUsingFileMapping() throws Exception { - PullOptionsImpl opts = mockitoServerRule.getPullOpts(); + PullOptionsImpl opts = mockServerRule.getPullOpts(); opts.setPullType("trans"); File pullBaseDir = tempFolder.newFolder("gettext-pull-test"); opts.setSrcDir(pullBaseDir); @@ -163,7 +163,7 @@ public void pullGettextProjectUsingFileMapping() throws Exception { target.setContents("hello world translated"); transResourceOnServer.getTextFlowTargets().add(target); - PullCommand pullCommand = mockitoServerRule.createPullCommand( + PullCommand pullCommand = mockServerRule.createPullCommand( Lists.newArrayList(new ResourceMeta("tar")), resourceOnServer, transResourceOnServer); @@ -175,3 +175,4 @@ public void pullGettextProjectUsingFileMapping() throws Exception { } } + From ffcc07caa662d87b7d801703b808d2d03ee2469d Mon Sep 17 00:00:00 2001 From: Patrick Huang Date: Mon, 1 Dec 2014 15:45:39 +1000 Subject: [PATCH 12/55] rhbz1124630 - remove find-duplicate skip and control httpcomponent version --- stub-server/pom.xml | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/stub-server/pom.xml b/stub-server/pom.xml index 3d054d53..bcf57891 100644 --- a/stub-server/pom.xml +++ b/stub-server/pom.xml @@ -75,6 +75,10 @@ + + org.apache.httpcomponents + httpclient + org.jboss.resteasy resteasy-jaxb-provider @@ -153,15 +157,10 @@ com.ning.maven.plugins maven-duplicate-finder-plugin - - - - - about.html - - - - true + + + about.html + @@ -170,3 +169,6 @@ + + + From eec55675829ea6d53a719645837c50d2cad112d4 Mon Sep 17 00:00:00 2001 From: Patrick Huang Date: Fri, 5 Dec 2014 13:00:32 +1000 Subject: [PATCH 13/55] rhbz1124630 - use explicit path construction - jersey can not handle path template with regex in path param - extra url prefix (i.e. rest) will get appended twice using previous method --- .../rest/client/AsyncProcessClient.java | 29 ++++++------ .../org/zanata/rest/client/ClientUtil.java | 46 ------------------- .../zanata/rest/client/CopyTransClient.java | 12 ++--- .../rest/client/FileResourceClient.java | 26 ++++------- 4 files changed, 27 insertions(+), 86 deletions(-) diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/AsyncProcessClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/AsyncProcessClient.java index 985584de..fb8f4401 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/AsyncProcessClient.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/AsyncProcessClient.java @@ -24,7 +24,6 @@ import java.net.URI; import java.util.Set; import javax.ws.rs.DefaultValue; -import javax.ws.rs.core.UriBuilder; import org.zanata.common.LocaleId; import org.zanata.rest.dto.ProcessStatus; @@ -34,8 +33,6 @@ import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; -import static org.zanata.rest.client.ClientUtil.resolvePath; - /** * @author Patrick Huang pahuang@redhat.com @@ -64,13 +61,12 @@ public ProcessStatus startSourceDocCreationOrUpdate(String idNoSlash, Client client = factory.getClient(); CacheResponseFilter filter = new CacheResponseFilter(); client.addFilter(filter); - WebResource webResource = client.resource(baseUri); - String path = - resolvePath(webResource, AsynchronousProcessResource.class, - "startSourceDocCreationOrUpdate", projectSlug, - iterationSlug, idNoSlash); - - webResource.path(path) + WebResource webResource = client.resource(baseUri) + .path(AsynchronousProcessResource.SERVICE_PATH) + .path("projects").path("p").path(projectSlug) + .path("iterations").path("i").path(iterationSlug) + .path("r").path(idNoSlash); + webResource .queryParams(ClientUtil.asMultivaluedMap("ext", extensions)) .queryParam("copyTrans", String.valueOf(copytrans)) .put(resource); @@ -86,12 +82,13 @@ public ProcessStatus startTranslatedDocCreationOrUpdate(String idNoSlash, Client client = factory.getClient(); CacheResponseFilter filter = new CacheResponseFilter(); client.addFilter(filter); - WebResource webResource = client.resource(baseUri); - String path = - resolvePath(webResource, AsynchronousProcessResource.class, - "startTranslatedDocCreationOrUpdate", projectSlug, - iterationSlug, idNoSlash, locale); - webResource.path(path) + WebResource webResource = client.resource(baseUri) + .path(AsynchronousProcessResource.SERVICE_PATH) + .path("projects").path("p").path(projectSlug) + .path("iterations").path("i").path(iterationSlug) + .path("r").path(idNoSlash) + .path("translations").path(locale.toString()); + webResource .queryParams(ClientUtil.asMultivaluedMap("ext", extensions)) .queryParam("merge", merge) .put(translatedDoc); diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/ClientUtil.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ClientUtil.java index 8463502f..328c6696 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/ClientUtil.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/ClientUtil.java @@ -21,8 +21,6 @@ package org.zanata.rest.client; -import java.lang.reflect.Field; -import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; @@ -32,9 +30,7 @@ import javax.ws.rs.core.Response; import com.google.common.base.Strings; -import com.google.common.base.Throwables; import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; /** @@ -43,48 +39,6 @@ */ public class ClientUtil { - /** - * Resolve a REST resource path to a method. - * - * @param webResource - * web resource - * @param resourceInterface - * Zanata REST api interface - * @param methodName - * the method name we want to call which is annotated by @Path - * @param pathParams - * path param values - * @param - * interface type - * @return resolved path - */ - static String resolvePath(WebResource webResource, - Class resourceInterface, String methodName, - Object... pathParams) { - try { - // Zanata API always define SERVICE_PATH field - Field servicePathField = resourceInterface.getField("SERVICE_PATH"); - String servicePath = servicePathField.get(null).toString(); - Method method = getMethod(resourceInterface, methodName); - return webResource.getUriBuilder().path(servicePath).path(method) - .build(pathParams).getPath(); - } catch (NoSuchFieldException | IllegalAccessException e) { - throw Throwables.propagate(e); - } - } - - private static Method getMethod(Class resourceClass, - String methodName) { - Method[] methods = resourceClass.getDeclaredMethods(); - for (Method method : methods) { - if (method.getName().equals(methodName)) { - return method; - } - } - throw new IllegalArgumentException(methodName + " not found in " - + resourceClass); - } - static MultivaluedMap asMultivaluedMap( String paramKey, Iterable values) { MultivaluedMapImpl map = new MultivaluedMapImpl(); diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/CopyTransClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/CopyTransClient.java index 7932bbff..c356d179 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/CopyTransClient.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/CopyTransClient.java @@ -28,8 +28,6 @@ import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; -import static org.zanata.rest.client.ClientUtil.resolvePath; - /** * @author Patrick Huang pahuang@redhat.com @@ -58,11 +56,11 @@ public CopyTransStatus startCopyTrans(String projectSlug, private WebResource webResource(Client client, String projectSlug, String iterationSlug, String docId) { - WebResource webResource = client.resource(baseUri); - String path = - resolvePath(webResource, CopyTransResource.class, - "startCopyTrans", projectSlug, iterationSlug, docId); - return webResource.path(path); + return client.resource(baseUri) + .path(CopyTransResource.SERVICE_PATH) + .path("/proj").path(projectSlug) + .path("iter").path(iterationSlug) + .path("doc").path(docId); } @Override diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/FileResourceClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/FileResourceClient.java index a99bdfe7..f55a7268 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/FileResourceClient.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/FileResourceClient.java @@ -21,8 +21,6 @@ package org.zanata.rest.client; -import static org.zanata.rest.client.ClientUtil.resolvePath; - import java.net.URI; import javax.ws.rs.core.MediaType; @@ -133,26 +131,20 @@ public ChunkUploadResponse uploadTranslationFile( public ClientResponse downloadSourceFile(String projectSlug, String iterationSlug, String fileType, String docId) { - WebResource webResource = factory.getClient().resource(baseUri); - String path = resolvePath(webResource, FileResource.class, - "downloadSourceFile", projectSlug, iterationSlug, fileType); - return webResource.path(path) - .queryParam("docId", docId) - .get(ClientResponse.class); + WebResource webResource = factory.getClient().resource(baseUri) + .path(FileResource.SERVICE_PATH).path("source") + .path(projectSlug).path(iterationSlug).path(fileType); + return webResource.queryParam("docId", docId).get(ClientResponse.class); } public ClientResponse downloadTranslationFile(String projectSlug, String iterationSlug, String locale, String fileExtension, String docId) { - WebResource webResource = factory.getClient().resource(baseUri); - String path = - resolvePath(webResource, FileResource.class, - "downloadTranslationFile", - projectSlug, iterationSlug, locale, fileExtension); - return webResource.path(path) - .queryParam("docId", docId) - .get(ClientResponse.class); - + WebResource webResource = factory.getClient().resource(baseUri) + .path(FileResource.SERVICE_PATH).path("translation") + .path(projectSlug).path(iterationSlug).path(locale) + .path(fileExtension); + return webResource.queryParam("docId", docId).get(ClientResponse.class); } private static FormDataMultiPart addBodyPartIfPresent( From 6c2099ddc2e0d001102c1a700e7b01f1b958de1a Mon Sep 17 00:00:00 2001 From: Patrick Huang Date: Thu, 11 Dec 2014 14:58:47 +1000 Subject: [PATCH 14/55] rhbz1124630 - need to override accept header for some clients to work --- .../src/main/java/org/zanata/rest/client/ProjectClient.java | 5 ++++- .../java/org/zanata/rest/client/ProjectIterationClient.java | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectClient.java index 695a812e..b4b28ad5 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectClient.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectClient.java @@ -21,6 +21,8 @@ package org.zanata.rest.client; +import javax.ws.rs.core.MediaType; + import org.zanata.rest.dto.Project; import org.zanata.rest.service.ProjectResource; import com.sun.jersey.api.client.WebResource; @@ -50,6 +52,7 @@ private WebResource webResource() { } public void put(Project project) { - webResource().put(project); + webResource().accept(MediaType.WILDCARD_TYPE).put(project); } } + diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectIterationClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectIterationClient.java index e0051472..105f89ec 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectIterationClient.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectIterationClient.java @@ -23,6 +23,8 @@ import java.net.URI; +import javax.ws.rs.core.MediaType; + import org.zanata.rest.dto.ProjectIteration; import com.sun.jersey.api.client.WebResource; @@ -55,10 +57,11 @@ private WebResource webResource() { } public void put(ProjectIteration projectVersion) { - webResource().put(projectVersion); + webResource().accept(MediaType.WILDCARD_TYPE).put(projectVersion); } public String sampleConfiguration() { return webResource().path("config").get(String.class); } } + From c417014347e2ad948f3862458a895cdd02790770 Mon Sep 17 00:00:00 2001 From: Patrick Huang Date: Tue, 16 Dec 2014 16:01:43 +1000 Subject: [PATCH 15/55] make the script work when you symlinked it --- zanata-cli/etc/scripts/zanata-cli | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/zanata-cli/etc/scripts/zanata-cli b/zanata-cli/etc/scripts/zanata-cli index 93ed0194..c5cce3f3 100755 --- a/zanata-cli/etc/scripts/zanata-cli +++ b/zanata-cli/etc/scripts/zanata-cli @@ -1,4 +1,15 @@ #!/bin/bash -e -SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -PROJ_DIR=$SCRIPT_DIR/../.. -exec mvn -f $PROJ_DIR/pom.xml -q exec:java -Dexec.args="$*" + +# Full path to script even $0 has symlinks. +# Reference: http://stackoverflow.com/a/246128/345718 +SOURCE="${BASH_SOURCE[0]}" +while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink + DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" + SOURCE="$(readlink "$SOURCE")" + [[ ${SOURCE} != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located +done +SCRIPT_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" + +PROJ_DIR=${SCRIPT_DIR}/../.. +exec mvn -f ${PROJ_DIR}/pom.xml -q exec:java -Dexec.args="$*" + From 5e30fc97234c66d1f024ddd9e0549c3bc82ce436 Mon Sep 17 00:00:00 2001 From: Patrick Huang Date: Wed, 24 Dec 2014 08:15:07 +1000 Subject: [PATCH 16/55] rhbz1124630 - need to add header for all requests --- .../client/commands/ConfigurableCommand.java | 4 ++ .../client/commands/init/InitCommand.java | 5 +- .../client/commands/init/InitCommandTest.java | 6 +++ .../zanata/rest/client/AcceptTypeFilter.java | 49 +++++++++++++++++++ .../rest/client/FileResourceClient.java | 1 + .../org/zanata/rest/client/ProjectClient.java | 6 +-- .../rest/client/ProjectIterationClient.java | 5 +- .../zanata/rest/client/RestClientFactory.java | 5 ++ 8 files changed, 73 insertions(+), 8 deletions(-) create mode 100644 zanata-rest-client/src/main/java/org/zanata/rest/client/AcceptTypeFilter.java diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/ConfigurableCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/ConfigurableCommand.java index 073a3c2d..6bdd6819 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/ConfigurableCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/ConfigurableCommand.java @@ -80,6 +80,10 @@ public RestClientFactory getClientFactory() { return clientFactory; } + protected final void setClientFactory(RestClientFactory clientFactory) { + this.clientFactory = clientFactory; + } + @Override public boolean isDeprecated() { return deprecated; diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/init/InitCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/init/InitCommand.java index 3da170e6..fa61c296 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/init/InitCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/init/InitCommand.java @@ -70,7 +70,8 @@ public class InitCommand extends ConfigurableCommand { private UserConfigHandler userConfigHandler; public InitCommand(InitOptions opts) { - super(opts); + // we don't have all mandatory information yet (server URL etc) + super(opts, new RestClientFactory() {}); console = new ConsoleInteractorImpl(); projectConfigHandler = new ProjectConfigHandler(console, getOpts()); @@ -93,6 +94,8 @@ protected void run() throws Exception { // Search for zanata.ini userConfigHandler.verifyUserConfig(); + setClientFactory(OptionsUtil.createClientFactory(getOpts())); + ensureServerVersion(); // If there's a zanata.xml, ask the user diff --git a/zanata-client-commands/src/test/java/org/zanata/client/commands/init/InitCommandTest.java b/zanata-client-commands/src/test/java/org/zanata/client/commands/init/InitCommandTest.java index 1da8eecf..111cd450 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/commands/init/InitCommandTest.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/commands/init/InitCommandTest.java @@ -54,6 +54,12 @@ public void setUp() throws IOException { command = new InitCommand(opts, console, clientFactory); } + @Test + public void createCommandWithoutMandatoryOptionsWillNotCauseException() { + // we don't have server url etc yet + command = new InitCommand(opts); + } + @Test public void willDownloadProjectConfigFromServer() throws IOException { when(clientFactory.getProjectIterationClient("gcc", "master")).thenReturn(projectIterationClient); diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/AcceptTypeFilter.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/AcceptTypeFilter.java new file mode 100644 index 00000000..6e1c7119 --- /dev/null +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/AcceptTypeFilter.java @@ -0,0 +1,49 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import javax.ws.rs.core.MultivaluedMap; + +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.filter.ClientFilter; + +/** + * This adds a generic Accept header to all request. It is a workaround for + * RESTEasy 2 service. Clients requiring specific Accpet type can override it. + * + * @author Patrick Huang pahuang@redhat.com + */ +public class AcceptTypeFilter extends ClientFilter { + @Override + public ClientResponse handle(ClientRequest cr) + throws ClientHandlerException { + MultivaluedMap headers = cr.getHeaders(); + // make sure we have at least one Accept header otherwise jersey will + // insert an "Accept: text/html, image/gif, image/jpeg, *" which breaks + // RESTEasy 2 + headers.add("Accept", "application/*"); + return getNext().handle(cr); + } +} diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/FileResourceClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/FileResourceClient.java index f55a7268..a01ad73a 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/FileResourceClient.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/FileResourceClient.java @@ -55,6 +55,7 @@ public StringSet acceptedFileTypes() { .resource(baseUri) .path(FileResource.SERVICE_PATH) .path("accepted_types") + .accept(MediaType.TEXT_PLAIN_TYPE) .get(String.class); return new StringSet(types); } diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectClient.java index b4b28ad5..d1ae8e44 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectClient.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectClient.java @@ -21,10 +21,8 @@ package org.zanata.rest.client; -import javax.ws.rs.core.MediaType; - import org.zanata.rest.dto.Project; -import org.zanata.rest.service.ProjectResource; + import com.sun.jersey.api.client.WebResource; /** @@ -52,7 +50,7 @@ private WebResource webResource() { } public void put(Project project) { - webResource().accept(MediaType.WILDCARD_TYPE).put(project); + webResource().put(project); } } diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectIterationClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectIterationClient.java index 105f89ec..f8c4eff5 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectIterationClient.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectIterationClient.java @@ -23,9 +23,8 @@ import java.net.URI; -import javax.ws.rs.core.MediaType; - import org.zanata.rest.dto.ProjectIteration; + import com.sun.jersey.api.client.WebResource; /** @@ -57,7 +56,7 @@ private WebResource webResource() { } public void put(ProjectIteration projectVersion) { - webResource().accept(MediaType.WILDCARD_TYPE).put(projectVersion); + webResource().put(projectVersion); } public String sampleConfiguration() { diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/RestClientFactory.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/RestClientFactory.java index 1c2c15e9..f40abe57 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/RestClientFactory.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/RestClientFactory.java @@ -64,6 +64,10 @@ public class RestClientFactory { private Client client; private URI baseURI; + // for use by InitCommand + protected RestClientFactory() { + } + public RestClientFactory(URI base, String username, String apiKey, VersionInfo clientApiVersion, boolean logHttp, boolean sslCertDisabled) { @@ -79,6 +83,7 @@ public RestClientFactory(URI base, String username, String apiKey, client = Client.create(clientConfig); client.addFilter( new ApiKeyHeaderFilter(username, apiKey, clientVersion)); + client.addFilter(new AcceptTypeFilter()); client.addFilter(new TraceDebugFilter(logHttp)); } From 69bb0eab286c3bf4e88004bade27e08732878150 Mon Sep 17 00:00:00 2001 From: Patrick Huang Date: Wed, 7 Jan 2015 10:15:54 +1000 Subject: [PATCH 17/55] set project type when selecting version in zanata init --- .../commands/init/ProjectIterationPrompt.java | 29 ++++++++++++++++--- .../client/commands/init/ProjectPrompt.java | 10 +++---- .../init/ProjectIterationPromptTest.java | 2 ++ 3 files changed, 32 insertions(+), 9 deletions(-) diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/init/ProjectIterationPrompt.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/init/ProjectIterationPrompt.java index c0ed91fb..16d3f457 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/init/ProjectIterationPrompt.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/init/ProjectIterationPrompt.java @@ -20,6 +20,7 @@ */ package org.zanata.client.commands.init; +import static com.google.common.base.Strings.isNullOrEmpty; import static org.zanata.client.commands.ConsoleInteractor.DisplayMode.Confirmation; import static org.zanata.client.commands.ConsoleInteractor.DisplayMode.Hint; import static org.zanata.client.commands.ConsoleInteractor.DisplayMode.Question; @@ -29,6 +30,7 @@ import java.util.List; import org.zanata.client.commands.ConsoleInteractor; +import org.zanata.client.commands.ConsoleInteractorImpl; import org.zanata.common.EntityStatus; import org.zanata.rest.client.ProjectClient; import org.zanata.rest.client.ProjectIterationClient; @@ -37,7 +39,9 @@ import org.zanata.rest.dto.ProjectIteration; import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Joiner; import com.google.common.base.Predicate; +import com.google.common.base.Strings; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.sun.jersey.api.client.UniformInterfaceException; @@ -93,11 +97,28 @@ protected void selectVersion() { consoleInteractor.printf(Question, _("select.version.prompt")); String selection = consoleInteractor.expectAnswerWithRetry(expect(versionIndexes)); - String versionId = - Iterables.get(activeIterations, - (Integer.valueOf(selection) - 1)) - .getId(); + ProjectIteration projectIteration = Iterables.get(activeIterations, + (Integer.valueOf(selection) - 1)); + String versionId = projectIteration.getId(); opts.setProjectVersion(versionId); + opts.setProjectType(resolveProjectType(project, projectIteration)); + } + + private String resolveProjectType(Project project, + ProjectIteration projectIteration) { + if (!isNullOrEmpty(projectIteration.getProjectType())) { + return projectIteration.getProjectType().toLowerCase(); + } else if (!isNullOrEmpty(project.getDefaultType())) { + return project.getDefaultType().toLowerCase(); + } else { + String projectTypes = + Joiner.on(", ").join(ProjectPrompt.PROJECT_TYPE_LIST); + consoleInteractor.printfln(Question, _("project.type.prompt"), + projectTypes); + return consoleInteractor.expectAnswerWithRetry( + ConsoleInteractorImpl.AnswerValidatorImpl + .expect(ProjectPrompt.PROJECT_TYPE_LIST)); + } } @VisibleForTesting diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/init/ProjectPrompt.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/init/ProjectPrompt.java index 8a7f95ab..7ccf2c8d 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/init/ProjectPrompt.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/init/ProjectPrompt.java @@ -60,6 +60,9 @@ class ProjectPrompt { // state variables private List allProjects = Collections.emptyList(); private List filteredProjects = Collections.emptyList(); + public static final List PROJECT_TYPE_LIST = + Lists.transform(Lists.newArrayList(ProjectType.values()), + new ProjectTypeToStringFunction()); ProjectPrompt(ConsoleInteractor consoleInteractor, InitOptions opts, ProjectIterationPrompt projectIterationPrompt, @@ -190,14 +193,11 @@ protected void createNewProject() { String projectId = consoleInteractor.expectAnyAnswer(); consoleInteractor.printfln(Question, _("project.name.prompt")); String projectName = consoleInteractor.expectAnyAnswer(); - List projectTypeList = - Lists.transform(Lists.newArrayList(ProjectType.values()), - new ProjectTypeToStringFunction()); - String projectTypes = Joiner.on(", ").join(projectTypeList); + String projectTypes = Joiner.on(", ").join(PROJECT_TYPE_LIST); consoleInteractor.printfln(Question, _("project.type.prompt"), projectTypes); String projectType = consoleInteractor.expectAnswerWithRetry( - AnswerValidatorImpl.expect(projectTypeList)); + AnswerValidatorImpl.expect(PROJECT_TYPE_LIST)); ProjectClient projectClient = clientFactory.getProjectClient(projectId); Project project = new Project(projectId, projectName, projectType); try { diff --git a/zanata-client-commands/src/test/java/org/zanata/client/commands/init/ProjectIterationPromptTest.java b/zanata-client-commands/src/test/java/org/zanata/client/commands/init/ProjectIterationPromptTest.java index 1ad5d581..9f7abe6b 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/commands/init/ProjectIterationPromptTest.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/commands/init/ProjectIterationPromptTest.java @@ -72,11 +72,13 @@ public void willGuideUserToSelectVersion() { verify(projectClient).get(); assertThat(opts.getProjectVersion(), Matchers.equalTo("4.8.2")); + assertThat(opts.getProjectType(), Matchers.equalTo("gettext")); } private static ProjectIteration newIteration(String id, EntityStatus status) { ProjectIteration iteration = new ProjectIteration(id); iteration.setStatus(status); + iteration.setProjectType("gettext"); return iteration; } From 0e84b877726a446664fb2b07cc1619f2371eb1bb Mon Sep 17 00:00:00 2001 From: Sean Flanigan Date: Wed, 14 Jan 2015 10:57:45 +1000 Subject: [PATCH 18/55] Squashed commit of the following: commit 259510ced07390eb38bd830651cddf1a75954ed4 Merge: fdbdd25 5b902fd Author: Sean Flanigan Date: Wed Jan 14 10:46:48 2015 +1000 Merge remote-tracking branch 'origin/master' into fix-formatting Conflicts: zanata-client-commands/src/main/java/org/zanata/client/commands/pull/PullCommand.java zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushCommand.java zanata-rest-client/src/main/java/org/zanata/rest/client/ClientUtility.java zanata-rest-client/src/main/java/org/zanata/rest/client/TraceDebugInterceptor.java commit fdbdd25198f8565f633c62f55f8c4ec95d810524 Author: Sean Flanigan Date: Fri Dec 5 15:23:28 2014 +1000 Update zanata-parent commit 97d9ac922fd66e704ebc2dd29e0d9b5647e60259 Author: Sean Flanigan Date: Fri Dec 5 11:41:39 2014 +1000 Fix formatting --- .../src/main/java/org/zanata/client/ZanataClient.java | 7 +++---- .../test/java/org/zanata/client/HTTPMockContainer.java | 2 +- .../test/java/org/zanata/client/ZanataClientTest.java | 2 +- .../java/org/zanata/client/commands/UpdateChecker.java | 3 +-- .../zanata/client/commands/init/SourceConfigPrompt.java | 3 +-- .../org/zanata/client/commands/pull/PullCommand.java | 7 +++---- .../org/zanata/client/commands/pull/RawPullCommand.java | 2 +- .../org/zanata/client/commands/push/PushCommand.java | 8 +++++--- .../org/zanata/client/commands/push/RawPushCommand.java | 9 +++------ .../client/commands/stats/GetStatisticsCommand.java | 5 ++--- .../src/test/java/org/zanata/client/MockServerRule.java | 3 +-- .../java/org/zanata/client/commands/OptionsUtilTest.java | 2 +- .../zanata/client/commands/init/ProjectPromptTest.java | 3 ++- .../src/main/java/org/zanata/maven/PushSimpleMojo.java | 3 ++- 14 files changed, 27 insertions(+), 32 deletions(-) diff --git a/zanata-cli/src/main/java/org/zanata/client/ZanataClient.java b/zanata-cli/src/main/java/org/zanata/client/ZanataClient.java index df73ffb8..01993924 100644 --- a/zanata-cli/src/main/java/org/zanata/client/ZanataClient.java +++ b/zanata-cli/src/main/java/org/zanata/client/ZanataClient.java @@ -211,10 +211,9 @@ private void printHelp(PrintWriter out) { out.println(); out.println("Available commands:"); for (String cmd : OPTIONS.keySet()) { - out.println(" " + cmd /* - * + ": " + OPTIONS.get(cmd).newInstance(). - * getCommandDescription() - */); + out.println(" " + cmd); + // + ": " + OPTIONS.get(cmd).newInstance(). + // getCommandDescription() } } diff --git a/zanata-cli/src/test/java/org/zanata/client/HTTPMockContainer.java b/zanata-cli/src/test/java/org/zanata/client/HTTPMockContainer.java index 0429295b..a30ecad7 100644 --- a/zanata-cli/src/test/java/org/zanata/client/HTTPMockContainer.java +++ b/zanata-cli/src/test/java/org/zanata/client/HTTPMockContainer.java @@ -49,7 +49,7 @@ public void handle(Request request, Response response) { body.println(responseContent); body.close(); - } catch(Exception e) { + } catch (Exception e) { e.printStackTrace(); } } diff --git a/zanata-cli/src/test/java/org/zanata/client/ZanataClientTest.java b/zanata-cli/src/test/java/org/zanata/client/ZanataClientTest.java index 61f0060a..02b64399 100644 --- a/zanata-cli/src/test/java/org/zanata/client/ZanataClientTest.java +++ b/zanata-cli/src/test/java/org/zanata/client/ZanataClientTest.java @@ -28,7 +28,7 @@ * */ @PrepareForTest(SubCommandHandler2.class) -@PowerMockIgnore({"com.sun.*", "org.apache.log4j.*", "org.xml.*", "javax.xml.*"}) +@PowerMockIgnore({ "com.sun.*", "org.apache.log4j.*", "org.xml.*", "javax.xml.*" }) @RunWith(PowerMockRunner.class) public class ZanataClientTest { @Rule diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/UpdateChecker.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/UpdateChecker.java index b6f3da9b..aa523f6a 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/UpdateChecker.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/UpdateChecker.java @@ -188,8 +188,7 @@ public void checkNewerVersion() { props.setProperty(LAST_CHECKED, today); props.store(new BufferedWriter(new FileWriterWithEncoding( updateMarker, Charsets.UTF_8)), null); - } - catch (IOException e) { + } catch (IOException e) { log.warn("failed to load file {}", updateMarker); } } diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/init/SourceConfigPrompt.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/init/SourceConfigPrompt.java index 8f7fa6fe..0df88386 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/init/SourceConfigPrompt.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/init/SourceConfigPrompt.java @@ -176,8 +176,7 @@ private static String getUsageFromOptionAnnotation( Option.class).usage() // the usage text is not very well formatted (contains new line) .replaceAll(System.getProperty("line.separator"), " "); - } - catch (NoSuchMethodException e) { + } catch (NoSuchMethodException e) { log.error("can not find method: {} on class {}", methodName, optionsClass); return methodName; } diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/pull/PullCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/pull/PullCommand.java index ae9faddd..9bceaa14 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/pull/PullCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/pull/PullCommand.java @@ -264,9 +264,8 @@ && getOpts().getPullType() == PushPullType.Source) { transResponse.getHeaders() .getFirst(HttpHeaders.ETAG)); } - } - // 304 NOT MODIFIED (the document can stay the same) - else if (transResponse.getClientResponseStatus() == ClientResponse.Status.NOT_MODIFIED) { + } else if (transResponse.getClientResponseStatus() == ClientResponse.Status.NOT_MODIFIED) { + // 304 NOT MODIFIED (the document can stay the same) log.info( "No changes in translations for locale {} and document {}", locale, localDocName); @@ -309,7 +308,7 @@ else if (transResponse.getClientResponseStatus() == ClientResponse.Status.NOT_MO } catch (RuntimeException e) { String message = - "Operation failed: "+e.getMessage()+"\n\n" + "Operation failed: " + e.getMessage() + "\n\n" + " To retry from the last document, please set the following option(s):\n\n" + " "; if (getOpts().getEnableModules()) { diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/pull/RawPullCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/pull/RawPullCommand.java index 3880155e..474985c2 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/pull/RawPullCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/pull/RawPullCommand.java @@ -212,7 +212,7 @@ public void run() throws IOException { } } catch (IOException | RuntimeException e) { log.error( - "Operation failed: "+e.getMessage()+"\n\n" + "Operation failed: " + e.getMessage() + "\n\n" + " To retry from the last document, please add the option: {}\n", getOpts().buildFromDocArgument(qualifiedDocName)); throw new RuntimeException(e.getMessage(), e); diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushCommand.java index bbfc91fc..b4fe7e1d 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushCommand.java @@ -420,7 +420,7 @@ public void visit(LocaleMapping locale, } } catch (Exception e) { String message = - "Operation failed: "+e.getMessage()+"\n\n" + "Operation failed: " + e.getMessage() + "\n\n" + " To retry from the last document, please set the following option(s):\n\n" + " "; if (getOpts().getEnableModules()) { @@ -572,7 +572,8 @@ private void pushSrcDocToServer(final String docUri, final Resource srcDoc, break; } - wait(POLL_PERIOD); // Wait before retrying + // Wait before retrying + wait(POLL_PERIOD); status = asyncProcessClient.getProcessStatus(status.getUrl()); } @@ -693,7 +694,8 @@ targetDoc, extensions, getOpts() break; } - wait(POLL_PERIOD); // Wait before retrying + // Wait before retrying + wait(POLL_PERIOD); status = asyncProcessClient.getProcessStatus(status.getUrl()); } ConsoleUtils.endProgressFeedback(); diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/RawPushCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/RawPushCommand.java index 1086f159..2a92cd48 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/RawPushCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/RawPushCommand.java @@ -172,11 +172,8 @@ public void run() throws IOException { + "': existing translations on server may be overwritten/deleted"); if (getOpts().getPushType() == PushPullType.Both) { - confirmWithUser("This will overwrite existing documents AND TRANSLATIONS on the server.\n"); // , - // and - // delete - // obsolete - // documents.\n"); + confirmWithUser("This will overwrite existing documents AND TRANSLATIONS on the server.\n"); + // , and delete obsolete documents.\n"); } else if (getOpts().getPushType() == PushPullType.Trans) { confirmWithUser("This will overwrite existing TRANSLATIONS on the server.\n"); } @@ -229,7 +226,7 @@ public void visit(LocaleMapping locale, } } catch (IOException | RuntimeException e) { log.error( - "Operation failed: "+e.getMessage()+"\n\n" + "Operation failed: " + e.getMessage() + "\n\n" + " To retry from the last document, please add the option: {}\n", getOpts().buildFromDocArgument(localDocName)); throw new RuntimeException(e.getMessage(), e); diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/stats/GetStatisticsCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/stats/GetStatisticsCommand.java index 39f06d82..3d27f772 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/stats/GetStatisticsCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/stats/GetStatisticsCommand.java @@ -90,9 +90,8 @@ public void run() throws Exception { .getProjectVersion(), getOpts().getIncludeDetails(), getOpts() .getIncludeWordLevelStats(), localeListArg); - } - // Otherwise, stats for the single document - else { + } else { + // Otherwise, stats for the single document containerStats = client .getStatistics(getOpts().getProj(), getOpts() diff --git a/zanata-client-commands/src/test/java/org/zanata/client/MockServerRule.java b/zanata-client-commands/src/test/java/org/zanata/client/MockServerRule.java index d2c06ba1..7d2d52de 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/MockServerRule.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/MockServerRule.java @@ -151,8 +151,7 @@ private static URI setUrl(ConfigurableProjectOptions opts) { URI uri = new URI("http://localhost:8888/zanata"); opts.setUrl(uri.toURL()); return uri; - } - catch (Exception e) { + } catch (Exception e) { throw Throwables.propagate(e); } } diff --git a/zanata-client-commands/src/test/java/org/zanata/client/commands/OptionsUtilTest.java b/zanata-client-commands/src/test/java/org/zanata/client/commands/OptionsUtilTest.java index f230ec2b..7b90eac8 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/commands/OptionsUtilTest.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/commands/OptionsUtilTest.java @@ -132,6 +132,6 @@ public void willThrowExceptionIfRuleIsInvalid() { OptionsUtil.checkPotentialMistakesInRules(opts, console); - verify(console).printfln(Warning, _("invalid.rule"),rule); + verify(console).printfln(Warning, _("invalid.rule"), rule); } } diff --git a/zanata-client-commands/src/test/java/org/zanata/client/commands/init/ProjectPromptTest.java b/zanata-client-commands/src/test/java/org/zanata/client/commands/init/ProjectPromptTest.java index 4c4c4bda..a43bb7e0 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/commands/init/ProjectPromptTest.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/commands/init/ProjectPromptTest.java @@ -88,7 +88,8 @@ public void willFilterAllProjectsIfUserTypeLetters() { // Given: user input ConsoleInteractor console = MockConsoleInteractor.predefineAnswers( - "99", // part of project name + // part of project name + "99", "1"); prompt = new ProjectPrompt(console, opts, diff --git a/zanata-maven-plugin/src/main/java/org/zanata/maven/PushSimpleMojo.java b/zanata-maven-plugin/src/main/java/org/zanata/maven/PushSimpleMojo.java index 48b310ab..c8dce97b 100644 --- a/zanata-maven-plugin/src/main/java/org/zanata/maven/PushSimpleMojo.java +++ b/zanata-maven-plugin/src/main/java/org/zanata/maven/PushSimpleMojo.java @@ -41,6 +41,7 @@ public boolean getEnableModules() { @Override public boolean getDeleteObsoleteModules() { - return false; // False for Simple push + // False for Simple push + return false; } } From dfa4a00077f7906401022bfb807e50d050c6b9ca Mon Sep 17 00:00:00 2001 From: Sean Flanigan Date: Wed, 14 Jan 2015 13:37:50 +1000 Subject: [PATCH 19/55] Fix formatting --- .../src/test/java/org/zanata/client/TestProjectGenerator.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/zanata-client-commands/src/test/java/org/zanata/client/TestProjectGenerator.java b/zanata-client-commands/src/test/java/org/zanata/client/TestProjectGenerator.java index f9039f0b..490251a2 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/TestProjectGenerator.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/TestProjectGenerator.java @@ -162,8 +162,7 @@ public String getUrl() { public URL getURL() { try { return new URI(url).toURL(); - } - catch (MalformedURLException | URISyntaxException e) { + } catch (MalformedURLException | URISyntaxException e) { throw Throwables.propagate(e); } } From 5823a762ba6a28311cb39e41bc9ab458047224ae Mon Sep 17 00:00:00 2001 From: Carlos Munoz Date: Fri, 16 Jan 2015 09:33:01 +1000 Subject: [PATCH 20/55] Add Read the docs documentation. Currently uses the default readthedocs theme, but can be customized with our own theme. This is an almost exact copy of the content on zanata.org/help that relates to the client. --- docs/commands/init.md | 47 +++++++++ docs/commands/pull.md | 43 +++++++++ docs/commands/push.md | 62 ++++++++++++ docs/configuration.md | 122 ++++++++++++++++++++++++ docs/images/302-user-settings.png | Bin 0 -> 20604 bytes docs/images/350-version-config-file.png | Bin 0 -> 10475 bytes docs/index.md | 34 +++++++ docs/installation.md | 43 +++++++++ docs/maven-plugin/commands.md | 65 +++++++++++++ docs/maven-plugin/configuration.md | 67 +++++++++++++ docs/maven-plugin/installation.md | 32 +++++++ mkdocs.yml | 19 ++++ 12 files changed, 534 insertions(+) create mode 100644 docs/commands/init.md create mode 100644 docs/commands/pull.md create mode 100644 docs/commands/push.md create mode 100644 docs/configuration.md create mode 100644 docs/images/302-user-settings.png create mode 100644 docs/images/350-version-config-file.png create mode 100644 docs/index.md create mode 100644 docs/installation.md create mode 100644 docs/maven-plugin/commands.md create mode 100644 docs/maven-plugin/configuration.md create mode 100644 docs/maven-plugin/installation.md create mode 100644 mkdocs.yml diff --git a/docs/commands/init.md b/docs/commands/init.md new file mode 100644 index 00000000..3cdabd95 --- /dev/null +++ b/docs/commands/init.md @@ -0,0 +1,47 @@ +# Command: init + +To initialise a project from the command line, the `init` command can be used. This command will guide you through the steps necessary to set up a new or existing project, and start using Zanata. + +These instructions assume that you have installed zanata-cli version 3.4.0 or higher as shown in [Installing the Client](installation). + + + +## Getting started + +The first thing to do is to type the following command in the console: `zanata-cli init` + +The client will proceed to ask which of your preferred Zanata servers it needs to use to register your new project (this information is taken from your `zanata.ini` file; if the desired server does not appear in the list, it should be added to this file). + +```bash +[INFO] Loading project config from zanata.xml +[INFO] Loading user config from /home/camunoz/.config/zanata.ini + Found servers in zanata.ini: + 1) http://localhost:8080/zanata/ + 2) https://translate.jboss.org/ + 3) https://translate.zanata.org/zanata/ +[?] Which Zanata server do you want to use? +``` + +Select the Zanata server to use by typing in the number and hiting ENTER. The client will now ask whether you want to create a new project, or use an existing one from your instance: + +```bash +[?] Do you want to 1) select an existing project or 2) create a new one (1/2)? +``` + +According to your selection the client will ask for information about your new project and proceed to create it, or it will give you an option to select an existing one from the server. + +```bash +[?] What project ID/slug do you want to have (must start and end with a letter or number, and contain only letters, numbers, underscores and hyphens): +$ my-project-id +[?] What project name do you want to have: +$ My Project Name +[?] What is your project type ([utf8properties, properties, gettext, podir, xliff, xml, file])? +$ podir +[>] Project created. Now it's time to create a version to host your files. + +[?] What version ID/slug do you want to have: +$ master +[>] Version created. +``` + +the Zanata client will continue to ask questions and provide information on the next steps necessary to get you started with your project on Zanata. \ No newline at end of file diff --git a/docs/commands/pull.md b/docs/commands/pull.md new file mode 100644 index 00000000..b47451c4 --- /dev/null +++ b/docs/commands/pull.md @@ -0,0 +1,43 @@ +# Command: pull + +To download documents from your project-version, the command-line client's `pull` command can be used. + +These instructions assume that you have installed zanata-cli as shown in [Installing the Client](installation), and have saved user and project configuration as shown in [Configuring the Client][configuration]. + + +## Translation Document Download + +The basic command for downloading documents is `zanata-cli pull`. The pull command should always be run from the directory that contains `zanata.xml` for your project (find information about `zanata.xml` at [Configuring the Client][configuration]). + +At the time of writing, you will have to specify source and translation directories with the command, even though the default pull command will pull only translated documents from the server. This will be fixed in a future version. This means that the simplest pull command is: + +```bash +zanata-cli pull -s src -t trans +``` + + +This command will: + + 1. look up the locales to pull from `zanata.xml` (all the enabled locales by default). + 1. display the current settings and list of locales that will be downloaded. + 1. confirm that you want to proceed with the download. + 1. download translated versions of any documents that have any translations. + +Documents with no translations will not be downloaded unless specifically requested by adding the `--create-skeletons` option. + +To download only a few locales, use the `-l` or `--locales` option. For example, to download only Japanese and Russian translations, I might run `zanata-cli pull -s src -t trans -l ja,ru`. You can also modify the locales in `zanata.xml` if you will be consistently specifying a different set of locales. + +For a full list of the available options for pull, run `zanata-cli help pull` + + +## Source Document Download + +The pull command can also download source documents. This is generally only for reference purposes since source documents cannot be changed on the server. + +To pull translations instead of source documents, add the option `--pull-type source`, like so: + +``` +zanata-cli pull --pull-type source -s src -t source +``` + +To pull source and translation documents together, use `--pull-type both`. diff --git a/docs/commands/push.md b/docs/commands/push.md new file mode 100644 index 00000000..f04c7743 --- /dev/null +++ b/docs/commands/push.md @@ -0,0 +1,62 @@ +# Command: push + +To upload documents to your project-version, the command-line client's `push` command can be used. + +These instructions assume that you have installed zanata-cli as shown in [Installing the Client](installation), and have saved user and project configuration as shown in [Configuring the Client][]. + + + +## Source Document Upload + +The basic command for uploading documents is `zanata-cli push`. The push command should always be run from the directory that contains `zanata.xml` for your project (find information about `zanata.xml` at [Configuring the Client][configuration]). + +At the time of writing, you will have to specify source and translation directories with the command, even though the default push command will push only source documents to the server. This will be fixed in a future version. This means that the simplest push command is: + +`zanata-cli push -s src -t trans` + +This command will: + + 1. search for source documents in a directory named `src` and any of its subdirectories. + 1. display the current settings and list of source documents that were found. + 1. confirm that you want to proceed with the upload. + 1. upload the located source documents to the server. + +*Note:* if your source files are in the same directory as non-source files that have the same extension, such as when using Java `.properties` files for both translation and configuration, the `--includes` or `--excludes` option should be used to tell Zanata which files it should push. + +For a full list of the available options for push, run `zanata-cli help push` + + +## Translation Document Upload + +The push command can also upload translations. This is mainly for use when translation has started on your project before it has moved to Zanata. Translators can also use this command to upload translations, although translation on the Zanata website is safer. + +To push translations instead of source documents, add the option `--push-type trans`, like so: + +```bash +zanata-cli push --push-type trans -s src -t trans +``` + +To push source and translation documents together, use `--push-type both`. + +These commands will upload all available translations for the locales specified in `zanata.xml`, unless the `-l` or `--locales` option is used to specify a smaller set of locales. For example: `-l ja,de`. + +*Note:* translation documents must be named appropriately to match a source document. The appropriate name depends on your project type. For example, if the above command is used for a Java Properties project with a source document `src/strings/messages.properties`, a Japanese translation for the document would be at `trans/strings/messages_ja.properties`. + +```bash +src + strings + messages.properties +trans + strings + messages_ja.properties +``` + +If you are unsure about the layout and naming for translation files in the selected project type, you can do a trial pull and look at the output. This can be done by copying `zanata.xml` to an empty folder and running a pull command such as: + +```bash +zanata-cli pull -s src -t trans --create-skeletons +``` + +The option `--create-skeletons` is used to make sure files will be written even if there are no translations. + +For more information on the pull command, see [Document Download with Client](commands/pull). diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 00000000..ae69713f --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,122 @@ +# Configuring the Client + +zanata-cli requires User Configuration and Project-Version Configuration. + +## User Configuration + +User configuration stores your credentials so that zanata-cli can prove to the server that requests are from you rather than an imposter. The information in your user config should be kept secret. + +zanata-cli expects to find user configuration in `.config/zanata.ini` within your user directory. + +To add configuration for a Zanata server: + + 1. Use your favourite text editor to create or open `zanata.ini` in `~/.config/`. + 1. Sign into the Zanata server and navigate to the user settings page + 1. Ensure that an API Key is shown. If you do not have an API Key, click 'Generate API Key' now. +![User settings page](images/302-user-settings.png) + + 1. Copy the contents of the text-box labeled 'Configuration [zanata.ini]'. + 1. Paste the copied lines into `zanata.ini` and save the file. + + +## Project-Version Configuration + +Project configuration stores information about a project-version, and should be kept in the project directory. + +zanata-cli expects to find project-version configuration in a file named `zanata.xml` in the project directory. + +To add project-version configuration to your project directory: + + 1. Sign into the Zanata server and navigate to the appropriate version of your project. + 1. Click the `Download config file` link to initiate download of `zanata.xml`. +![Download config file link on version page](images/350-version-config-file.png) + + 1. Save `zanata.xml` in your project directory. + + +These steps should be repeated for each project-version before using any zanata-cli commands for the project-version. + +You can customize `zanata.xml` with command hooks so that other tools will automatically run before or after Zanata commands. Read about command hooks at the [command hook page on the wiki](https://github.com/zanata/zanata-server/wiki/Client-Command-Hooks). + + +## Locale Configuration + +The `zanata.xml` will contain a list of locales so that the client knows which locales to push and pull to/from the Zanata server. When downloaded from the Zanata server, the list will have the locales as specified by the server itself. It will look something like this: + +```xml + + es + ja + fr + zh-Hant-TW + ... + +``` + +Sometimes the way locales are named in your project files doesn't match Zanata's locale nomenclature, so it's necessary to create a mapping between the two. You can achieve this in the client by modifying the locale entries in `zanata.xml`. + +For instance, if one of your files is called `myfile/es.po` and your project in Zanata has the `es-ES` locale, then your client mappng would look like this: + +```xml + es-ES +``` + +### Translation files mapping rules + +You can also customize the way translation files are found when pushing, as well as the location they will be saved to when pulling. +{% highlight xml %} + + + {locale}/{path}/{filename}.po + {path}/{locale_with_underscore}.po + +{% endhighlight %} + +In the example above, `pattern` identifies a source file, and the contents of the `rule` element specify how translation files will be stored. + +The `pattern` attribute is a [glob](http://en.wikipedia.org/wiki/Glob_(programming)) matching pattern to your source document file(s). You can define more than one rule and apply each rule to a specific set of source documents using different patterns. The **first** matched rule will be applied to the file. + +`pattern` is optional. If not specified, the rule will be applied to all source documents in your project. +The actual rule consists of literal path and placeholders/variables. + +Supported placeholders/variables are: + + 1. **{path}** is the path between source document root (what you define as src-dir option) and the final file. + 1. **{filename}** the source document name without leading path and extension. + 1. **{locale}** the locale for the translation file. If you use "map-from" argument in your locale mapping, this will be the map-from value. + 1. **{locale\_with\_underscore}** same as above except all hyphens '-' will be replaced with underscores '_'. This is typically used in properties and gettext projects. + 1. **{extension}** the source document file extension + +For example, given a source document is found at `/home/user/myproject/src/main/resource/message.properties` + +... and your source document root (src-dir option) is set to "." + +... Your zanata.xml is located at `/home/user/myproject` + +... For a locale mapping defined as `zh`: + + +The following placeholders will be detected: + +``` +{path} = 'src/main/resource' +{filename} = 'message' +{locale} = 'zh-CN' +{locale\_with\_underscore} = 'zh_CN' +{extension} = 'properties' +``` + + +The mapping rules configuration is optional in zanata.xml. If not specified, standard rules are applied according to your [project type](https://github.com/zanata/zanata-server/wiki/Project-Types). + + 1. gettext: `{path}/{locale_with_underscore}.po` + 1. podir: `{locale}/{path}/{filename}.po` + 1. properties: `{path}/{filename}_{locale_with_underscore}.{extension}` + 1. utf8properties: `{path}/{filename}_{locale_with_underscore}.{extension}` + 1. xliff: `{path}/{filename}_{locale_with_underscore}.{extension}` + 1. xml: `{path}/{filename}_{locale_with_underscore}.{extension}` + 1. file: `{locale}/{path}/{filename}.{extension}` + +--- + +[Old instructions](https://github.com/zanata/zanata-server/wiki/Client-Configuration) diff --git a/docs/images/302-user-settings.png b/docs/images/302-user-settings.png new file mode 100644 index 0000000000000000000000000000000000000000..451b4aab8e4bcd4577c0672280660d5f572eb4b0 GIT binary patch literal 20604 zcmbrm1z1$!+BQ0f3Kr5xi%54j=upz#CEYo6sth7IAkrn>AR-`*5-UZ-5DYn5?OPM+d4QmcM0-qNX6B+nHyMKteQyonNn;P@$ote zS^v9E1A*-RGBd@7Kw=glkT(=q5Xh1s1mZ^Vzk8sSHW(IEVsbp3^{&_#8n;E={B-_+ z>f7L{*uqd)MBOYqzcX9P&*d*3P6x9Htngy8do&^v#+{39F7gG5isgJTo+4o|W7pBybEJ;h?Fnqt`+cpwyj zZ|kY1<*3mRk$#89;zzxbdh$gFsX2Z0e#_t;x-wN}S9*-rOE-a4txvpVszdklKIZSJ zSWnhV*$Zrocybj~Rx2&_H9Yi=oZm;m!ZGb z^wHVa9cF6qm;{``rtMphR?Ni3GD@-YkK8;FEYeN*ehP7N3mC3h;$*P}$i=Z*_p6K; zea(r_$VJ77`zc)XNfYmrUu5F0kmJoa3ouoc*2uM9XFeJs(i!78toj6oe{mpYj&V@0Ta;dXdYazGz*oqoQ(PSm?BKm|_w_3i8; z7Fy)L8hVLe6qzqqAyvP1BJG965~SmoW(sksn3+1q2@-aXzPERe_R=^-XsmxoQ*L-K zalax#vt)p?cj-O`Ld0D0OG}BEG+s(R$8!A8(sk|MwK#8)$>z&ira0PLjN#d~!fY*y z4fSEP&i+TGvSDfd@JxdRp?cYKA_m##Uw$2l@B%}xEA@?fJnEnvMz#*}Qb zkA!{f_bem>#B}_6;R-&yO69elw&PDo|IUulPLc-6J&RMY+=nG9e608sd2ip4%P+0d zDA-v-M7j{U=qgAWLIjU-&6DylJ)^ zZ#ZA(j5VAa|9;Y==WZb~wuU&V*^C&70?i>fZV@!gh*nx{m=+Ux+c!h8SK(E!^9KGP zuaH+=`|lUmbw#o32K#~z;n|0W-vwmewpm$Cp%0xNelRS-_+(|2Qk_b=ra@@QO2{d(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^B%TJgHKe)Gvht@&21DR- zwo)8sm1o$t(bRNyLF0M{5w*@xuT5UH^BSo2N?76}@nDdk%pxSpqyoy+AoX-nWMm{v zjF8~qH$=^wyY3?VZXg{@s9p|q)OydHa&UTpwSt#)yIaNMB`Z2M;J3jf$Zhv9%Z5Uy z((7nWxmtbEGw9RjIf!a75L;wa8qGM%6NL&CZiXL_P`$VeH#wBFAk{=y0&Zx#iOQ+$ zADVJWS!}4O5lVN_Jj|HPQBDeMZU78;dD>w(qbbPV&|N$YF72<<;o+CamiIBBj>uzl zI$fnCP^vl=PsmuBoE_VtoQ9`)1_cP6fntOmAMnDF1Pfp3$+>KwXVpl4_?sRg51sh< zc;Bvb#R_zyU;wjt>Ot;w&4MKn5AzI#fsTWZ=8F0E-6#&PjW8N zEX-2ozh2#?cWGkuK(luQ7V9Id^}E+~hOYKzTE+uz`2A+z zpQ3GidVvN?$SzH%>iD03Op>yc6i0fXZ*l<9XEBE>x}U>uU`Jc z)*C~PPbu`Ub2@VbWS5mi>$33G1K+Ivx9k7e1?bnu4+|^OidqaJ(svZWVSzfno<}?? I+`?1;0Sk8N;s5{u literal 0 HcmV?d00001 diff --git a/docs/images/350-version-config-file.png b/docs/images/350-version-config-file.png new file mode 100644 index 0000000000000000000000000000000000000000..5f8262ae187deee422695cdde8a00b27958a5983 GIT binary patch literal 10475 zcmcI~cTkgGx9&?*L=Y4Zq^opLKzavh(xnSXlU_sbO;nJs^d5@zrt}^W>Af35K)Of> zolsIve&_yk?>#g3JKxN?GjAr7Jv;kdd+oi}^Q>p@*q1tL6l4r!002;^zfjf(00LV4 zhl!LB-{SDDH4OhnOY?&V)RTx&p$;y~TSh>r(K+b23-S;!=Yv(}%lS^?ew8@ViH4}PMBl*_ue0u-M z&Ij2o9WsVMV}G^P3_GNTrf9zilxLL-{WOd~*frK;#zOst1*+gKH{Vm;4Xy|PifqVF z-cd=8Q9j=klqdb%hh|g0^Di5cnEx^>JWd^Dr2lL2M>sKRZ%8YZH zfpl-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*jis5Y;Nn^b;iZRS&K7KaKgNrg9NFqqVX}VZPw*_CsS6Rb^RaaJ!HY$&(c2U!Cn81jKWZ0=X_svxmS79c zleTWPnfHv`ay2VjE|i#2Tg^zk%IH&T68C11V??uY9uK<{!$!9i+k((W0qwu(|8o-f z@-n+*E<$$s4gfZhq+x1ihisgM45}=qk@s5}Cjfd+vns#J8YQ@Z!g>Nhb^B7E4+Mj;#U+s}Xl|x13unJh4SxesAKA2TxKSL!`gbE)$&@5Gk0}1%qmLJiB+2 zew^x1KYUJw^%@JlX7ASPMXwet;9mvO3-X}(5I46XHNbLuYV6K^&e<7dtn+ZmbP4uQ@fQPSR% zH@{AW=+yZeq(8P8bneg!_o(x}AlZ!;TAFe5%Xk}dkkyteWSt&c@t^cO>Y72+*uazU;N=LlZidY`ybWmEHH?_TQrfs2i zz$QIc3P5F5tt~A-|Bwy3_~!G+cQnCL$2RifrP5SB-wxd*9E2QLV} zXWu`-lOO>Yk)@&(^yesj)oi=66-xNL02SeC6U)oF$i5eRIBb(%?>}J9bds{guzpb-LK-QOizzMtjoKZ3GKYzVw z&p;cOl+PnEFj5M+f2kt1+u$yl5nyE{(tj!}ii1hWLy?z%bCyKoxao#JQvB2SZzAdc mhwE_v6Ibf~#Td)Dn>)ANypIj|(fHeofVzr~a@}+5sQ&;dXAnXF literal 0 HcmV?d00001 diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 00000000..0e67da93 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,34 @@ +Zanata Command line Client +============= + +The Zanata Command line client (CLI) is the perfect way to connect to a Zanata server to +push and pull content. + +Features +-------- + +- Initialize a Translation project from the command line. +- Push source content to the Zanata server. +- Pull translated content from the Zanata server. + +Installation +------------ + +For installation instructions please see the [Installation Section](installation) + +Contribute +---------- + +- Issue Tracker: http://bugzilla.redhat.com +- Source Code: github.com/zanata/zanata-client + +Support +------- + +If you are having issues, please let us know. +We have a mailing list located at: zanata-users@redhat.com + +License +------- + +The project is licensed under the BSD license. \ No newline at end of file diff --git a/docs/installation.md b/docs/installation.md new file mode 100644 index 00000000..bbca24e0 --- /dev/null +++ b/docs/installation.md @@ -0,0 +1,43 @@ +# Installation + +The Zanata client (zanata-cli) can be installed on most systems. Installation is easiest under Fedora, other systems can use Apache Ivy for installation. Manual installation is also possible. + + +## Installation on Fedora + +If you are using Fedora, zanata-cli is available through the `yum` package manager. + +```bash +sudo yum install zanata-client +``` + +## Installation with Ivy + +The Ivy distribution of the client is a small script that will download the client the first time it is run. This distribution requires Apache Ivy to run. + +Instructions for installing Apache Ivy and the Ivy version of zanata-cli can be found at [Zanata Ivy Client on github](https://github.com/zanata/zanata-client-ivy). + +*Note:* The Ivy client will download required files the first time it is run, which may take several minutes. It will show `resolving dependencies...` while this is happening. + +## Manual Installation + +To manually install zanata-cli: + + 1. Navigate to [zanata-cli on Maven Central](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.zanata%22%20AND%20a%3A%22zanata-cli%22). + 1. Download either `dist.zip` or `dist.tar.gz`. + + 1. Extract the contents of the archive to your location of choice. + 1. Create a symbolic link to the `zanata-cli` script in the bin directory of the extracted archive. e.g. from the archive directory, run `sudo ln -s bin/zanata-cli /usr/local/bin/zanata-cli`. + + 1. (optional) you can also enable tab-autocomplete for the client if you use bash as your terminal shell. This can be done by copying or linking the `zanata-cli-completion` script from the bin directory to `/etc/bash_completion.d/`. e.g. `ln -s bin/zanata-cli-completion /etc/bash_completion.d/zanata-cli-completion`. + +## Nightly Builds + +If you like to live dangerously, the client nightly relase is available. This may have newer features, but is not guaranteed to be stable. + +The latest nightly build is available as an archive that can be installed manually. To install the latest nightly build: + + 1. Open [Client nightly builds](http://repository-zanata.forge.cloudbees.com/snapshot/org/zanata/zanata-cli/). + 1. Open the directory showing the highest version number. + 1. Download either of the distributable archives (ending with `-dist.zip` or `-dist.tar.gz`). + 1. Install as per manual installation instructions above. \ No newline at end of file diff --git a/docs/maven-plugin/commands.md b/docs/maven-plugin/commands.md new file mode 100644 index 00000000..b2776835 --- /dev/null +++ b/docs/maven-plugin/commands.md @@ -0,0 +1,65 @@ +# Commands + +If your project uses Apache Maven, you can use Zanata's Maven Plugin rather than the command line client. The Maven Plugin can be used for non-Maven projects, but the same functionality is available in zanata-cli without the need to install or configure Maven. + +The following instructions assume that you have installed and configured the Zanata Maven Plugin. Instructions for installation and configuration are available at [Installing the Maven Plugin](maven-plugin/installation) and [Configuring the Maven Plugin](maven-plugin/configuration) + +## Basic Maven Plugin commands + +Commands and options for the Maven Plugin are similar to commands and options for zanata-cli, but with different syntax. + +### Help + +To see an overview of commands, use + +```bash +mvn zanata:help +``` + +and for detailed help for a particular command, use something like + +``` +mvn zanata:help -Ddetail=true -Dgoal=push +``` + +These are equivalent to commands `zanata-cli help` and `zanata-cli help push` in zanata-cli. + +*Note:* an online view of the same help information can be viewed at [Maven Plugin Reference](https://zanata.ci.cloudbees.com/job/zanata-client-site/site/zanata-maven-plugin/plugin-info.html). + +### Push + +The basic push command is + +```bash +mvn zanata:push +``` + +This will look for source documents in the location for `srcDir` specified in `pom.xml` and upload them to the server. If `srcDir` is not specified in `pom.xml`, the current directory will be used. + +The source directory can be overridden on the command line as shown here: + +```bash +mvn zanata:push -Dzanata.srcDir="src/messages" +``` + +This will look for source strings in "src/messages". + +More detail on the push command can be found at [Document Upload with Client](commands/push) + +### Pull + +The basic pull command is + +```bash +mvn zanata:pull +``` + +This will download translated documents from the server and save them in the location for `transDir` specified in `pom.xml`. If `transDir` is not specified in `pom.xml`, the current directory will be used. + +To download the source documents as well, specify pull type 'both' as shown here: + +```bash +mvn zanata:pull -Dzanata.pullType="both" +``` + +More detail on the pull command can be found at [Document Download with Client](commands/pull) diff --git a/docs/maven-plugin/configuration.md b/docs/maven-plugin/configuration.md new file mode 100644 index 00000000..f9f933b4 --- /dev/null +++ b/docs/maven-plugin/configuration.md @@ -0,0 +1,67 @@ +# Configuration + +To use the Maven Plugin, some Zanata configuration files and an installation of Apache Maven are needed. Some additional configuration will let you use a shorter command to run the Maven Plugin. + +For Apache Maven installation, see [Installing the Maven Plugin](maven-plugin/installation). + + +## Zanata Project Configuration + +The Zanata Maven plugin uses the general configuration files `zanata.ini` and `zanata.xml` in the same way as zanata-cli. For instructions on setting up these files, see [Configuring the Client](configuration). + +In addition, parameters such as source directory can be specified in `pom.xml` so that they are not needed on the command line. + + +## Command Configuration + +When Maven is installed, a verbose command can be used to run the Zanata Maven Plugin: + +```bash +mvn org.zanata:zanata-maven-plugin::help +``` + +The following instructions will allow the concise form of the command to be used instead: + +```bash +mvn zanata:help +``` + + +### Global Command Configuration + +To use the concise form of commands for any project, open `~/.m2/settings.xml` and ensure that pluginGroup `org.zanata` is present in pluginGroups: + +```xml + + ... + + org.zanata + ... + + ... + +``` + +This allows maven to use the latest version of the Zanata plugin when any `mvn zanata:*` command is run. + + +### Per-Project Command Configuration + +The plugin can be added to a single project by adding some elements to the project's `pom.xml` file. + +The following shows a build entry in `pom.xml` that will use version 3.4.0 of the Zanata plugin, and specifies the current directory (`.`) for source documents. This is equivalent to specifying the source directory on the command line as `-Dzanata.srcDir="."`. + +```xml + + + + org.zanata + zanata-maven-plugin + 3.4.0 + + . + + + + +``` diff --git a/docs/maven-plugin/installation.md b/docs/maven-plugin/installation.md new file mode 100644 index 00000000..dd4421f3 --- /dev/null +++ b/docs/maven-plugin/installation.md @@ -0,0 +1,32 @@ +# Installation + +If your project uses Apache Maven, you can use Zanata's Maven Plugin rather than the command line client. The Maven Plugin can be used for non-Maven projects, but the same functionality is available in zanata-cli without the need to install or configure Maven. + +With Maven installed, the plugin can be run in the verbose form with no additional setup, or can be set up to use the concise form globally or for a single poject. The first time a command is run, the plugin and all its dependencies will be downloaded, which may take a while. + +## Prerequisite - Install Maven + +Zanata Maven plugin requires Apache Maven to be installed. Maven can be downloaded from [The Apache Maven website](http://maven.apache.org/) or installed using your operating system's package manager (e.g. `yum install maven`). Other installation options can be found at [Zanata wiki - Maven Plugin](https://github.com/zanata/zanata-server/wiki/Zanata-Maven-Integration). + + +## Verbose Command (No Additional Setup) + +It is possible to run the Zanata plugin without any special setup once Maven is installed. + +This is done by specifying the full plugin id including version on the command line. For example, the help command can be run with: + +```bash +mvn org.zanata:zanata-maven-plugin::help +``` + +The instructions in other sections will assume that you are using the concise form of the command, so if you choose to use the verbose form you should use `mvn org.zanata:zanata-maven-plugin::` anywhere you see `mvn zanata:` in the instructions. + +## Concise Command + +Using global or per-project setup will allow the use of the concise form of the command, which would shorten the help command to: + +```bash +mvn zanata:help +``` + +See "Global Command Configuration" under [Configuring the Maven Plugin](maven-plugin/configuration) for details. diff --git a/mkdocs.yml b/mkdocs.yml new file mode 100644 index 00000000..25349569 --- /dev/null +++ b/mkdocs.yml @@ -0,0 +1,19 @@ +site_name: Zanata Client +docs_dir: docs +repo_name: GitHub +repo_url: http://www.github.com/zanata/zanata-client +theme: readthedocs +# theme_dir: For custom themes + +pages: +- ['index.md', 'Home'] +- ['installation.md', 'User Guide', 'Installation'] +- ['configuration.md', 'User Guide', 'Configuration'] +- ['maven-plugin/installation.md', 'Maven Plugin', 'Installation'] +- ['maven-plugin/configuration.md', 'Maven Plugin', 'Configuration'] +- ['maven-plugin/commands.md', 'Maven Plugin', 'Commands'] +- ['commands/init.md', 'Commands'] +- ['commands/push.md', 'Commands'] +- ['commands/pull.md', 'Commands'] + +copyright: Copyright © 2015, Red Hat. From 5c6712298a6ff1053a535fb142f8ba2a0070f81a Mon Sep 17 00:00:00 2001 From: Alex Eng Date: Tue, 27 Jan 2015 16:15:46 +1000 Subject: [PATCH 21/55] Add intelliJ file in git ignore --- .gitignore | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 6f7067af..e8a9842e 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,9 @@ .classpath .project .settings -*.iml */bin/ test-output/ + +# idea +*.idea/ +*.iml From d47e176e9223be0a0d0d12027a8a1a9df69439f5 Mon Sep 17 00:00:00 2001 From: Alex Eng Date: Thu, 5 Feb 2015 15:13:36 +1000 Subject: [PATCH 22/55] Add myTranslations options to push command https://bugzilla.redhat.com/show_bug.cgi?id=1184299 Squashed commit of the following: commit e0b4abbd972ce65ab19087bca9344035f6aabec2 Author: Alex Eng Date: Thu Feb 5 14:46:27 2015 +1000 Update client version to 3.7.0-SNAPSHOT, zanata-api to 3.7.0-SNAPSHOT commit c21a156264ef2fd6d29517e2bbeab65337351bea Merge: be52d4a b289753 Author: Alex Eng Date: Wed Jan 28 09:58:00 2015 +1000 Merge branch 'master' into rhbz1184299 commit be52d4a1a66da4dcf0d241dbacc7a76c74c06e12 Author: Alex Eng Date: Wed Jan 28 08:49:13 2015 +1000 Add myTranslations options to push command --- pom.xml | 4 ++-- stub-server/pom.xml | 2 +- .../service/MockAsynchronousProcessResource.java | 2 +- zanata-cli/pom.xml | 2 +- zanata-client-commands/pom.xml | 2 +- .../zanata/client/commands/push/PushCommand.java | 8 +++++--- .../zanata/client/commands/push/PushOptions.java | 2 ++ .../client/commands/push/PushOptionsImpl.java | 15 +++++++++++++++ .../java/org/zanata/client/MockServerRule.java | 5 +++-- .../client/commands/push/PushCommandTest.java | 4 ++-- .../PushPullFileProjectITCase.java | 2 +- .../PushPullGettextITCase.java | 2 +- zanata-maven-plugin/pom.xml | 2 +- .../java/org/zanata/maven/AbstractPushMojo.java | 12 ++++++++++++ zanata-rest-client/pom.xml | 2 +- .../zanata/rest/client/AsyncProcessClient.java | 3 ++- .../rest/client/AsyncProcessClientTest.java | 2 +- 17 files changed, 52 insertions(+), 19 deletions(-) rename zanata-client-commands/src/test/java/org/zanata/client/{integraion => integration}/PushPullFileProjectITCase.java (99%) rename zanata-client-commands/src/test/java/org/zanata/client/{integraion => integration}/PushPullGettextITCase.java (99%) diff --git a/pom.xml b/pom.xml index 41deda4d..1570ba56 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 client - 3.6.0-SNAPSHOT + 3.7.0-SNAPSHOT Zanata client modules pom @@ -35,7 +35,7 @@ - 3.6.0-SNAPSHOT + 3.7.0-SNAPSHOT 3.3.0 3.0.1.Final 1.17.1 diff --git a/stub-server/pom.xml b/stub-server/pom.xml index bcf57891..6de41aab 100644 --- a/stub-server/pom.xml +++ b/stub-server/pom.xml @@ -7,7 +7,7 @@ org.zanata client - 3.6.0-SNAPSHOT + 3.7.0-SNAPSHOT stub-server stub-server diff --git a/stub-server/src/main/java/org/zanata/rest/service/MockAsynchronousProcessResource.java b/stub-server/src/main/java/org/zanata/rest/service/MockAsynchronousProcessResource.java index 197e7763..0b0733f4 100644 --- a/stub-server/src/main/java/org/zanata/rest/service/MockAsynchronousProcessResource.java +++ b/stub-server/src/main/java/org/zanata/rest/service/MockAsynchronousProcessResource.java @@ -59,7 +59,7 @@ public ProcessStatus startSourceDocCreationOrUpdate(String idNoSlash, public ProcessStatus startTranslatedDocCreationOrUpdate(String idNoSlash, String projectSlug, String iterationSlug, LocaleId locale, TranslationsResource translatedDoc, Set extensions, - String merge) { + String merge, @DefaultValue("false") boolean myTrans) { ProcessStatus processStatus = new ProcessStatus(); processStatus.setStatusCode(ProcessStatus.ProcessStatusCode.Running); processStatus.setPercentageComplete(50); diff --git a/zanata-cli/pom.xml b/zanata-cli/pom.xml index 9e91baef..bf6cba58 100644 --- a/zanata-cli/pom.xml +++ b/zanata-cli/pom.xml @@ -4,7 +4,7 @@ org.zanata client - 3.6.0-SNAPSHOT + 3.7.0-SNAPSHOT zanata-cli Zanata command-line client diff --git a/zanata-client-commands/pom.xml b/zanata-client-commands/pom.xml index ddf791ef..c407c48b 100644 --- a/zanata-client-commands/pom.xml +++ b/zanata-client-commands/pom.xml @@ -4,7 +4,7 @@ org.zanata client - 3.6.0-SNAPSHOT + 3.7.0-SNAPSHOT zanata-client-commands Zanata client commands diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushCommand.java index b4fe7e1d..17c61b38 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushCommand.java @@ -654,7 +654,8 @@ private void pushTargetDocToServer(final String docUri, docUri, getOpts().getProj(), getOpts() .getProjectVersion(), new LocaleId(locale.getLocale()), targetDoc, - extensions, getOpts().getMergeType()); + extensions, getOpts().getMergeType(), + getOpts().isMyTrans()); boolean waitForCompletion = true; @@ -687,8 +688,9 @@ private void pushTargetDocToServer(final String docUri, getOpts().getProj(), getOpts() .getProjectVersion(), new LocaleId(locale.getLocale()), - targetDoc, extensions, getOpts() - .getMergeType()); + targetDoc, extensions, + getOpts().getMergeType(), + getOpts().isMyTrans()); ConsoleUtils .setProgressFeedbackMessage("Waiting for other clients ..."); break; diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushOptions.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushOptions.java index e7553e4b..34b24edd 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushOptions.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushOptions.java @@ -54,4 +54,6 @@ public interface PushOptions extends PushPullOptions { public String getValidate(); + public boolean isMyTrans(); + } diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushOptionsImpl.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushOptionsImpl.java index ba386fb3..947390f8 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushOptionsImpl.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushOptionsImpl.java @@ -40,6 +40,7 @@ public class PushOptionsImpl extends AbstractPushPullOptionsImpl private static final boolean DEF_CASE_SENSITIVE = true; private static final boolean DEF_EXCLUDE_LOCALES = true; private static final boolean DEF_COPYTRANS = true; + private static final boolean DEF_MY_TRANS = false; private static final int DEF_CHUNK_SIZE = 1024 * 1024; /** @see org.zanata.common.MergeType for options */ private static final String DEF_MERGE_TYPE = "AUTO"; @@ -58,6 +59,7 @@ public class PushOptionsImpl extends AbstractPushPullOptionsImpl private String sourceLang = "en-US"; private String validate; + private boolean myTrans = DEF_MY_TRANS; @Override public ZanataCommand initCommand() { @@ -242,4 +244,17 @@ void setValidate(String validate) { this.validate = validate; } + @Override + public boolean isMyTrans() { + return myTrans; + } + + @Option( + name = "--my-trans", + handler = BooleanValueHandler.class, + usage = "Indicates if all uploaded translations were translated by you " + + "(default: " + DEF_MY_TRANS + ")") + public void setMyTrans(boolean myTrans) { + this.myTrans = myTrans; + } } diff --git a/zanata-client-commands/src/test/java/org/zanata/client/MockServerRule.java b/zanata-client-commands/src/test/java/org/zanata/client/MockServerRule.java index 7d2d52de..f4389011 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/MockServerRule.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/MockServerRule.java @@ -184,7 +184,8 @@ public PushCommand createPushCommand() { docIdCaptor.capture(), eq(pushOpts.getProj()), eq(pushOpts.getProjectVersion()), localeIdCaptor.capture(), transResourceCaptor.capture(), - extensionCaptor.capture(), eq(pushOpts.getMergeType()))) + extensionCaptor.capture(), eq(pushOpts.getMergeType()), + eq(pushOpts.isMyTrans()))) .thenReturn(running); when(asyncClient.getProcessStatus(mockProcessId)) .thenReturn(finished); @@ -229,7 +230,7 @@ public void verifyPushTranslation() { docIdCaptor.capture(), eq(pushOpts.getProj()), eq(pushOpts.getProjectVersion()), localeIdCaptor.capture(), transResourceCaptor.capture(), extensionCaptor.capture(), - eq(pushOpts.getMergeType())); + eq(pushOpts.getMergeType()), eq(pushOpts.isMyTrans())); } public PullOptionsImpl getPullOpts() { diff --git a/zanata-client-commands/src/test/java/org/zanata/client/commands/push/PushCommandTest.java b/zanata-client-commands/src/test/java/org/zanata/client/commands/push/PushCommandTest.java index d80257bf..a71a9e66 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/commands/push/PushCommandTest.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/commands/push/PushCommandTest.java @@ -212,8 +212,8 @@ private void push(boolean pushTrans, boolean mapLocale) throws Exception { anyString(), anyString(), eq(expectedLocale), any(TranslationsResource.class), - eq(extensionSet), eq("auto"))).thenReturn( - mockStatus); + eq(extensionSet), eq("auto"), eq(false))). + thenReturn(mockStatus); // when(mockTranslationResources.putTranslations(eq("RPM"), // eq(expectedLocale), (TranslationsResource) notNull(), // eq(extensionSet), eq("auto"))) diff --git a/zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullFileProjectITCase.java b/zanata-client-commands/src/test/java/org/zanata/client/integration/PushPullFileProjectITCase.java similarity index 99% rename from zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullFileProjectITCase.java rename to zanata-client-commands/src/test/java/org/zanata/client/integration/PushPullFileProjectITCase.java index a5974127..5780e112 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullFileProjectITCase.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/integration/PushPullFileProjectITCase.java @@ -19,7 +19,7 @@ * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ -package org.zanata.client.integraion; +package org.zanata.client.integration; import java.io.File; import java.io.InputStream; diff --git a/zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullGettextITCase.java b/zanata-client-commands/src/test/java/org/zanata/client/integration/PushPullGettextITCase.java similarity index 99% rename from zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullGettextITCase.java rename to zanata-client-commands/src/test/java/org/zanata/client/integration/PushPullGettextITCase.java index 2449ea8a..4743e331 100644 --- a/zanata-client-commands/src/test/java/org/zanata/client/integraion/PushPullGettextITCase.java +++ b/zanata-client-commands/src/test/java/org/zanata/client/integration/PushPullGettextITCase.java @@ -1,4 +1,4 @@ -package org.zanata.client.integraion; +package org.zanata.client.integration; import java.io.File; import java.util.Set; diff --git a/zanata-maven-plugin/pom.xml b/zanata-maven-plugin/pom.xml index f6675664..c58980b1 100644 --- a/zanata-maven-plugin/pom.xml +++ b/zanata-maven-plugin/pom.xml @@ -4,7 +4,7 @@ org.zanata client - 3.6.0-SNAPSHOT + 3.7.0-SNAPSHOT zanata-maven-plugin diff --git a/zanata-maven-plugin/src/main/java/org/zanata/maven/AbstractPushMojo.java b/zanata-maven-plugin/src/main/java/org/zanata/maven/AbstractPushMojo.java index 80019be6..2915bc24 100644 --- a/zanata-maven-plugin/src/main/java/org/zanata/maven/AbstractPushMojo.java +++ b/zanata-maven-plugin/src/main/java/org/zanata/maven/AbstractPushMojo.java @@ -146,6 +146,14 @@ public PushPullCommand initCommand() { */ private String validate = "content"; + /** + * Indicates if all uploaded translations were translated by you. + * + * @parameter expression="${zanata.myTrans}" + * default-value="false" + */ + private boolean myTrans = false; + @Override public String getSourceLang() { return sourceLang; @@ -207,4 +215,8 @@ public String getValidate() { return validate; } + @Override + public boolean isMyTrans() { + return myTrans; + } } diff --git a/zanata-rest-client/pom.xml b/zanata-rest-client/pom.xml index 4cd18ffe..de822a67 100644 --- a/zanata-rest-client/pom.xml +++ b/zanata-rest-client/pom.xml @@ -6,7 +6,7 @@ org.zanata client - 3.6.0-SNAPSHOT + 3.7.0-SNAPSHOT jar diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/AsyncProcessClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/AsyncProcessClient.java index fb8f4401..d7c19bcf 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/AsyncProcessClient.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/AsyncProcessClient.java @@ -78,7 +78,7 @@ public ProcessStatus startSourceDocCreationOrUpdate(String idNoSlash, public ProcessStatus startTranslatedDocCreationOrUpdate(String idNoSlash, String projectSlug, String iterationSlug, LocaleId locale, TranslationsResource translatedDoc, Set extensions, - String merge) { + String merge, @DefaultValue("false") boolean myTrans) { Client client = factory.getClient(); CacheResponseFilter filter = new CacheResponseFilter(); client.addFilter(filter); @@ -91,6 +91,7 @@ public ProcessStatus startTranslatedDocCreationOrUpdate(String idNoSlash, webResource .queryParams(ClientUtil.asMultivaluedMap("ext", extensions)) .queryParam("merge", merge) + .queryParam("assignCreditToUploader", String.valueOf(myTrans)) .put(translatedDoc); client.removeFilter(filter); return filter.getEntity(ProcessStatus.class); diff --git a/zanata-rest-client/src/test/java/org/zanata/rest/client/AsyncProcessClientTest.java b/zanata-rest-client/src/test/java/org/zanata/rest/client/AsyncProcessClientTest.java index 71c0690a..bf9730be 100644 --- a/zanata-rest-client/src/test/java/org/zanata/rest/client/AsyncProcessClientTest.java +++ b/zanata-rest-client/src/test/java/org/zanata/rest/client/AsyncProcessClientTest.java @@ -67,7 +67,7 @@ public void testStartTranslatedDocCreationOrUpdate() throws Exception { "about-fedora", "master", LocaleId.DE, new TranslationsResource(), Sets.newHashSet("gettext"), - "auto"); + "auto", false); assertThat(processStatus.getStatusCode(), Matchers.equalTo( ProcessStatus.ProcessStatusCode.Running)); From 7059ecbd72a51100204ae949788ff0347433a99f Mon Sep 17 00:00:00 2001 From: Alex Eng Date: Fri, 20 Feb 2015 14:01:58 +1000 Subject: [PATCH 23/55] Update my-trans option when push - make it optional - output selected option before executing push Squashed commit of the following: commit 381ddacb7ad80e86f97cecdb61e8508bd15390bb Author: Alex Eng Date: Fri Feb 20 07:32:01 2015 +1000 Update my-trans option when push --- .../java/org/zanata/client/commands/push/PushCommand.java | 3 +++ .../java/org/zanata/client/commands/push/PushOptionsImpl.java | 4 +--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushCommand.java index 17c61b38..6c378a9e 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushCommand.java @@ -156,12 +156,15 @@ public static void logOptions(Logger logger, PushOptions opts) { logger.info("Pushing source and target documents"); logger.info("Locales to push: {}", opts.getLocaleMapList()); } + logger.info("Current directory: {}", System.getProperty("user.dir")); logger.info("Source directory (originals): {}", opts.getSrcDir()); if (opts.getPushType() == PushPullType.Both || opts.getPushType() == PushPullType.Trans) { logger.info("Target base directory (translations): {}", opts.getTransDir()); + + logger.info("Is my translations: {}", opts.isMyTrans()); } if (opts.getFromDoc() != null) { logger.info("From document: {}", opts.getFromDoc()); diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushOptionsImpl.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushOptionsImpl.java index 947390f8..bc97602c 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushOptionsImpl.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushOptionsImpl.java @@ -251,9 +251,7 @@ public boolean isMyTrans() { @Option( name = "--my-trans", - handler = BooleanValueHandler.class, - usage = "Indicates if all uploaded translations were translated by you " + - "(default: " + DEF_MY_TRANS + ")") + usage = "Indicates all uploaded translations were translated by you ") public void setMyTrans(boolean myTrans) { this.myTrans = myTrans; } From 6347270c831684a206853b8fe8e413e6f715b4e0 Mon Sep 17 00:00:00 2001 From: Patrick Huang Date: Fri, 9 Jan 2015 15:49:02 +1000 Subject: [PATCH 24/55] rhbz1156236 - deprecate locales in config file and fetch from server --- .../org/zanata/client/ZanataClientTest.java | 2 + .../zanata/client/commands/OptionsUtil.java | 48 +++++++++++++++- .../client/commands/PushPullCommand.java | 9 ++- .../client/commands/pull/PullOptionsImpl.java | 2 +- .../client/commands/push/PushOptionsImpl.java | 2 +- .../src/main/resources/prompts.properties | 2 + .../java/org/zanata/maven/PushMojoTest.java | 2 - .../java/org/zanata/maven/ZanataMojoTest.java | 5 +- .../client/ProjectIterationLocalesClient.java | 57 +++++++++++++++++++ .../zanata/rest/client/RestClientFactory.java | 5 ++ 10 files changed, 124 insertions(+), 10 deletions(-) create mode 100644 zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectIterationLocalesClient.java diff --git a/zanata-cli/src/test/java/org/zanata/client/ZanataClientTest.java b/zanata-cli/src/test/java/org/zanata/client/ZanataClientTest.java index 02b64399..2b8e0235 100644 --- a/zanata-cli/src/test/java/org/zanata/client/ZanataClientTest.java +++ b/zanata-cli/src/test/java/org/zanata/client/ZanataClientTest.java @@ -3,6 +3,7 @@ import java.io.StringWriter; import java.net.URL; +import org.hamcrest.CoreMatchers; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -183,6 +184,7 @@ Mockito. anyObject())).thenReturn( client.processArgs(command, "--url", url, "--project", project, "--project-version", version); + assertThat(err.toString(), CoreMatchers.is("")); verify(mockOptions).setUrl(new URL(url)); verify(mockOptions).setProj(project); verify(mockOptions).setProjectVersion(version); diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/OptionsUtil.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/OptionsUtil.java index 4bd5852f..af8f7e24 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/OptionsUtil.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/OptionsUtil.java @@ -2,6 +2,7 @@ import java.io.File; import java.net.URISyntaxException; +import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; @@ -15,14 +16,19 @@ import org.zanata.client.config.ConfigUtil; import org.zanata.client.config.FileMappingRule; import org.zanata.client.config.LocaleList; +import org.zanata.client.config.LocaleMapping; import org.zanata.client.config.ZanataConfig; import org.zanata.client.exceptions.ConfigException; +import org.zanata.rest.client.ProjectIterationLocalesClient; import org.zanata.rest.client.RestClientFactory; +import org.zanata.rest.dto.LocaleDetails; import org.zanata.util.VersionUtility; import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; import static org.zanata.client.commands.ConsoleInteractor.DisplayMode.Question; import static org.zanata.client.commands.ConsoleInteractor.DisplayMode.Warning; @@ -42,6 +48,7 @@ public class OptionsUtil { */ public static void applyConfigFiles(ConfigurableOptions opts) throws ConfigurationException, JAXBException { + boolean shouldFetchLocalesFromServer = false; if (opts instanceof ConfigurableProjectOptions) { ConfigurableProjectOptions projOpts = (ConfigurableProjectOptions) opts; @@ -59,6 +66,15 @@ public static void applyConfigFiles(ConfigurableOptions opts) // zanata.ini, // so we apply it first applyProjectConfig(projOpts, projectConfig); + boolean localesDefinedInFile = + projectConfig.getLocales() != null + && !projectConfig.getLocales().isEmpty(); + if (localesDefinedInFile) { + ConsoleInteractorImpl console = new ConsoleInteractorImpl(); + console.printfln(Warning, _("locales.in.config.deprecated")); + } else { + shouldFetchLocalesFromServer = true; + } } else { log.warn("Project config file '{}' not found; ignoring.", projectConfigFile); @@ -77,6 +93,34 @@ public static void applyConfigFiles(ConfigurableOptions opts) opts.getUserConfig()); } } + // we have to wait until user config has been applied + if (shouldFetchLocalesFromServer) { + ConfigurableProjectOptions projectOptions = + (ConfigurableProjectOptions) opts; + LocaleList localeMappings = fetchLocalesFromServer(projectOptions); + projectOptions.setLocaleMapList(localeMappings); + } + } + + private static LocaleList fetchLocalesFromServer( + ConfigurableProjectOptions projectOpts) { + LocaleList localeList = new LocaleList(); + ProjectIterationLocalesClient projectIterationLocalesClient = + createClientFactoryWithoutVersionCheck(projectOpts) + .getProjectLocalesClient(projectOpts.getProj(), + projectOpts.getProjectVersion()); + List localeMappings = + Lists.transform(projectIterationLocalesClient.getLocales(), + new Function() { + @Override + public LocaleMapping apply(LocaleDetails input) { + return input == null ? null : new LocaleMapping( + input.getLocaleId().getId(), + input.getAlias()); + } + }); + localeList.addAll(localeMappings); + return localeList; } /** @@ -101,8 +145,8 @@ private static void applyProjectConfig(ConfigurableProjectOptions opts, } applySrcDirAndTransDirFromProjectConfig(opts, config); applyIncludesAndExcludesFromProjectConfig(opts, config); - LocaleList locales = config.getLocales(); - opts.setLocaleMapList(locales); + LocaleList localesInFile = config.getLocales(); + opts.setLocaleMapList(localesInFile); if (opts.getCommandHooks().isEmpty() && config.getHooks() != null) { opts.setCommandHooks(config.getHooks()); diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/PushPullCommand.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/PushPullCommand.java index 5425839d..ac620ad0 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/PushPullCommand.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/PushPullCommand.java @@ -170,13 +170,15 @@ protected List getDocListForProjectIterationFromServer() { * Filters the project's list of locales * * @param projectLocales - * locales defined by the project's zanata.xml + * locales defined by the project on the server or in zanata.xml + * (only for backward compatibility) * @param locales * locales requested by the user (eg Maven param, command line * option) * @return the filtered list of locales * @throws ConfigException - * if one of the locales was not found in zanata.xml + * if one of the requested locales was not found on the server + * or in zanata.xml (only for backward compatibility) */ public static LocaleList getLocaleMapList(LocaleList projectLocales, String[] locales) { @@ -200,7 +202,8 @@ public static LocaleList getLocaleMapList(LocaleList projectLocales, if (!foundLocale) { throw new ConfigException("Specified locale '" + locale - + "' was not found in zanata.xml!"); + + "' was not found! Available locales: " + + projectLocales); } } return effectiveLocales; diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/pull/PullOptionsImpl.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/pull/PullOptionsImpl.java index 85ad86bb..42e22c4c 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/pull/PullOptionsImpl.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/pull/PullOptionsImpl.java @@ -73,7 +73,7 @@ public String getCommandDescription() { @Option(aliases = { "-l" }, name = "--locales", metaVar = "LOCALE1,LOCALE2", usage = "Locales to pull from the server.\n" - + "By default all locales in zanata.xml will be pulled.") + + "By default all locales configured will be pulled.") public void setLocales(String locales) { this.locales = locales.split(","); } diff --git a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushOptionsImpl.java b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushOptionsImpl.java index bc97602c..0c433529 100644 --- a/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushOptionsImpl.java +++ b/zanata-client-commands/src/main/java/org/zanata/client/commands/push/PushOptionsImpl.java @@ -94,7 +94,7 @@ public void setSourceLang(String sourceLang) { @Option(aliases = { "-l" }, name = "--locales", metaVar = "LOCALE1,LOCALE2,...", usage = "Locales to push to the server.\n" - + "By default all locales in zanata.xml will be pushed.") + + "By default all locales configured will be pushed.") public void setLocales(String locales) { this.locales = locales.split(","); } diff --git a/zanata-client-commands/src/main/resources/prompts.properties b/zanata-client-commands/src/main/resources/prompts.properties index 7f09c78b..dd829f05 100644 --- a/zanata-client-commands/src/main/resources/prompts.properties +++ b/zanata-client-commands/src/main/resources/prompts.properties @@ -89,3 +89,5 @@ no.default.mapping=Can not find default translation file mapping rule for projec invalid.rule=Rule defined is not valid (must contain locale): %s unrecognized.variables=Valid variables are %s. Anything else in '%s' will be treated as literal value. confirm.rule=Continue with current mapping rule(s) (y/n)? + +locales.in.config.deprecated=Locale mappings in project config file (zanata.xml) is deprecated! Please remove it from the file so that it can use latest language settins on the server. diff --git a/zanata-maven-plugin/src/test/java/org/zanata/maven/PushMojoTest.java b/zanata-maven-plugin/src/test/java/org/zanata/maven/PushMojoTest.java index 8be6f944..3d20bba2 100644 --- a/zanata-maven-plugin/src/test/java/org/zanata/maven/PushMojoTest.java +++ b/zanata-maven-plugin/src/test/java/org/zanata/maven/PushMojoTest.java @@ -1,7 +1,5 @@ package org.zanata.maven; -import java.util.Arrays; - import com.google.common.collect.ImmutableList; import org.zanata.client.commands.push.PushCommand; import org.zanata.client.commands.PushPullType; diff --git a/zanata-maven-plugin/src/test/java/org/zanata/maven/ZanataMojoTest.java b/zanata-maven-plugin/src/test/java/org/zanata/maven/ZanataMojoTest.java index ce34301c..b4a4ef89 100644 --- a/zanata-maven-plugin/src/test/java/org/zanata/maven/ZanataMojoTest.java +++ b/zanata-maven-plugin/src/test/java/org/zanata/maven/ZanataMojoTest.java @@ -1,6 +1,7 @@ package org.zanata.maven; import java.io.File; +import java.net.URL; import org.apache.maven.plugin.Mojo; import org.apache.maven.plugin.testing.AbstractMojoTestCase; @@ -34,7 +35,9 @@ protected void tearDown() throws Exception { } protected void applyPomParams(String pomFile) throws Exception { - File testPom = getTestFile("src/test/resources/push-test/" + pomFile); + URL resource = Thread.currentThread().getContextClassLoader() + .getResource("push-test/" + pomFile); + File testPom = new File(resource.getFile()); // This will work with "mvn test", but not with Eclipse's JUnit runner: // PushSimpleMojo mojo = (PushSimpleMojo) lookupMojo("push", testPom); // assertNotNull(mojo); diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectIterationLocalesClient.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectIterationLocalesClient.java new file mode 100644 index 00000000..dba4d105 --- /dev/null +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/ProjectIterationLocalesClient.java @@ -0,0 +1,57 @@ +/* + * Copyright 2014, Red Hat, Inc. and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.zanata.rest.client; + +import java.util.List; + +import org.zanata.rest.dto.LocaleDetails; + +import com.sun.jersey.api.client.GenericType; + +/** + * REST client for project iteration locales. + * + * @author Patrick Huang pahuang@redhat.com + */ +public class ProjectIterationLocalesClient { + private final RestClientFactory restClientFactory; + private final String projectSlug; + private final String versionSlug; + + public ProjectIterationLocalesClient(RestClientFactory restClientFactory, + String projectSlug, String versionSlug) { + this.restClientFactory = restClientFactory; + this.projectSlug = projectSlug; + this.versionSlug = versionSlug; + } + + public List getLocales() { + return restClientFactory.getClient() + .resource(restClientFactory.getBaseUri()) + .path("projects").path("p").path(projectSlug) + .path("iterations").path("i").path(versionSlug) + .path("locales") + .get(new GenericType>() { + }); + } +} diff --git a/zanata-rest-client/src/main/java/org/zanata/rest/client/RestClientFactory.java b/zanata-rest-client/src/main/java/org/zanata/rest/client/RestClientFactory.java index f40abe57..faac5150 100644 --- a/zanata-rest-client/src/main/java/org/zanata/rest/client/RestClientFactory.java +++ b/zanata-rest-client/src/main/java/org/zanata/rest/client/RestClientFactory.java @@ -257,6 +257,11 @@ public TransDocResourceClient getTransDocResourceClient(String projectSlug, return new TransDocResourceClient(this, projectSlug, versionSlug); } + public ProjectIterationLocalesClient getProjectLocalesClient( + String projectSlug, String versionSlug) { + return new ProjectIterationLocalesClient(this, projectSlug, versionSlug); + } + private static class AcceptAllX509TrustManager implements X509TrustManager { public X509Certificate[] getAcceptedIssuers() { return null; From fd98995ce965d5a3aa7450bff8c8407fc1f79be7 Mon Sep 17 00:00:00 2001 From: Sean Flanigan Date: Wed, 25 Feb 2015 12:24:22 +1000 Subject: [PATCH 25/55] Update parent to 21 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 1570ba56..796ef8b4 100644 --- a/pom.xml +++ b/pom.xml @@ -8,7 +8,7 @@ org.zanata zanata-parent - 21-SNAPSHOT + 21 ../parent From dd21226652f1ee7bd7f292db3e554635ac80b848 Mon Sep 17 00:00:00 2001 From: Carlos Munoz Date: Mon, 2 Mar 2015 10:57:16 +1000 Subject: [PATCH 26/55] Update licensing information. --- docs/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/index.md b/docs/index.md index 0e67da93..eabce928 100644 --- a/docs/index.md +++ b/docs/index.md @@ -31,4 +31,4 @@ We have a mailing list located at: zanata-users@redhat.com License ------- -The project is licensed under the BSD license. \ No newline at end of file +The project is licensed under the [LGPL 2.1 license](https://www.gnu.org/licenses/lgpl-2.1.html). From bc75d10e933c6fbf66116e61b6aca7b6b1944a5a Mon Sep 17 00:00:00 2001 From: David Mason Date: Mon, 2 Mar 2015 11:22:37 +1000 Subject: [PATCH 27/55] rhbz1156236 - Change deprecation warning message for locales in zanata.xml --- zanata-client-commands/src/main/resources/prompts.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zanata-client-commands/src/main/resources/prompts.properties b/zanata-client-commands/src/main/resources/prompts.properties index dd829f05..d9a93f5a 100644 --- a/zanata-client-commands/src/main/resources/prompts.properties +++ b/zanata-client-commands/src/main/resources/prompts.properties @@ -90,4 +90,4 @@ invalid.rule=Rule defined is not valid (must contain locale): %s unrecognized.variables=Valid variables are %s. Anything else in '%s' will be treated as literal value. confirm.rule=Continue with current mapping rule(s) (y/n)? -locales.in.config.deprecated=Locale mappings in project config file (zanata.xml) is deprecated! Please remove it from the file so that it can use latest language settins on the server. +locales.in.config.deprecated=Locale mappings are now handled using locale aliases on the server, so locale mappings in the project config file (zanata.xml) are now deprecated.\nPlease add a locale alias in the project language settings to replace each locale mapping in zanata.xml, then remove the section from zanata.xml. From fb21f723248d2ad7a147d88d648332e5cf2b91d9 Mon Sep 17 00:00:00 2001 From: Sean Flanigan Date: Mon, 2 Mar 2015 17:47:06 +1000 Subject: [PATCH 28/55] Sort zanata-cli-completion by option names --- .../org/zanata/client/BashCompletionGenerator.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/zanata-cli/src/test/java/org/zanata/client/BashCompletionGenerator.java b/zanata-cli/src/test/java/org/zanata/client/BashCompletionGenerator.java index 96b169b7..2a57bfa6 100644 --- a/zanata-cli/src/test/java/org/zanata/client/BashCompletionGenerator.java +++ b/zanata-cli/src/test/java/org/zanata/client/BashCompletionGenerator.java @@ -4,6 +4,7 @@ import java.io.IOException; import java.lang.reflect.AccessibleObject; import java.nio.charset.Charset; +import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Set; @@ -40,8 +41,15 @@ public class BashCompletionGenerator { private List baseCommands; private List