diff --git a/.gitignore b/.gitignore index 8eb5ff0b2..e2a23af44 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,6 @@ *.class -# Package Files # +# Package Files *.jar *.war *.ear @@ -11,6 +11,21 @@ .classpath .project -# IDEA project files +# IntelliJ +# User-specific stuff: +.idea +.idea/workspace.xml +.idea/tasks.xml +.idea/findbugs-idea.xml +.idea/codeStyleSettings.xml +.idea/dictionaries +.idea/shelf +*.iws +*.ipr *.iml -.idea \ No newline at end of file +# Sensitive or high-churn files: +.idea/dataSources.ids +.idea/dataSources.xml +.idea/sqlDataSources.xml +.idea/dynamic.xml +.idea/uiDesigner.xml \ No newline at end of file diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000..063139190 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,55 @@ +# The MIT License +# Copyright (c) 2012 Microsoft Corporation +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +language: java + +jdk: + - oraclejdk8 + - oraclejdk7 + - openjdk6 + +# enable container-based infrastructure +sudo: false + +env: + global: + - secure: "V37/WY3//w4fQUxmtKXw9dsU4iH5Z6HvTpBkZj+5DaX5h2Lj98FzALvkGSt7KvqVKQBbgETjs3HTMQkz6hwbLgX2okLKCQbmhZu3vQLqkWe6KPqnO1NOKSaU4vhCoGpScNWMiVxrzCHLHZf5tQu7d+1WVMk5GNlgGqeKVSnz5LY=" + - secure: "O9Mjx/mU5MLQsngcVbTf7AVMFo2Bh3ZWXwTyiLVXAfU7/VZX39vx30Mf2laNpewYqbiouix7fOkK76YS8459QRoLVBAQSwzjuGsZAwQvz7b7+r3kCS7rwGm7eCobJDbwItoxAxA00rI3gpyX/BnaX8aFutQw/0ZoPSPOH+LzR+4=" + +# cache local repository for speed of build +cache: + directories: + - $HOME/.m2/repository +before_cache: + - rm -rf $HOME/.m2/repository/com/microsoft/ews-java-api + +notifications: + webhooks: + urls: + - https://webhooks.gitter.im/e/04643d955d03eb39e24e + on_success: change + +before_install: + - chmod +x ./deploy_snapshot.sh + +after_success: + - bash <(curl -s https://codecov.io/bash) + - ./deploy_snapshot.sh diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c3b12aacf..9be0ef785 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,42 +1,4 @@ -## Contributing to Exchange Web Services Java API +## Contributing.md -There are several ways to contribute to the project: - -* Report bugs and features in the [issue tracker](https://github.com/officedev/ews-java-api/issues). -* Submit and review pull requests -* Help with documentation -* Help with testing - -GitHub supports [markdown](http://github.github.com/github-flavored-markdown/), so when filing bugs make sure you check the formatting before clicking submit. - -### Contributing code and content -Before submitting a feature or substantial code contribution please discuss it with the team and ensure it follows the product roadmap. You might also read these two blogs posts on contributing code: - -* [Open Source Contribution Etiquette](http://tirania.org/blog/archive/2010/Dec-31.html) by Miguel de Icaza -* [Don't "Push" Your Pull Requests](http://www.igvita.com/2011/12/19/dont-push-your-pull-requests/) by Ilya Grigorik. - -### Pull Requests -If you don't know what a pull request is read the "[Using pull requests](https://help.github.com/articles/using-pull-requests)" article. - -Some guidelines for pull requests: - -* Use a descriptive title and description. -* Include a single logical change. -* Base on master branch - once accepted, can be ported to stable branches. -* Should cleanly merge with target branch. - -### Commit Messages -1. Separate subject from body with a blank line -2. Limit the subject line to 50 characters -3. Capitalize the subject line -4. Do not end the subject line with a period -5. Use the imperative mood in the subject line (e.g. Fix #123: Make pigs fly). -6. Wrap the body at 72 characters -7. Use the body to explain what and why. The how should be mostly covered by the diff. - -References: - -* [How to Write a Git Commit Message](http://chris.beams.io/posts/git-commit/) -* [A Note About Git Commit Messages](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html) -* [Guidelines for Commit Messages](https://wiki.gnome.org/Git/CommitMessages) -* [On commit messages](http://who-t.blogspot.de/2009/12/on-commit-messages.html) +### To participate, please visit the project wiki for more information. +*Guidelines can be found* [**HERE**](https://github.com/OfficeDev/ews-java-api/wiki/Contributing) \ No newline at end of file diff --git a/deploy_snapshot.sh b/deploy_snapshot.sh new file mode 100644 index 000000000..09f13b0c5 --- /dev/null +++ b/deploy_snapshot.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +# The MIT License +# Copyright (c) 2012 Microsoft Corporation +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +if [ "$TRAVIS_REPO_SLUG" != "OfficeDev/ews-java-api" ]; then + echo "[DEPLOY] Skipping snapshot deployment for repo:'$TRAVIS_REPO_SLUG'." +elif [ "$TRAVIS_PULL_REQUEST" != "false" ]; then + echo "[DEPLOY] Skipping snapshot deployment for a pull request." +elif [ "$TRAVIS_SECURE_ENV_VARS" == "false" ]; then + echo "[DEPLOY] Skipping snapshot deployment due to TRAVIS_SECURE_ENV_VARS is set to '$TRAVIS_SECURE_ENV_VARS'." +elif [ "$TRAVIS_JDK_VERSION" != "oraclejdk7" ]; then + echo "[DEPLOY] Skipping snapshot deployment for jdk:'$TRAVIS_JDK_VERSION'." +else + echo "[DEPLOY] Deploying snapshot for commit:'$TRAVIS_COMMIT' @ build-id:'$TRAVIS_BUILD_ID'" + # create settings.xml + echo "ossrh-snapshot${OSSRHUSER}${OSSRHPASS}" > $HOME/.m2/settings.xml + # deploy + if [ -z "${GPG_PASSPHRASE+xxx}" ]; then + echo "[INFO] Deploying unsigned artifacts" + mvn clean deploy --settings="$HOME/.m2/settings.xml" -Dmaven.test.skip=true -Dcheckstyle.skip=true + else + echo "[INFO] Deploying signed artifacts" + mvn clean deploy --settings="$HOME/.m2/settings.xml" -Dmaven.test.skip=true -Dcheckstyle.skip=true -Dgpg.passphrase=$GPG_PASSPHRASE + fi + # clean up + rm -f $HOME/.m2/settings.xml +fi diff --git a/license.txt b/license.txt index d60bc954c..364ee36bf 100644 --- a/license.txt +++ b/license.txt @@ -1,22 +1,20 @@ -Exchange Web Services Java API +The MIT License +Copyright (c) 2012 Microsoft Corporation -Copyright (c) Microsoft Corporation -All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -MIT License +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. -Permission is hereby granted, free of charge, to any person obtaining a copy of this -software and associated documentation files (the ""Software""), to deal in the Software -without restriction, including without limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons -to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or -substantial portions of the Software. - -THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE -FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/pom.xml b/pom.xml index ee1d17dbc..e303359bc 100644 --- a/pom.xml +++ b/pom.xml @@ -1,12 +1,37 @@ + 4.0.0 - com.microsoft.office + com.microsoft.ews-java-api ews-java-api - 1.3-SNAPSHOT + + 2.1-SNAPSHOT Exchange Web Services Java API Exchange Web Services (EWS) Java API @@ -28,46 +53,344 @@ http://www.microsoft.com/ + + + vboctor + Victor Boctor + vboctor@users.noreply.github.com + http://www.github.com/officedev/ews-java-api + Microsoft + http://www.microsoft.com + + administrator + developer + + America/New_York + + http://www.example.com/jdoe/pic + + + + UTF-8 - 1.7 + 1.6 + + + + 2.16 + 1.6 + 2.10.3 + 3.3 + 1.6.5 + 2.4 + 1.14 + 1.1 + + 3.4 + 2.8 + 2.2 + 2.5 + 2.18.1 + 0.7.5.201505241946 + + 4.4.1 + 4.4.1 + 1.2 + 2.8 + 3.4 + 2.4 + + 4.12 + 1.3 + 1.10.19 + 1.7.12 + 1.1.3 + + + + default-jdk18-profile + + [1.8,) + + + -Xdoclint:none + + + + + java-7-or-later-profile + + [1.7,) + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + ${maven-checkstyle-plugin.version} + + true + google_checks.xml + + + + verify + + checkstyle + + + + + + + + + release-sign-artifacts + + + gpg.passphrase + + + + + + org.apache.maven.plugins + maven-gpg-plugin + ${maven-gpg-plugin.version} + + + sign-artifacts + verify + + sign + + + + + + + + + + + + MIT License + http://opensource.org/licenses/MIT + repo + + + + + https://github.com/OfficeDev/ews-java-api/issues + GitHub Issues + + + + travis + https://travis-ci.org/OfficeDev/ews-java-api + + + + https://github.com/OfficeDev/ews-java-api + scm:git:ssh://git@github.com:OfficeDev/ews-java-api.git + scm:git:ssh://git@github.com:OfficeDev/ews-java-api.git + + + + + ossrh-snapshot + https://oss.sonatype.org/content/repositories/snapshots + + + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2 + + + - commons-httpclient - commons-httpclient - 3.1 + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + + org.apache.httpcomponents + httpcore + ${httpcore.version} + + + + commons-io + commons-io + ${commons-io.version} commons-logging commons-logging - 1.2 + ${commons-logging.version} - jcifs - jcifs - 1.3.17 - - - javax.servlet - servlet-api - - + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + joda-time + joda-time + ${joda-time.version} junit junit - 4.11 + ${junit.version} + test + + + + org.hamcrest + hamcrest-all + ${hamcrest-all.version} + test + + + + org.mockito + mockito-core + ${mockito-core.version} + test + + + + org.slf4j + slf4j-api + ${slf4j.version} + test + + + + ch.qos.logback + logback-classic + ${logback.version} + test + + + + org.slf4j + jcl-over-slf4j + ${slf4j.version} + test + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + ${nexus-staging-maven-plugin.version} + true + + + true + ossrh + https://oss.sonatype.org/ + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${project.build.sourceEncoding} + ${javaLanguage.version} + ${javaLanguage.version} + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven-javadoc-plugin.version} + + true + ${javadoc.doclint.param} + + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + ${maven-source-plugin.version} + + + attach-sources + + jar-no-fork + + + + + + org.codehaus.mojo + animal-sniffer-maven-plugin + ${animal-sniffer-maven-plugin.version} + + + org.codehaus.mojo.signature + java16-sun + ${animal-sniffer-maven-plugin.signature.version} + + + + + check-java16-sun + test + + check + + + + + + + org.jacoco + jacoco-maven-plugin + ${jacoco-maven-plugin.version} + + + + prepare-agent + + + + report + test + + report + + + + + + @@ -76,7 +399,7 @@ org.apache.maven.plugins maven-site-plugin - 3.3 + ${maven-site-plugin.version} @@ -88,7 +411,7 @@ org.apache.maven.plugins maven-project-info-reports-plugin - 2.7 + ${maven-project-info-reports-plugin.version} Maven @@ -11,10 +35,8 @@ - - - \ No newline at end of file + diff --git a/src/test/java/microsoft/exchange/webservices/base/BaseTest.java b/src/test/java/microsoft/exchange/webservices/base/BaseTest.java new file mode 100644 index 000000000..46b07d915 --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/base/BaseTest.java @@ -0,0 +1,66 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.base; + +import microsoft.exchange.webservices.data.core.ExchangeService; +import microsoft.exchange.webservices.data.core.ExchangeServiceBase; +import microsoft.exchange.webservices.data.core.request.HttpWebRequest; +import org.junit.BeforeClass; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * A base class with "Common-Services" + */ +@RunWith(JUnit4.class) +public abstract class BaseTest { + + /** + * Mock for the ExchangeServiceBase + */ + protected static ExchangeServiceBase exchangeServiceBaseMock; + + /** + * Mock for the ExchangeService + */ + protected static ExchangeService exchangeServiceMock; + + /** + * Setup Mocks + * + * @throws Exception + */ + @BeforeClass + public static final void setUpBaseClass() throws Exception { + // Mock up ExchangeServiceBase + exchangeServiceBaseMock = new ExchangeServiceBase() { + @Override + protected void processHttpErrorResponse(HttpWebRequest httpWebResponse, Exception webException) + throws Exception { + throw webException; + } + }; + exchangeServiceMock = new ExchangeService(); + } +} diff --git a/src/test/java/microsoft/exchange/webservices/base/util/TestUtils.java b/src/test/java/microsoft/exchange/webservices/base/util/TestUtils.java new file mode 100644 index 000000000..3358ca533 --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/base/util/TestUtils.java @@ -0,0 +1,69 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.base.util; + +import org.junit.Assert; +import org.junit.Ignore; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Modifier; + +@Ignore +public final class TestUtils { + + private TestUtils() { + throw new UnsupportedOperationException(); + } + + + /** + * Check that class has only one private constructor without parameters that throws exception during + * instantiation. It's necessary for util-classes. + * + * @param utilClass util-class + * @throws Throwable exception during instantiation + */ + public static void checkUtilClassConstructor(final Class utilClass) throws Throwable { + // Check count of available constructors. + final Constructor[] constructors = utilClass.getDeclaredConstructors(); + Assert.assertEquals(1, constructors.length); + + // Check accessibility. + final Constructor constructor = constructors[0]; + Assert.assertTrue(Modifier.isPrivate(constructor.getModifiers())); + + // Try to create instance. + constructor.setAccessible(true); + try { + constructor.newInstance(); + } catch (final InvocationTargetException ex) { + throw ex.getTargetException(); + } + + // We should never get this situation. + Assert.fail(); + } + +} diff --git a/src/test/java/microsoft/exchange/webservices/data/EwsUtilitiesTest.java b/src/test/java/microsoft/exchange/webservices/data/EwsUtilitiesTest.java deleted file mode 100644 index 5ce0f4aab..000000000 --- a/src/test/java/microsoft/exchange/webservices/data/EwsUtilitiesTest.java +++ /dev/null @@ -1,21 +0,0 @@ -/************************************************************************** - * copyright file="EwsUtilitiesTest.java" company="Microsoft" - * Copyright (c) Microsoft Corporation. All rights reserved. - * - * Defines the EwsUtilitiesTest.java. - **************************************************************************/ - -package microsoft.exchange.webservices.data; - -import org.junit.Assert; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.junit.Test; - -@RunWith(JUnit4.class) -public class EwsUtilitiesTest { - @Test - public void testGetBuildVersion() { - Assert.assertEquals("Build version must be 0s", "0.0.0.0", EwsUtilities.getBuildVersion()); - } -} diff --git a/src/test/java/microsoft/exchange/webservices/data/autodiscover/AlternateMailboxCollectionTest.java b/src/test/java/microsoft/exchange/webservices/data/autodiscover/AlternateMailboxCollectionTest.java new file mode 100644 index 000000000..084bbfec8 --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/autodiscover/AlternateMailboxCollectionTest.java @@ -0,0 +1,87 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.autodiscover; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.io.ByteArrayInputStream; + +import org.junit.Test; + +import microsoft.exchange.webservices.data.core.EwsXmlReader; + +public class AlternateMailboxCollectionTest { + + private static final String PARTIAL_RESULT = + "" + + "http://schemas.microsoft.com/exchange/2010/Autodiscover/Autodiscover/GetUserSettingsResponse" + + "" + + "1501076" + + "0Exchange2013_SP1" + + "" + + "" + + "" + + "" + + "AlternateMailboxes" + + "Archive" + + "Personal Archive - Testaccount008" + + "ou=Exchange Administrative Group/cn=Testaccount008 Test" + + "cb7c4056-a738-4004-bd0d-65b58d3b7bc1@test.com" + + "testaccount008@test.com" + + "Delegate" + + "Testaccount007 Test" + + "testaccount007@test.com" + + "testaccount007@test.com" + + "" + + ""; + + + @Test + public void testGetEntries() throws Exception { + final AlternateMailboxCollection amc = + AlternateMailboxCollection.loadFromXml(new EwsXmlReader( + new ByteArrayInputStream(PARTIAL_RESULT.getBytes()))); + + assertEquals(2, amc.getEntries().size()); + + final AlternateMailbox first = amc.getEntries().get(0); + assertEquals("Archive", first.getType()); + assertEquals("Personal Archive - Testaccount008", first.getDisplayName()); + assertEquals("ou=Exchange Administrative Group/cn=Testaccount008 Test", + first.getLegacyDN()); + assertEquals("cb7c4056-a738-4004-bd0d-65b58d3b7bc1@test.com", + first.getServer()); + assertNull(first.getSmtpAddress()); + assertEquals("testaccount008@test.com", first.getOwnerSmtpAddress()); + + final AlternateMailbox second = amc.getEntries().get(1); + assertEquals("Delegate", second.getType()); + assertEquals("Testaccount007 Test", second.getDisplayName()); + assertNull(second.getLegacyDN()); + assertNull(second.getServer()); + assertEquals("testaccount007@test.com", second.getSmtpAddress()); + assertEquals("testaccount007@test.com", second.getOwnerSmtpAddress()); + } +} diff --git a/src/test/java/microsoft/exchange/webservices/data/autodiscover/AutodiscoverDnsClientTest.java b/src/test/java/microsoft/exchange/webservices/data/autodiscover/AutodiscoverDnsClientTest.java new file mode 100644 index 000000000..0e529b036 --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/autodiscover/AutodiscoverDnsClientTest.java @@ -0,0 +1,65 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.autodiscover; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class AutodiscoverDnsClientTest { + + final String validResponse = "autodiscover.contoso.com"; + final String trailingDotResponse = "autodiscover.contoso.com."; + + /** + * If DNS gives us a null, we should return a null + */ + @Test public void textExtractNullHostnameFromDnsSrv() { + assertEquals(AutodiscoverDnsClient.extractHostnameFromDnsSrv(null), null); + } + + /** + * If DNS gives us back an empty string, we should return a null + */ + @Test public void textExtractEmptyHostnameFromDnsSrv() { + assertEquals(AutodiscoverDnsClient.extractHostnameFromDnsSrv(""), null); + } + + /** + * If DNS gives us back a plain domain, we should pass it through. + */ + @Test public void textExtractValidHostnameFromDnsSrv() { + assertEquals(AutodiscoverDnsClient.extractHostnameFromDnsSrv(validResponse), validResponse); + } + + /** + * If DNS gives us back a domain with a trailing dot, we should strip it. + */ + @Test public void textExtractTrailingDotHostnameFromDnsSrv() { + assertEquals(AutodiscoverDnsClient.extractHostnameFromDnsSrv(trailingDotResponse), validResponse); + } +} diff --git a/src/test/java/microsoft/exchange/webservices/data/autodiscover/request/GetUserSettingsRequestTest.java b/src/test/java/microsoft/exchange/webservices/data/autodiscover/request/GetUserSettingsRequestTest.java new file mode 100644 index 000000000..717d88f79 --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/autodiscover/request/GetUserSettingsRequestTest.java @@ -0,0 +1,193 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.autodiscover.request; + + +import microsoft.exchange.webservices.base.BaseTest; +import microsoft.exchange.webservices.data.autodiscover.AutodiscoverService; +import microsoft.exchange.webservices.data.core.EwsServiceXmlWriter; +import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion; +import microsoft.exchange.webservices.data.core.exception.misc.ArgumentException; +import microsoft.exchange.webservices.data.core.exception.service.local.ServiceValidationException; +import microsoft.exchange.webservices.data.core.exception.service.local.ServiceXmlSerializationException; +import org.hamcrest.core.IsNot; +import org.hamcrest.core.IsNull; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import javax.xml.stream.XMLStreamException; + +import java.io.ByteArrayOutputStream; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +/** + * Testclass for methods of GetUserSettingsRequest + */ +@RunWith(Parameterized.class) +public class GetUserSettingsRequestTest extends BaseTest { + + /** + * The ExchangeVersion which is under test + */ + private final ExchangeVersion exchangeVersion; + + /** + * The AutodiscoverService which is under test + */ + private final AutodiscoverService autodiscoverService; + + /** + * A mocked URI via HTTPS + */ + private final URI uriMockHttps = URI.create("https://localhost"); + + /** + * A mocked URI via HTTP + */ + private final URI uriMockHttp = URI.create("http://localhost"); + + /** + * Returns the Parameters which where handled to the constructor + * + * @return the available Services + * @throws ArgumentException + */ + @Parameterized.Parameters + public static List getAutodiscoverServices() throws ArgumentException { + return new ArrayList() { + + /** + * Constant serialized ID used for compatibility. + */ + private static final long serialVersionUID = 1L; + + { + for (ExchangeVersion exchangeVersion : ExchangeVersion.values()) { + add(new Object[] {exchangeVersion, new AutodiscoverService(exchangeVersion)}); + } + } + }; + } + + /** + * Construct the Testobject with given Parameters + * + * @param exchangeVersion + * @param autodiscoverService + */ + public GetUserSettingsRequestTest(final ExchangeVersion exchangeVersion, + final AutodiscoverService autodiscoverService) { + this.exchangeVersion = exchangeVersion; + this.autodiscoverService = autodiscoverService; + } + + /** + * setup + */ + @Before + public void setup() { + Assert.assertThat(this.exchangeVersion, IsNull.notNullValue()); + Assert.assertThat(this.autodiscoverService, IsNull.notNullValue()); + Assert.assertThat(uriMockHttp, IsNull.notNullValue()); + Assert.assertThat(uriMockHttps, IsNull.notNullValue()); + } + + /** + * Nothing should be written to the OutputStream if expectPartnerToken is not set. + * + * @throws ServiceValidationException + * @throws XMLStreamException the XML stream exception + * @throws ServiceXmlSerializationException the service xml serialization exception + */ + @Test + public void testWriteExtraCustomSoapHeadersToXmlWithoutPartnertoken() + throws ServiceValidationException, XMLStreamException, ServiceXmlSerializationException { + // HTTPS + GetUserSettingsRequest getUserSettingsRequest = + new GetUserSettingsRequest(autodiscoverService, uriMockHttps); + + // Test without expected Partnertoken + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + getUserSettingsRequest.writeExtraCustomSoapHeadersToXml( + new EwsServiceXmlWriter(exchangeServiceBaseMock, byteArrayOutputStream)); + + // nothing should be writyen to the outputstream + Assert.assertArrayEquals(byteArrayOutputStream.toByteArray(), new ByteArrayOutputStream().toByteArray()); + + // HTTP + getUserSettingsRequest = new GetUserSettingsRequest(autodiscoverService, uriMockHttp); + + // Test without expected Partnertoken + byteArrayOutputStream = new ByteArrayOutputStream(); + getUserSettingsRequest.writeExtraCustomSoapHeadersToXml( + new EwsServiceXmlWriter(exchangeServiceBaseMock, byteArrayOutputStream)); + + // nothing should be written to the outputstream + Assert.assertArrayEquals(byteArrayOutputStream.toByteArray(), new ByteArrayOutputStream().toByteArray()); + } + + /** + * Test if content is added correctly if expectPartnerToken is set. + * + * @throws ServiceValidationException + * @throws XMLStreamException the XML stream exception + * @throws ServiceXmlSerializationException the service xml serialization exception + */ + @Test + public void testWriteExtraCustomSoapHeadersToXmlWithPartnertoken() + throws ServiceValidationException, XMLStreamException, ServiceXmlSerializationException { + GetUserSettingsRequest getUserSettingsRequest = + new GetUserSettingsRequest(autodiscoverService, uriMockHttps, Boolean.TRUE); + + // Test without expected Partnertoken + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + getUserSettingsRequest.writeExtraCustomSoapHeadersToXml( + new EwsServiceXmlWriter(exchangeServiceBaseMock, byteArrayOutputStream)); + + // data should be added the same way as mentioned + Assert.assertThat(byteArrayOutputStream.toByteArray(), + IsNot.not(new ByteArrayOutputStream().toByteArray())); + + //TODO Test if the output is really correct + } + + /** + * Initialising a GetUserSettingsRequest with Http should lead to an ServiceValidationException. + * + * @throws ServiceValidationException + * @throws XMLStreamException the XML stream exception + * @throws ServiceXmlSerializationException the service xml serialization exception + */ + @Test(expected = ServiceValidationException.class) + public void testWriteExtraCustomSoapHeadersToXmlWithPartnertoken2() + throws ServiceValidationException, XMLStreamException, ServiceXmlSerializationException { + GetUserSettingsRequest getUserSettingsRequest = + new GetUserSettingsRequest(autodiscoverService, uriMockHttp, Boolean.TRUE); + } +} diff --git a/src/test/java/microsoft/exchange/webservices/data/core/EwsUtilitiesTest.java b/src/test/java/microsoft/exchange/webservices/data/core/EwsUtilitiesTest.java new file mode 100644 index 000000000..b93023cea --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/core/EwsUtilitiesTest.java @@ -0,0 +1,205 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.core; + +import static org.junit.Assert.assertEquals; + +import microsoft.exchange.webservices.data.core.service.folder.CalendarFolder; +import microsoft.exchange.webservices.data.core.service.folder.ContactsFolder; +import microsoft.exchange.webservices.data.core.service.folder.Folder; +import microsoft.exchange.webservices.data.core.service.folder.SearchFolder; +import microsoft.exchange.webservices.data.core.service.folder.TasksFolder; +import microsoft.exchange.webservices.data.core.service.item.Appointment; +import microsoft.exchange.webservices.data.core.service.item.Contact; +import microsoft.exchange.webservices.data.core.service.item.ContactGroup; +import microsoft.exchange.webservices.data.core.service.item.Conversation; +import microsoft.exchange.webservices.data.core.service.item.EmailMessage; +import microsoft.exchange.webservices.data.core.service.item.Item; +import microsoft.exchange.webservices.data.core.service.item.MeetingCancellation; +import microsoft.exchange.webservices.data.core.service.item.MeetingMessage; +import microsoft.exchange.webservices.data.core.service.item.MeetingRequest; +import microsoft.exchange.webservices.data.core.service.item.MeetingResponse; +import microsoft.exchange.webservices.data.core.service.item.PostItem; +import microsoft.exchange.webservices.data.core.service.item.Task; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +@RunWith(JUnit4.class) +public class EwsUtilitiesTest { + + @Test + public void testGetBuildVersion() { + assertEquals("Build version must be 0s", "0.0.0.0", EwsUtilities.getBuildVersion()); + } + + @Test + public void testGetItemTypeFromXmlElementName() { + assertEquals(Task.class, EwsUtilities.getItemTypeFromXmlElementName("Task")); + assertEquals(EmailMessage.class, EwsUtilities.getItemTypeFromXmlElementName("Message")); + assertEquals(PostItem.class, EwsUtilities.getItemTypeFromXmlElementName("PostItem")); + assertEquals(SearchFolder.class, EwsUtilities.getItemTypeFromXmlElementName("SearchFolder")); + assertEquals(Conversation.class, EwsUtilities.getItemTypeFromXmlElementName("Conversation")); + assertEquals(Folder.class, EwsUtilities.getItemTypeFromXmlElementName("Folder")); + assertEquals(CalendarFolder.class, EwsUtilities.getItemTypeFromXmlElementName("CalendarFolder")); + assertEquals(MeetingMessage.class, EwsUtilities.getItemTypeFromXmlElementName("MeetingMessage")); + assertEquals(Contact.class, EwsUtilities.getItemTypeFromXmlElementName("Contact")); + assertEquals(Item.class, EwsUtilities.getItemTypeFromXmlElementName("Item")); + assertEquals(Appointment.class, EwsUtilities.getItemTypeFromXmlElementName("CalendarItem")); + assertEquals(ContactsFolder.class, EwsUtilities.getItemTypeFromXmlElementName("ContactsFolder")); + assertEquals(MeetingRequest.class, EwsUtilities.getItemTypeFromXmlElementName("MeetingRequest")); + assertEquals(TasksFolder.class, EwsUtilities.getItemTypeFromXmlElementName("TasksFolder")); + assertEquals(MeetingCancellation.class, EwsUtilities.getItemTypeFromXmlElementName("MeetingCancellation")); + assertEquals(MeetingResponse.class, EwsUtilities.getItemTypeFromXmlElementName("MeetingResponse")); + assertEquals(ContactGroup.class, EwsUtilities.getItemTypeFromXmlElementName("DistributionList")); + } + + @Test + public void testEwsAssert() { + EwsUtilities.ewsAssert(true, null, null); + + try { + EwsUtilities.ewsAssert(false, "a", "b"); + } catch (final RuntimeException ex) { + assertEquals("[a] b", ex.getMessage()); + } + } + + @Test + public void testParseBigInt() throws ParseException { + assertEquals(BigInteger.TEN, EwsUtilities.parse(BigInteger.class, BigInteger.TEN.toString())); + } + + @Test + public void testParseBigDec() throws ParseException { + assertEquals(BigDecimal.TEN, EwsUtilities.parse(BigDecimal.class, BigDecimal.TEN.toString())); + } + + @Test + public void testParseString() throws ParseException { + final String input = "lorem ipsum dolor sit amet"; + assertEquals(input, EwsUtilities.parse(input.getClass(), input)); + } + + @Test + public void testParseDouble() throws ParseException { + Double input = Double.MAX_VALUE; + assertEquals(input, EwsUtilities.parse(input.getClass(), input.toString())); + + input = 0.0; + assertEquals(input, EwsUtilities.parse(input.getClass(), input.toString())); + + input = Double.MIN_VALUE; + assertEquals(input, EwsUtilities.parse(input.getClass(), input.toString())); + } + + @Test + public void testParseInteger() throws ParseException { + Integer input = Integer.MAX_VALUE; + assertEquals(input, EwsUtilities.parse(input.getClass(), input.toString())); + + input = 0; + assertEquals(input, EwsUtilities.parse(input.getClass(), input.toString())); + + input = Integer.MIN_VALUE; + assertEquals(input, EwsUtilities.parse(input.getClass(), input.toString())); + } + + @Test + public void testParseBoolean() throws ParseException { + Boolean input = Boolean.TRUE; + assertEquals(input, EwsUtilities.parse(input.getClass(), input.toString())); + + input = Boolean.FALSE; + assertEquals(input, EwsUtilities.parse(input.getClass(), input.toString())); + } + + @Test + public void testParseLong() throws ParseException { + Long input = Long.MAX_VALUE; + assertEquals(input, EwsUtilities.parse(input.getClass(), input.toString())); + + input = 0l; + assertEquals(input, EwsUtilities.parse(input.getClass(), input.toString())); + + input = Long.MIN_VALUE; + assertEquals(input, EwsUtilities.parse(input.getClass(), input.toString())); + } + + @Test + public void testParseFloat() throws ParseException { + Float input = Float.MAX_VALUE; + assertEquals(input, EwsUtilities.parse(input.getClass(), input.toString())); + + input = 0f; + assertEquals(input, EwsUtilities.parse(input.getClass(), input.toString())); + + input = Float.MIN_VALUE; + assertEquals(input, EwsUtilities.parse(input.getClass(), input.toString())); + } + + @Test + public void testParseShort() throws ParseException { + Short input = Short.MAX_VALUE; + assertEquals(input, EwsUtilities.parse(input.getClass(), input.toString())); + + input = 0; + assertEquals(input, EwsUtilities.parse(input.getClass(), input.toString())); + + input = Short.MIN_VALUE; + assertEquals(input, EwsUtilities.parse(input.getClass(), input.toString())); + } + + @Test + public void testParseByte() throws ParseException { + Byte input = Byte.MAX_VALUE; + assertEquals(input, EwsUtilities.parse(input.getClass(), input.toString())); + + input = 0; + assertEquals(input, EwsUtilities.parse(input.getClass(), input.toString())); + + input = Byte.MIN_VALUE; + assertEquals(input, EwsUtilities.parse(input.getClass(), input.toString())); + } + + @Test + public void testParseDate() throws ParseException { + final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); + String input = sdf.format(new Date()); + assertEquals(input, EwsUtilities.parse(input.getClass(), input)); + } + + @Test + public void testParseNullValue() throws ParseException { + final String input = null; + assertEquals(input, EwsUtilities.parse(String.class, input)); + } + +} diff --git a/src/test/java/microsoft/exchange/webservices/data/core/EwsXmlReaderTest.java b/src/test/java/microsoft/exchange/webservices/data/core/EwsXmlReaderTest.java new file mode 100644 index 000000000..b84ed4b0a --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/core/EwsXmlReaderTest.java @@ -0,0 +1,102 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.core; + +import static org.mockito.Mockito.doReturn; + +import microsoft.exchange.webservices.data.security.XmlNodeType; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import javax.xml.stream.XMLEventReader; +import javax.xml.stream.events.Characters; +import javax.xml.stream.events.XMLEvent; + +import java.io.ByteArrayInputStream; + +public class EwsXmlReaderTest { + + @Mock(name="presentEvent") XMLEvent presentEvent; + @Mock(name="xmlReader") XMLEventReader xmlReader; + @InjectMocks EwsXmlReader impl; + @Mock Characters character; + + @Before + public void setUp() throws Exception { + impl = new EwsXmlReader(new ByteArrayInputStream(("" + + "").getBytes("UTF-8"))); + MockitoAnnotations.initMocks(this); + + } + + @Test + public void testReadValueWhenCharacterDataIsNull() throws Exception { + + doReturn(false).when(presentEvent).isStartElement(); + doReturn(XmlNodeType.CHARACTERS).when(presentEvent).getEventType(); + doReturn(true).when(presentEvent).isCharacters(); + doReturn(character).when(presentEvent).asCharacters(); + + //next event, then end event, then no more event + doReturn(true).doReturn(true).doReturn(false).when(xmlReader).hasNext(); + Characters nextEvent = Mockito.mock(Characters.class); + doReturn(true).when(nextEvent).isCharacters(); + doReturn(XmlNodeType.CHARACTERS).when(nextEvent).getEventType(); + XMLEvent endEvent = Mockito.mock(XMLEvent.class); + doReturn(nextEvent).doReturn(endEvent).when(xmlReader).nextEvent(); + doReturn(true).when(endEvent).isEndElement(); + + impl.readValue(true); //must not throw npe even if character.getData() is null + + Assert.assertNull(character.getData()); + } + + @Test + public void testReadValueWhenCharacterDataIsNullForStartElement() throws Exception { + + doReturn(true).when(presentEvent).isStartElement(); + doReturn(XmlNodeType.CHARACTERS).when(presentEvent).getEventType(); + doReturn(true).when(presentEvent).isCharacters(); + doReturn(character).when(presentEvent).asCharacters(); + + //next event, then end event, then no more event + doReturn(true).doReturn(true).doReturn(false).when(xmlReader).hasNext(); + Characters nextEvent = Mockito.mock(Characters.class); + doReturn(true).when(nextEvent).isCharacters(); + doReturn(XmlNodeType.CHARACTERS).when(nextEvent).getEventType(); + XMLEvent endEvent = Mockito.mock(XMLEvent.class); + doReturn(nextEvent).doReturn(endEvent).when(xmlReader).nextEvent(); + doReturn(true).when(endEvent).isEndElement(); + + impl.readValue(true); //must not throw npe even if character.getData() is null + + Assert.assertNull(character.getData()); + } + +} diff --git a/src/test/java/microsoft/exchange/webservices/data/core/LazyMemberTest.java b/src/test/java/microsoft/exchange/webservices/data/core/LazyMemberTest.java new file mode 100644 index 000000000..a3abf8848 --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/core/LazyMemberTest.java @@ -0,0 +1,95 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.core; + +import static org.junit.Assert.fail; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +public class LazyMemberTest { + + LazyMember impl; + + @Mock ILazyMember iLazyMember; + + @Before + public void setUp() throws Exception { + + MockitoAnnotations.initMocks(this); + impl = new LazyMember(iLazyMember); + + doReturn(new Object()).when(iLazyMember).createInstance(); + + } + + @Test public void testGetMember() throws Exception { + impl.getMember(); + impl.getMember(); + + //createInstance has been called only one time + verify(iLazyMember, times(1)).createInstance(); + + } + + @Test public void testGetMemberMultiThread() throws Exception { + final int poolSize = 3; + final CountDownLatch latch = new CountDownLatch(poolSize); + final ExecutorService pool = Executors.newFixedThreadPool(poolSize); + + final Runnable runnableUsingSingleton = new Runnable() { + @Override public void run() { + try { + //just to ensure all threads will try to get the signleton at the same time + latch.await(); + impl.getMember(); + } catch (InterruptedException e) { + fail(e.getMessage()); + } + } + }; + + for(int i = 0; i < poolSize; ++i) { + pool.submit(runnableUsingSingleton); + latch.countDown(); //decrease countdown + } + + pool.shutdown(); + pool.awaitTermination(3, TimeUnit.SECONDS); + + //createInstance has been called only one time + verify(iLazyMember, times(1)).createInstance(); + + } +} diff --git a/src/test/java/microsoft/exchange/webservices/data/core/PropertyBagTest.java b/src/test/java/microsoft/exchange/webservices/data/core/PropertyBagTest.java new file mode 100644 index 000000000..f811fb106 --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/core/PropertyBagTest.java @@ -0,0 +1,66 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.core; + +import microsoft.exchange.webservices.data.core.service.ServiceObject; +import microsoft.exchange.webservices.data.core.service.item.Item; +import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion; +import microsoft.exchange.webservices.data.core.exception.misc.ArgumentException; +import microsoft.exchange.webservices.data.core.exception.service.local.ServiceObjectPropertyException; +import microsoft.exchange.webservices.data.misc.OutParam; +import microsoft.exchange.webservices.data.property.definition.IntPropertyDefinition; +import microsoft.exchange.webservices.data.property.definition.RecurrencePropertyDefinition; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class PropertyBagTest { + + /** + * Calling tryGetPropertyType with invalid data. + * Expecting exception + * + * @throws Exception + */ + @Test(expected=ArgumentException.class) + public void tryGetPropertyType() throws Exception{ + PropertyBag pb = createPropertyBag(); + pb.tryGetPropertyType(String.class, new RecurrencePropertyDefinition("test", "none", null, ExchangeVersion.Exchange2010_SP2), new OutParam()); + } + + @Test(expected = ServiceObjectPropertyException.class) + public void testGetObjectFromPropertyDefinition() throws Exception { + PropertyBag pb = createPropertyBag(); + pb.getObjectFromPropertyDefinition(new IntPropertyDefinition("", "none", ExchangeVersion.Exchange2007_SP1)); + } + + + private PropertyBag createPropertyBag() throws Exception { + ExchangeService es = new ExchangeService(); + ServiceObject owner = new Item(es); + return new PropertyBag(owner); + } + +} diff --git a/src/test/java/microsoft/exchange/webservices/data/core/XSDurationTest.java b/src/test/java/microsoft/exchange/webservices/data/core/XSDurationTest.java new file mode 100644 index 000000000..f18445d6f --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/core/XSDurationTest.java @@ -0,0 +1,71 @@ +/* + * The MIT License Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.core; + +import microsoft.exchange.webservices.data.core.EwsUtilities; +import microsoft.exchange.webservices.data.misc.TimeSpan; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class XSDurationTest { + + // Tests for EwsUtilities.getXSDurationToTimeSpan() + + @Test + public void testPeriodHours() { + TimeSpan timeSpan = EwsUtilities.getXSDurationToTimeSpan("-PT13H"); + Assert.assertEquals("-P0DT13H0M0.0S", EwsUtilities.getTimeSpanToXSDuration(timeSpan)); + } + + @Test + public void testPeriodHoursMinutes() { + TimeSpan timeSpan = EwsUtilities.getXSDurationToTimeSpan("-PT5H30M"); + Assert.assertEquals("-P0DT5H30M0.0S", EwsUtilities.getTimeSpanToXSDuration(timeSpan)); + } + + @Test + public void testPeriodFull() { + TimeSpan timeSpan = EwsUtilities.getXSDurationToTimeSpan("PT2H30M59.0S"); + Assert.assertEquals("P0DT2H30M59.0S", EwsUtilities.getTimeSpanToXSDuration(timeSpan)); + } + + @Test + public void testPeriodFullNegative() { + TimeSpan timeSpan = EwsUtilities.getXSDurationToTimeSpan("-PT2H30M59.0S"); + Assert.assertEquals("-P0DT2H30M59.0S", EwsUtilities.getTimeSpanToXSDuration(timeSpan)); + } + + @Test + public void testPeriodFail2() { + TimeSpan timeSpan = EwsUtilities.getXSDurationToTimeSpan("PT2H100M59.0S"); + Assert.assertEquals("P0DT3H40M59.0S", EwsUtilities.getTimeSpanToXSDuration(timeSpan)); + } + + @Test(expected = IllegalArgumentException.class) + public void testPeriodFail() { + TimeSpan timeSpan = EwsUtilities.getXSDurationToTimeSpan("P2H30M59.0S"); + Assert.assertEquals("-P0DT2H30M59.0S", EwsUtilities.getTimeSpanToXSDuration(timeSpan)); + } + +} diff --git a/src/test/java/microsoft/exchange/webservices/data/core/service/items/AppointmentTest.java b/src/test/java/microsoft/exchange/webservices/data/core/service/items/AppointmentTest.java new file mode 100644 index 000000000..cb66e48cd --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/core/service/items/AppointmentTest.java @@ -0,0 +1,59 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.core.service.items; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; + +import microsoft.exchange.webservices.data.core.ExchangeService; +import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion; +import microsoft.exchange.webservices.data.core.service.item.Appointment; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + + +/** + * Testclass for methods of Appointment + */ +@RunWith(JUnit4.class) +public class AppointmentTest { + + private final ExchangeService exchangeService = mock(ExchangeService.class); + + @Test + public void testSetSubject() throws Exception { + doReturn(ExchangeVersion.Exchange2010_SP2).when(exchangeService).getRequestedServerVersion(); + + Appointment appointment = new Appointment(exchangeService); + + final String subject = "Lorem Ipsum"; + appointment.setSubject(subject); + + assertThat(appointment.getSubject(), is(equalTo(subject))); + } +} diff --git a/src/test/java/microsoft/exchange/webservices/data/core/service/items/TaskTest.java b/src/test/java/microsoft/exchange/webservices/data/core/service/items/TaskTest.java new file mode 100644 index 000000000..524b4a07e --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/core/service/items/TaskTest.java @@ -0,0 +1,171 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.core.service.items; + +import static org.junit.Assert.assertThat; + +import microsoft.exchange.webservices.base.BaseTest; +import microsoft.exchange.webservices.data.core.service.item.Task; +import microsoft.exchange.webservices.data.core.exception.service.local.ServiceObjectPropertyException; +import org.hamcrest.core.IsEqual; +import org.hamcrest.core.IsInstanceOf; +import org.hamcrest.core.IsNot; +import org.hamcrest.core.IsNull; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Testclass for methods of Task + */ +@RunWith(JUnit4.class) +public class TaskTest extends BaseTest { + + /** + * Mock for the Task + */ + private Task taskMock; + + /** + * Setup Mocks + * + * @throws Exception + */ + @Before + public void setup() throws Exception { + this.taskMock = new Task(TaskTest.exchangeServiceMock); + } + + /** + * Test for reading the value before it is assigned + * + * @throws Exception + */ + @Test(expected = ServiceObjectPropertyException.class) + public void testInitialValuePercent() throws Exception { + taskMock.getPercentComplete(); + } + + /** + * Test for adding 0.0 as percentCompleted + * + * @throws Exception + */ + @Test + public void testAddZeroPercent() throws Exception { + final Double targetValue = 0.0; + taskMock.setPercentComplete(targetValue); + + assertThat(taskMock.getPercentComplete(), IsNot.not(IsNull.nullValue())); + assertThat(taskMock.getPercentComplete(), IsInstanceOf.instanceOf(Double.class)); + assertThat(taskMock.getPercentComplete(), IsEqual.equalTo(targetValue)); + } + + /** + * Test for adding 100.0 as percentCompleted + * + * @throws Exception + */ + @Test + public void testAdd100Percent() throws Exception { + final Double targetValue = 100.0; + taskMock.setPercentComplete(targetValue); + + assertThat(taskMock.getPercentComplete(), IsNot.not(IsNull.nullValue())); + assertThat(taskMock.getPercentComplete(), IsInstanceOf.instanceOf(Double.class)); + assertThat(taskMock.getPercentComplete(), IsEqual.equalTo(targetValue)); + } + + /** + * Test for adding Double.MAX_VALUE as percentCompleted + * + * @throws Exception + */ + @Test(expected = IllegalArgumentException.class) + public void testAddMaxDoublePercent() throws Exception { + final Double targetValue = Double.MAX_VALUE; + taskMock.setPercentComplete(targetValue); + } + + /** + * Test for adding -0.1 as percentCompleted + * + * @throws Exception + */ + @Test(expected = IllegalArgumentException.class) + public void testAddInvalidPercent() throws Exception { + final Double targetValue = -0.1; + taskMock.setPercentComplete(targetValue); + } + + /** + * Test for adding +100.1 as percentCompleted + * + * @throws Exception + */ + @Test(expected = IllegalArgumentException.class) + public void testAddInvalidPercent2() throws Exception { + final Double targetValue = +100.1; + taskMock.setPercentComplete(targetValue); + } + + /** + * Test for adding Double.NaN as percentCompleted + * + * @throws Exception + */ + @Test(expected = IllegalArgumentException.class) + public void testAddNanDoublePercent() throws Exception { + final Double targetValue = Double.NaN; // closest Value to Zero + taskMock.setPercentComplete(targetValue); + } + + /** + * Test for checking if the value changes in case of a thrown exception + * + * @throws Exception + */ + @Test + public void testDontChangeValueOnException() throws Exception { + // set valid value + final Double targetValue = 50.5; + taskMock.setPercentComplete(targetValue); + + assertThat(taskMock.getPercentComplete(), IsNot.not(IsNull.nullValue())); + assertThat(taskMock.getPercentComplete(), IsInstanceOf.instanceOf(Double.class)); + assertThat(taskMock.getPercentComplete(), IsEqual.equalTo(targetValue)); + + final Double invalidValue = -0.1; + try { + taskMock.setPercentComplete(invalidValue); + } catch (IllegalArgumentException ex) { + // ignored + } + + assertThat(taskMock.getPercentComplete(), IsNot.not(IsNull.nullValue())); + assertThat(taskMock.getPercentComplete(), IsInstanceOf.instanceOf(Double.class)); + assertThat(taskMock.getPercentComplete(), IsEqual.equalTo(targetValue)); + } +} diff --git a/src/test/java/microsoft/exchange/webservices/data/credential/WSSecurityBasedCredentialsTest.java b/src/test/java/microsoft/exchange/webservices/data/credential/WSSecurityBasedCredentialsTest.java new file mode 100644 index 000000000..317e0fddd --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/credential/WSSecurityBasedCredentialsTest.java @@ -0,0 +1,103 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.credential; + +import static org.hamcrest.CoreMatchers.allOf; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.core.StringContains.containsString; +import static org.hamcrest.text.IsEmptyString.isEmptyOrNullString; +import static org.junit.Assert.assertThat; + +import microsoft.exchange.webservices.data.core.EwsUtilities; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; + +@RunWith(JUnit4.class) public class WSSecurityBasedCredentialsTest { + + private static final Log LOG = LogFactory.getLog(WSSecurityBasedCredentialsTest.class); + + private WSSecurityBasedCredentials wsSecurityBasedCredentials; + private XMLStreamWriter xmlStreamWriter = null; + private Writer stringWriter = null; + + @Before public void initTest() throws XMLStreamException { + // testObject + wsSecurityBasedCredentials = new WSSecurityBasedCredentials() { + + }; + + // testContext + stringWriter = new StringWriter(); + xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(stringWriter); + } + + @After public void tearDown() { + if (stringWriter != null) { + try { + stringWriter.close(); + } catch (IOException e) { + LOG.warn(e.getMessage(), e); + } + } + if (xmlStreamWriter != null) { + try { + xmlStreamWriter.close(); + } catch (XMLStreamException e) { + LOG.warn(e.getMessage(), e); + } + } + } + + @Test public void testEmitExtraSoapHeaderNamespaceAliases() throws XMLStreamException, IOException { + xmlStreamWriter.writeStartDocument(); + xmlStreamWriter.writeStartElement("test"); + + wsSecurityBasedCredentials.emitExtraSoapHeaderNamespaceAliases(xmlStreamWriter); + + xmlStreamWriter.writeEndElement(); + xmlStreamWriter.writeEndDocument(); + xmlStreamWriter.flush(); + + assertThat(stringWriter.toString(), + allOf(not(isEmptyOrNullString()), containsString("xmlns"), containsString("test"), + containsString(EwsUtilities.WSSecuritySecExtNamespacePrefix), + containsString(EwsUtilities.WSAddressingNamespacePrefix), + containsString(EwsUtilities.WSSecuritySecExtNamespace), + containsString(EwsUtilities.WSAddressingNamespace))); + } + +} diff --git a/src/test/java/microsoft/exchange/webservices/data/dns/DnsClientTest.java b/src/test/java/microsoft/exchange/webservices/data/dns/DnsClientTest.java new file mode 100644 index 000000000..9e866f219 --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/dns/DnsClientTest.java @@ -0,0 +1,49 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.dns; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.Hashtable; + +public class DnsClientTest { + @Test public void getEnvShouldSetNaming() { + Hashtable env = DnsClient.getEnv(""); + Assert.assertEquals(env.get("java.naming.factory.initial"), + "com.sun.jndi.dns.DnsContextFactory"); + } + + @Test public void getEnvShouldNotSetProviderUrl() throws Exception { + Hashtable env = DnsClient.getEnv(""); + Assert.assertFalse(env.containsKey("java.naming.provider.url")); + env = DnsClient.getEnv(null); + Assert.assertFalse(env.containsKey("java.naming.provider.url")); + } + + @Test public void getEnvShoulSetProviderUrl() throws Exception { + Hashtable env = DnsClient.getEnv("1.1.1.1"); + Assert.assertEquals(env.get("java.naming.provider.url"), "dns://1.1.1.1"); + } +} diff --git a/src/test/java/microsoft/exchange/webservices/data/exception/InvalidOrUnsupportedTimeZoneDefinitionExceptionTest.java b/src/test/java/microsoft/exchange/webservices/data/exception/InvalidOrUnsupportedTimeZoneDefinitionExceptionTest.java new file mode 100644 index 000000000..93d4f8c2b --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/exception/InvalidOrUnsupportedTimeZoneDefinitionExceptionTest.java @@ -0,0 +1,65 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.exception; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; + +import microsoft.exchange.webservices.data.core.exception.service.local.InvalidOrUnsupportedTimeZoneDefinitionException; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class InvalidOrUnsupportedTimeZoneDefinitionExceptionTest { + + private final String msg = "some message"; + private final Exception rootCause = new Exception(); + + + @Test public void testInvalidOrUnsupportedTimeZoneDefinitionExceptionStringException() { + InvalidOrUnsupportedTimeZoneDefinitionException + impl = + new InvalidOrUnsupportedTimeZoneDefinitionException(msg, rootCause); + assertEquals(msg, impl.getMessage()); + assertSame(rootCause, impl.getCause()); + } + + @Test public void testInvalidOrUnsupportedTimeZoneDefinitionExceptionString() { + InvalidOrUnsupportedTimeZoneDefinitionException + impl = + new InvalidOrUnsupportedTimeZoneDefinitionException(msg); + assertEquals(msg, impl.getMessage()); + assertNull(impl.getCause()); + } + + @Test public void testInvalidOrUnsupportedTimeZoneDefinitionException() { + InvalidOrUnsupportedTimeZoneDefinitionException + impl = + new InvalidOrUnsupportedTimeZoneDefinitionException(); + assertNull(impl.getMessage()); + assertNull(impl.getCause()); + } +} diff --git a/src/test/java/microsoft/exchange/webservices/data/exception/MaximumRedirectionHopsExceededExceptionTest.java b/src/test/java/microsoft/exchange/webservices/data/exception/MaximumRedirectionHopsExceededExceptionTest.java new file mode 100644 index 000000000..5ae191821 --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/exception/MaximumRedirectionHopsExceededExceptionTest.java @@ -0,0 +1,65 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.exception; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; + +import microsoft.exchange.webservices.data.autodiscover.exception.MaximumRedirectionHopsExceededException; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class MaximumRedirectionHopsExceededExceptionTest { + + private final String msg = "some message"; + private final Exception rootCause = new Exception(); + + + @Test public void testMaximumRedirectionHopsExceededException() { + + MaximumRedirectionHopsExceededException impl = new MaximumRedirectionHopsExceededException(); + assertNull(impl.getMessage()); + assertNull(impl.getCause()); + } + + @Test public void testMaximumRedirectionHopsExceededExceptionString() { + + MaximumRedirectionHopsExceededException impl = new MaximumRedirectionHopsExceededException(msg); + assertEquals(msg, impl.getMessage()); + assertNull(impl.getCause()); + } + + @Test public void testMaximumRedirectionHopsExceededExceptionStringException() { + + MaximumRedirectionHopsExceededException + impl = + new MaximumRedirectionHopsExceededException(msg, rootCause); + assertEquals(msg, impl.getMessage()); + assertSame(rootCause, impl.getCause()); + } + +} diff --git a/src/test/java/microsoft/exchange/webservices/data/misc/IFunctionsTest.java b/src/test/java/microsoft/exchange/webservices/data/misc/IFunctionsTest.java new file mode 100644 index 000000000..4ee453423 --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/misc/IFunctionsTest.java @@ -0,0 +1,104 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.misc; + +import microsoft.exchange.webservices.data.core.EwsUtilities; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.codec.binary.StringUtils; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.Date; +import java.util.UUID; + +@RunWith(JUnit4.class) +public class IFunctionsTest { + + @Test + public void testToString() { + final IFunctions.ToString f = IFunctions.ToString.INSTANCE; + Assert.assertEquals("null", f.func(null)); + Assert.assertEquals("", f.func("")); + Assert.assertEquals("1", f.func(1)); + } + + @Test + public void testToBoolean() { + final IFunctions.ToBoolean f = IFunctions.ToBoolean.INSTANCE; + Assert.assertFalse(f.func(null)); + Assert.assertFalse(f.func("")); + Assert.assertFalse(f.func("false")); + Assert.assertTrue(f.func("true")); + } + + @Test + public void testStringToObject() { + final IFunctions.StringToObject f = IFunctions.StringToObject.INSTANCE; + Assert.assertNull(f.func(null)); + Assert.assertEquals("", f.func("")); + } + + @Test + public void testToUUID() { + final IFunctions.ToUUID f = IFunctions.ToUUID.INSTANCE; + try { + Assert.assertNull(f.func(null)); + } catch (final Throwable ex) { + final UUID uuid = UUID.randomUUID(); + Assert.assertEquals(uuid, f.func(uuid.toString())); + } + } + + @Test + public void testBase64Decoder() { + final String value = "123"; + final IFunctions.Base64Decoder f = IFunctions.Base64Decoder.INSTANCE; + Assert.assertArrayEquals(Base64.decodeBase64(value), (byte[]) f.func(value)); + } + + @Test + public void testBase64Encoder() { + final byte[] value = StringUtils.getBytesUtf8("123"); + final IFunctions.Base64Encoder f = IFunctions.Base64Encoder.INSTANCE; + Assert.assertEquals(Base64.encodeBase64String(value), f.func(value)); + } + + @Test + public void testToLowerCase() { + final IFunctions.ToLowerCase f = IFunctions.ToLowerCase.INSTANCE; + Assert.assertNull(f.func(null)); + Assert.assertEquals("", f.func("")); + Assert.assertEquals("abc", f.func("AbC")); + } + + @Test + public void testDateTimeToXSDateTime() { + final IFunctions.DateTimeToXSDateTime f = IFunctions.DateTimeToXSDateTime.INSTANCE; + final Date value = new Date(); + Assert.assertEquals(EwsUtilities.dateTimeToXSDateTime(value), f.func(value)); + } + +} diff --git a/src/test/java/microsoft/exchange/webservices/data/misc/TimeSpanTest.java b/src/test/java/microsoft/exchange/webservices/data/misc/TimeSpanTest.java new file mode 100644 index 000000000..22eb337c9 --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/misc/TimeSpanTest.java @@ -0,0 +1,64 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.misc; + +import microsoft.exchange.webservices.base.BaseTest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.Calendar; +import java.util.GregorianCalendar; + +/** + * The Class TimeSpanTest. + */ +@RunWith(JUnit4.class) +public class TimeSpanTest extends BaseTest { + + /** + * testTimeSpanToXSDuration + */ + @Test + public void testTimeSpanToXSDuration() { + Calendar calendar = new GregorianCalendar(2008, Calendar.OCTOBER, 10); + timeSpanToXSDuration(calendar); + } + + /** + * Time span to xs duration. + * + * @param timeSpan the time span + * @return the string + */ + public String timeSpanToXSDuration(Calendar timeSpan) { + String offsetStr = (timeSpan.SECOND < 0) ? "-" : ""; + String obj = String.format("%s %s %s %s %s ", offsetStr, Math + .abs(timeSpan.DAY_OF_MONTH), Math.abs(timeSpan.HOUR_OF_DAY), + Math.abs(timeSpan.MINUTE), Math.abs(timeSpan.SECOND) + "." + + Math.abs(timeSpan.MILLISECOND)); + + return obj; + } +} diff --git a/src/test/java/microsoft/exchange/webservices/data/misc/availability/TimeWindowTest.java b/src/test/java/microsoft/exchange/webservices/data/misc/availability/TimeWindowTest.java new file mode 100644 index 000000000..d0c9cc93d --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/misc/availability/TimeWindowTest.java @@ -0,0 +1,81 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.misc.availability; + +import microsoft.exchange.webservices.base.BaseTest; +import microsoft.exchange.webservices.data.core.EwsServiceXmlReader; +import microsoft.exchange.webservices.data.core.EwsServiceXmlWriter; +import microsoft.exchange.webservices.data.core.XmlElementNames; +import microsoft.exchange.webservices.data.core.enumeration.misc.XmlNamespace; +import microsoft.exchange.webservices.data.security.XmlNodeType; +import org.junit.Assert; +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.util.Date; + +public class TimeWindowTest extends BaseTest { + + @Test + public void testWriteToXmlUnscopedDatesOnlyUsesUTC() { + // Thu, 01 Jan 2015 0:0:00 UTC + final Date midnight = new Date(1420070400000l); + // Thu, 01 Jan 2015 23:59:59 GMT + final Date just_before_midnight = new Date(1420156799000l); + + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + EwsServiceXmlWriter writer; + + try { + // build the test xml markup + writer = new EwsServiceXmlWriter(exchangeServiceMock, outputStream); + writer.writeStartDocument(); + writer.writeStartElement(XmlNamespace.NotSpecified, "test"); + writer.writeAttributeValue("xmlns:" + XmlNamespace.Types.getNameSpacePrefix(), XmlNamespace.Types.getNameSpaceUri()); + TimeWindow tw = new TimeWindow(); + tw.setStartTime(midnight); + tw.setEndTime(just_before_midnight); + tw.writeToXmlUnscopedDatesOnly(writer, XmlElementNames.Duration); + writer.writeEndElement(); + + // read the test markup + InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); + EwsServiceXmlReader reader = new EwsServiceXmlReader(inputStream, exchangeServiceMock); + reader.read(new XmlNodeType(XmlNodeType.START_DOCUMENT)); + reader.readStartElement(XmlNamespace.NotSpecified, "test"); + reader.readStartElement(XmlNamespace.Types, XmlElementNames.Duration); + TimeWindow checkTw = new TimeWindow(); + + checkTw.loadFromXml(reader); + + // Test that the dates have not shifted. + Assert.assertEquals(midnight, checkTw.getStartTime()); + Assert.assertEquals(midnight, checkTw.getEndTime()); + } catch (Exception e) { + Assert.fail(e.getMessage()); + } + } +} diff --git a/src/test/java/microsoft/exchange/webservices/data/property/complex/ComplexPropertyCollectionTest.java b/src/test/java/microsoft/exchange/webservices/data/property/complex/ComplexPropertyCollectionTest.java new file mode 100644 index 000000000..90f11b5ae --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/property/complex/ComplexPropertyCollectionTest.java @@ -0,0 +1,72 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.property.complex; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.List; + + +@RunWith(JUnit4.class) +public class ComplexPropertyCollectionTest { + + @Test + public void testComplexPropertyChangedPositive() { + final ComplexPropertyCollection collection = createFakeComplexPropertyCollection(); + + final ComplexProperty property = createFakeComplexProperty(); + collection.complexPropertyChanged(property); + + final List modifiedItems = collection.getModifiedItems(); + Assert.assertTrue(collection.getAddedItems().isEmpty()); + Assert.assertTrue(modifiedItems.contains(property)); + Assert.assertEquals(1, modifiedItems.size()); + } + + @Test(expected = RuntimeException.class) + public void testComplexPropertyChangedNegative() { + final ComplexPropertyCollection collection = createFakeComplexPropertyCollection(); + collection.complexPropertyChanged(null); + } + + + private ComplexProperty createFakeComplexProperty() { + return new ComplexProperty() {}; + } + + private ComplexPropertyCollection createFakeComplexPropertyCollection() { + return new ComplexPropertyCollection() { + @Override protected ComplexProperty createComplexProperty(final String xmlElementName) { + return null; + } + @Override protected String getCollectionItemXmlElementName(final ComplexProperty complexProperty) { + return null; + } + }; + } + +} diff --git a/src/test/java/microsoft/exchange/webservices/data/property/complex/EmailAddressTest.java b/src/test/java/microsoft/exchange/webservices/data/property/complex/EmailAddressTest.java new file mode 100644 index 000000000..e696e4ba2 --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/property/complex/EmailAddressTest.java @@ -0,0 +1,43 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.property.complex; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class EmailAddressTest { + + @Test + public void testEmailAddressToString() { + EmailAddress address = new EmailAddress(); + address.setAddress("ews@ews.com"); + Assert.assertEquals(address.toString(), "ews@ews.com"); + address.setName("ews"); + Assert.assertEquals(address.toString(), "ews "); + } + +} diff --git a/src/test/java/microsoft/exchange/webservices/data/property/complex/ExtendedPropertyCollectionTest.java b/src/test/java/microsoft/exchange/webservices/data/property/complex/ExtendedPropertyCollectionTest.java new file mode 100644 index 000000000..436b5e356 --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/property/complex/ExtendedPropertyCollectionTest.java @@ -0,0 +1,77 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.property.complex; + +import java.util.ArrayList; + +import microsoft.exchange.webservices.data.core.enumeration.property.MapiPropertyType; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import microsoft.exchange.webservices.data.core.exception.misc.ArgumentException; +import microsoft.exchange.webservices.data.misc.OutParam; +import microsoft.exchange.webservices.data.property.definition.ExtendedPropertyDefinition; + +@RunWith(JUnit4.class) +public class ExtendedPropertyCollectionTest { + + /** + * Calling tryGetValue with invalid input + * expecting exception. + * + * @throws Exception + */ + @Test(expected=ArgumentException.class) + public void tryGetValue() throws Exception{ + ExtendedPropertyCollection epc = new ExtendedPropertyCollection(); + epc.setExtendedProperty(new ExtendedPropertyDefinition(), new ArrayList()); + Class cls = Long.class; + // By default - type of ExtendedPropertyDefinition will be String + ExtendedPropertyDefinition propertyDefinition = new ExtendedPropertyDefinition(); + + OutParam propertyValueOut = new OutParam(); + // It should fail here due to incompatibility between default String and passed Long + Assert.assertTrue(epc.tryGetValue(cls, propertyDefinition, propertyValueOut)); + } + + /** + * Calling tryGetValue with non-default input + * expecting positive result. + * + */ + @Test() + public void tryGetValueWithProperInput() throws Exception{ + ExtendedPropertyCollection epc = new ExtendedPropertyCollection(); + Class cls = Integer.class; + Integer testValue = new Integer(456); + ExtendedPropertyDefinition propertyDefinition = new ExtendedPropertyDefinition(123, MapiPropertyType.Integer); + epc.setExtendedProperty(propertyDefinition, testValue); + + OutParam propertyValueOut = new OutParam(); + Assert.assertTrue(epc.tryGetValue(cls, propertyDefinition, propertyValueOut)); + Assert.assertTrue(propertyValueOut.getParam().equals(testValue)); + } +} diff --git a/src/test/java/microsoft/exchange/webservices/data/property/complex/OlsonTimeZoneTest.java b/src/test/java/microsoft/exchange/webservices/data/property/complex/OlsonTimeZoneTest.java new file mode 100644 index 000000000..3278e4b7a --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/property/complex/OlsonTimeZoneTest.java @@ -0,0 +1,63 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.property.complex; + +import microsoft.exchange.webservices.data.property.complex.time.OlsonTimeZoneDefinition; +import microsoft.exchange.webservices.data.util.TimeZoneUtils; +import org.apache.commons.lang3.StringUtils; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.Map; +import java.util.TimeZone; + +@RunWith(JUnit4.class) +public class OlsonTimeZoneTest { + + @Test + public void testOlsonTimeZoneConversion() { + final Map olsonTimeZoneToMsMap = TimeZoneUtils.createOlsonTimeZoneToMsMap(); + final String[] timeZoneIds = TimeZone.getAvailableIDs(); + + for (final String timeZoneId : timeZoneIds) { + final boolean america = timeZoneId.startsWith("America"); + final boolean europe = timeZoneId.startsWith("Europe"); + final boolean africa = timeZoneId.startsWith("Africa"); + + if (america || europe || africa) { + // There are a few timezones that are out of date or don't have direct microsoft mappings + // according to the Unicode source we use so we will only test Americas, Europe and Africa. + final TimeZone timeZone = TimeZone.getTimeZone(timeZoneId); + final OlsonTimeZoneDefinition olsonTimeZone = new OlsonTimeZoneDefinition(timeZone); + final String olsonTimeZoneId = olsonTimeZone.getId(); + + Assert.assertFalse("olsonTimeZoneId for " + timeZoneId + " is blank", StringUtils.isBlank(olsonTimeZoneId)); + Assert.assertEquals(olsonTimeZoneToMsMap.get(timeZoneId), olsonTimeZoneId); + } + } + } + +} diff --git a/src/test/java/microsoft/exchange/webservices/data/property/complex/RecurrenceReaderTest.java b/src/test/java/microsoft/exchange/webservices/data/property/complex/RecurrenceReaderTest.java new file mode 100644 index 000000000..8b6987baf --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/property/complex/RecurrenceReaderTest.java @@ -0,0 +1,60 @@ +/* + * The MIT License Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.property.complex; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.doReturn; +import microsoft.exchange.webservices.data.core.EwsServiceXmlReader; +import microsoft.exchange.webservices.data.core.XmlElementNames; +import microsoft.exchange.webservices.data.property.complex.recurrence.pattern.Recurrence.MonthlyPattern; +import microsoft.exchange.webservices.data.property.complex.recurrence.pattern.Recurrence.YearlyPattern; + +import org.junit.Test; +import org.mockito.Mockito; + +public class RecurrenceReaderTest { + + @Test + public void testMonthlyPattern() throws Exception { + + EwsServiceXmlReader reader = Mockito.mock(EwsServiceXmlReader.class); + doReturn(XmlElementNames.DayOfMonth).when(reader).getLocalName(); + doReturn(1).when(reader).readElementValue(Integer.class); + + MonthlyPattern monthly = new MonthlyPattern(); + monthly.tryReadElementFromXml(reader); + + assertEquals(1, monthly.getDayOfMonth()); + } + + @Test + public void testYearlyPattern() throws Exception { + + EwsServiceXmlReader reader = Mockito.mock(EwsServiceXmlReader.class); + doReturn(XmlElementNames.DayOfMonth).when(reader).getLocalName(); + doReturn(1).when(reader).readElementValue(Integer.class); + + YearlyPattern yearly = new YearlyPattern(); + yearly.tryReadElementFromXml(reader); + + assertEquals(1, yearly.getDayOfMonth()); + } + +} diff --git a/src/test/java/microsoft/exchange/webservices/data/property/complex/TimeChangeTest.java b/src/test/java/microsoft/exchange/webservices/data/property/complex/TimeChangeTest.java new file mode 100644 index 000000000..6346bacf6 --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/property/complex/TimeChangeTest.java @@ -0,0 +1,102 @@ +/* + * The MIT License Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + +package microsoft.exchange.webservices.data.property.complex; + +import java.util.Calendar; +import java.util.TimeZone; + +import javax.xml.bind.DatatypeConverter; + +import microsoft.exchange.webservices.data.core.EwsUtilities; +import microsoft.exchange.webservices.data.misc.Time; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class TimeChangeTest { + + private static String time = "03:00:00"; + private static String time_fail1 = "21:32"; + private static String time_fail2 = "25:25:10"; + private static String time_fail3 = "-10:00:00"; + + private static String dateUTC = "2001-10-27Z"; + private static String date_fail1 = "2001-10-32"; + private static String date_fail2 = "2001-13-26+02:00"; + private static String date_fail3 = "01-10-26"; + + @Test + public void testDateUTC() { + Assert.assertEquals("2001-10-27Z", testDate(dateUTC)); + } + + private String testDate(String value) { + Calendar cal = DatatypeConverter.parseDate(value); + cal.setTimeZone(TimeZone.getTimeZone("UTC")); + String XSDate = EwsUtilities.dateTimeToXSDate(cal.getTime()); + return XSDate; + } + + @Test(expected = IllegalArgumentException.class) + public void testDateFail1() { + testDate(date_fail1); + } + + @Test(expected = IllegalArgumentException.class) + public void testDateFail2() { + testDate(date_fail2); + } + + @Test(expected = IllegalArgumentException.class) + public void testDateFail3() { + testDate(date_fail3); + } + + private String testTime(String value) { + Calendar cal = DatatypeConverter.parseTime(value); + Time time = new Time(cal.getTime()); + return time.toXSTime(); + } + + @Test(expected = IllegalArgumentException.class) + public void testTimeFail1() { + testTime(time_fail1); + } + + @Test(expected = IllegalArgumentException.class) + public void testTimeFail2() { + testTime(time_fail2); + } + + @Test(expected = IllegalArgumentException.class) + public void testTimeFail3() { + testTime(time_fail3); + } + + @Test + public void testTimeValues() { + Assert.assertEquals("{0:00}:{1:00}:{2:00},3,0,0", testTime(time)); + } + +} diff --git a/src/test/java/microsoft/exchange/webservices/data/property/complex/TimeZoneTransitionCompareTest.java b/src/test/java/microsoft/exchange/webservices/data/property/complex/TimeZoneTransitionCompareTest.java new file mode 100644 index 000000000..47e993a28 --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/property/complex/TimeZoneTransitionCompareTest.java @@ -0,0 +1,133 @@ +/* + * The MIT License Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.property.complex; + +import static org.mockito.Mockito.doReturn; + +import java.util.Date; + +import microsoft.exchange.webservices.data.property.complex.time.AbsoluteDateTransition; +import microsoft.exchange.webservices.data.property.complex.time.TimeZoneDefinition; +import microsoft.exchange.webservices.data.property.complex.time.TimeZoneTransition; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.Mockito; + +@RunWith(JUnit4.class) +public class TimeZoneTransitionCompareTest { + + @Test + public void testAbsoluteDateTransitionsEqual() { + TimeZoneDefinition timeZoneDefinition = new TimeZoneDefinition(); + + Date date = new Date(); + + AbsoluteDateTransition first = Mockito.mock(AbsoluteDateTransition.class); + AbsoluteDateTransition second = Mockito.mock(AbsoluteDateTransition.class); + + doReturn(date).when(first).getDateTime(); + doReturn(date).when(second).getDateTime(); + + Assert.assertEquals(0, timeZoneDefinition.compare(first, second)); + } + + @Test + public void testAbsoluteDateTransitionsLess() { + TimeZoneDefinition timeZoneDefinition = new TimeZoneDefinition(); + + Date date1 = new Date(); + Date date2 = new Date(date1.getTime() + 1); + + AbsoluteDateTransition first = Mockito.mock(AbsoluteDateTransition.class); + AbsoluteDateTransition second = Mockito.mock(AbsoluteDateTransition.class); + + doReturn(date1).when(first).getDateTime(); + doReturn(date2).when(second).getDateTime(); + + Assert.assertEquals(-1, timeZoneDefinition.compare(first, second)); + } + + @Test + public void testAbsoluteDateTransitionsGreater() { + TimeZoneDefinition timeZoneDefinition = new TimeZoneDefinition(); + + Date date1 = new Date(); + Date date2 = new Date(date1.getTime() - 1); + + AbsoluteDateTransition first = Mockito.mock(AbsoluteDateTransition.class); + AbsoluteDateTransition second = Mockito.mock(AbsoluteDateTransition.class); + + doReturn(date1).when(first).getDateTime(); + doReturn(date2).when(second).getDateTime(); + + Assert.assertEquals(1, timeZoneDefinition.compare(first, second)); + } + + @Test + public void testAbsoluteDateTransitionAndTimeZoneTransition() { + TimeZoneDefinition timeZoneDefinition = new TimeZoneDefinition(); + + Date date1 = new Date(); + + AbsoluteDateTransition first = Mockito.mock(AbsoluteDateTransition.class); + TimeZoneTransition second = Mockito.mock(TimeZoneTransition.class); + + doReturn(date1).when(first).getDateTime(); + + Assert.assertEquals(1, timeZoneDefinition.compare(first, second)); + } + + @Test + public void testAbsoluteDateTransitionAndNull() { + TimeZoneDefinition timeZoneDefinition = new TimeZoneDefinition(); + + Date date1 = new Date(); + AbsoluteDateTransition first = Mockito.mock(AbsoluteDateTransition.class); + doReturn(date1).when(first).getDateTime(); + + Assert.assertEquals(1, timeZoneDefinition.compare(first, null)); + } + + @Test + public void testNullAndAbsoluteDateTransition() { + TimeZoneDefinition timeZoneDefinition = new TimeZoneDefinition(); + + Date date1 = new Date(); + AbsoluteDateTransition second = Mockito.mock(AbsoluteDateTransition.class); + doReturn(date1).when(second).getDateTime(); + + Assert.assertEquals(-1, timeZoneDefinition.compare(null, second)); + } + + @Test + public void testCompareSameObject() { + TimeZoneDefinition timeZoneDefinition = new TimeZoneDefinition(); + + Date date1 = new Date(); + AbsoluteDateTransition first = Mockito.mock(AbsoluteDateTransition.class); + doReturn(date1).when(first).getDateTime(); + + Assert.assertEquals(0, timeZoneDefinition.compare(first, first)); + } + +} diff --git a/src/test/java/microsoft/exchange/webservices/data/property/complex/UniqueBodyTest.java b/src/test/java/microsoft/exchange/webservices/data/property/complex/UniqueBodyTest.java new file mode 100644 index 000000000..02895f730 --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/property/complex/UniqueBodyTest.java @@ -0,0 +1,93 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.property.complex; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +import microsoft.exchange.webservices.data.core.EwsServiceXmlReader; +import microsoft.exchange.webservices.data.core.EwsServiceXmlWriter; +import microsoft.exchange.webservices.data.core.XmlAttributeNames; +import microsoft.exchange.webservices.data.core.XmlElementNames; +import microsoft.exchange.webservices.data.core.enumeration.property.BodyType; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +public class UniqueBodyTest { + + UniqueBody impl; + + final String text = "test"; + + final BodyType bodyType = BodyType.HTML; + + @Mock EwsServiceXmlReader reader; + @Mock EwsServiceXmlWriter writer; + + + @Before public void setUp() throws Exception { + impl = new UniqueBody(); + MockitoAnnotations.initMocks(this); + } + + @Test public void testReadAttributesFromXml() throws Exception { + doReturn(BodyType.Text).when(reader).readAttributeValue(BodyType.class, XmlAttributeNames.BodyType); + impl.readAttributesFromXml(reader); + assertEquals(BodyType.Text, impl.getBodyType()); + } + + @Test public void testReadTextValueFromXml() throws Exception { + setTextToImpl(text); + assertEquals(text, impl.getText()); + assertEquals(text, UniqueBody.getStringFromUniqueBody(impl)); + } + + @Test public void testWriteAttributesToXml() throws Exception { + impl.writeAttributesToXml(writer); + verify(writer).writeAttributeValue(XmlAttributeNames.BodyType, impl.getBodyType()); + } + + @Test public void testWriteElementsToXml() throws Exception { + impl.writeElementsToXml(writer); + verify(writer, never()).writeValue(this.text, XmlElementNames.UniqueBody); + setTextToImpl(text); + impl.writeElementsToXml(writer); + verify(writer).writeValue(text, XmlElementNames.UniqueBody); + } + + @Test public void testToString() throws Exception { + assertEquals("", impl.toString()); + setTextToImpl(text); + assertEquals(text, impl.toString()); + } + + private void setTextToImpl(String myText) throws Exception { + doReturn(myText).when(reader).readValue(); + impl.readTextValueFromXml(reader); + } +} \ No newline at end of file diff --git a/src/test/java/microsoft/exchange/webservices/data/property/complex/UserConfigurationDictionaryTest.java b/src/test/java/microsoft/exchange/webservices/data/property/complex/UserConfigurationDictionaryTest.java new file mode 100644 index 000000000..c0bfaa0ba --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/property/complex/UserConfigurationDictionaryTest.java @@ -0,0 +1,160 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.property.complex; + +import microsoft.exchange.webservices.base.BaseTest; +import microsoft.exchange.webservices.data.core.EwsServiceXmlWriter; +import microsoft.exchange.webservices.data.core.exception.service.local.ServiceLocalException; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.util.Date; + +/** + * Testclass for methods of UserConfigurationDictionary + */ +@RunWith(JUnit4.class) +public class UserConfigurationDictionaryTest extends BaseTest { + + /** + * Mock for the UserConfigurationDictionary + */ + protected UserConfigurationDictionary userConfigurationDictionary; + + @Before + public void setup() throws Exception { + // Initialise a UserConfigurationDictionary Testobject + this.userConfigurationDictionary = new UserConfigurationDictionary(); + } + + /** + * Adding a Double Value to the Dictionary witch is not allowed + * + * @throws Exception + */ + @Test(expected = ServiceLocalException.class) + public void testAddUnsupportedElementsToDictionary() throws Exception { + this.userConfigurationDictionary.addElement("someDouble", 1.0); + } + + /** + * testAddSupportedElementsToDictionary + * + * @throws Exception + */ + @Test + public void testAddSupportedElementsToDictionary() throws Exception { + fillDictionaryWithValidEntries(); + } + + /** + * Fills the Dictionary with + * + * @throws Exception + */ + private void fillDictionaryWithValidEntries() throws Exception { + // Adding Test Values to the Object + final int testInt = 1; + final long testLong = 1l; + final String testString = "someVal"; + final String[] testStringArray = new String[] {"test1", "test2", "test3"}; + final Date testDate = new Date(); + final boolean testBoolean = true; + final byte testByte = Byte.decode("0x10"); + final byte[] testByteArray = testString.getBytes(); + final Byte[] testByteArray2 = new Byte[testByteArray.length]; + for (int currentIndex = 0; currentIndex < testByteArray.length; currentIndex++) { + testByteArray2[currentIndex] = testByteArray[currentIndex]; + } + + Assert.assertNotNull(this.userConfigurationDictionary); + + this.userConfigurationDictionary.addElement("someString", testString); + Assert.assertTrue(this.userConfigurationDictionary.containsKey("someString")); + Assert.assertEquals(testString, this.userConfigurationDictionary.getElements("someString")); + Assert.assertTrue(this.userConfigurationDictionary.getElements("someString") instanceof String); + + this.userConfigurationDictionary.addElement("someLong", testLong); + Assert.assertTrue(this.userConfigurationDictionary.containsKey("someLong")); + Assert.assertEquals(testLong, this.userConfigurationDictionary.getElements("someLong")); + Assert.assertTrue(this.userConfigurationDictionary.getElements("someLong") instanceof Long); + + this.userConfigurationDictionary.addElement("someInteger", testInt); + Assert.assertTrue(this.userConfigurationDictionary.containsKey("someInteger")); + Assert.assertEquals(testInt, this.userConfigurationDictionary.getElements("someInteger")); + Assert.assertTrue(this.userConfigurationDictionary.getElements("someInteger") instanceof Integer); + + this.userConfigurationDictionary.addElement("someString[]", testStringArray); + Assert.assertTrue(this.userConfigurationDictionary.containsKey("someString[]")); + Assert.assertEquals(testStringArray, this.userConfigurationDictionary.getElements("someString[]")); + Assert.assertTrue(this.userConfigurationDictionary.getElements("someString[]") instanceof String[]); + + this.userConfigurationDictionary.addElement("someDate", testDate); + Assert.assertTrue(this.userConfigurationDictionary.containsKey("someDate")); + Assert.assertEquals(testDate, this.userConfigurationDictionary.getElements("someDate")); + Assert.assertTrue(this.userConfigurationDictionary.getElements("someDate") instanceof Date); + + this.userConfigurationDictionary.addElement("someBoolean", testBoolean); + Assert.assertTrue(this.userConfigurationDictionary.containsKey("someBoolean")); + Assert.assertEquals(testBoolean, this.userConfigurationDictionary.getElements("someBoolean")); + Assert.assertTrue(this.userConfigurationDictionary.getElements("someBoolean") instanceof Boolean); + + this.userConfigurationDictionary.addElement("someByte", testByte); + Assert.assertTrue(this.userConfigurationDictionary.containsKey("someByte")); + Assert.assertEquals(testByte, this.userConfigurationDictionary.getElements("someByte")); + Assert.assertTrue(this.userConfigurationDictionary.getElements("someByte") instanceof Byte); + + this.userConfigurationDictionary.addElement("someByte[]", testByteArray); + Assert.assertTrue(this.userConfigurationDictionary.containsKey("someByte[]")); + Assert.assertEquals(testByteArray, this.userConfigurationDictionary.getElements("someByte[]")); + Assert.assertTrue(this.userConfigurationDictionary.getElements("someByte[]") instanceof byte[]); + + this.userConfigurationDictionary.addElement("someByte2[]", testByteArray2); + Assert.assertTrue(this.userConfigurationDictionary.containsKey("someByte2[]")); + Assert.assertEquals(testByteArray2, this.userConfigurationDictionary.getElements("someByte2[]")); + Assert.assertTrue(this.userConfigurationDictionary.getElements("someByte2[]") instanceof Byte[]); + } + + /** + * Tests the Method writeElementsToXml(...) + * with all valid Elements + */ + @Test + public void testWriteElementsToXml() throws Exception { + // Mock up needed Classes + OutputStream output = new ByteArrayOutputStream(); + EwsServiceXmlWriter testWriter = new EwsServiceXmlWriter(exchangeServiceBaseMock, output); + + // Adding Test Values to the Object + fillDictionaryWithValidEntries(); + + // Write the Elements + this.userConfigurationDictionary.writeElementsToXml(testWriter); + } +} diff --git a/src/test/java/microsoft/exchange/webservices/data/property/definition/ByteArrayPropertyDefinitionTest.java b/src/test/java/microsoft/exchange/webservices/data/property/definition/ByteArrayPropertyDefinitionTest.java new file mode 100644 index 000000000..75887ca35 --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/property/definition/ByteArrayPropertyDefinitionTest.java @@ -0,0 +1,69 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.property.definition; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion; +import microsoft.exchange.webservices.data.core.enumeration.property.PropertyDefinitionFlags; +import org.apache.commons.codec.binary.Base64; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.EnumSet; + +@RunWith(JUnit4.class) +public class ByteArrayPropertyDefinitionTest { + + private ByteArrayPropertyDefinition testObject; + + private static final String TEST_STRING = "Lorem ipsum dolor sit amet"; + private static final String BASE64_ENCODEDSTRING = Base64.encodeBase64String(TEST_STRING.getBytes()); + + /** + * setup + */ + @Before + public void init(){ + this.testObject = + new ByteArrayPropertyDefinition("myTestObject", "myTestUri", + EnumSet.of(PropertyDefinitionFlags.None), + ExchangeVersion.Exchange2010_SP2); + } + + /** + * Test for ByteArrayPropertyDefinition.toString() + * This Test should guarantee that toString() byte encoding works + */ + @Test + public void testToString(){ + String result = testObject.toString(TEST_STRING.getBytes()); + assertNotNull(result); + assertEquals(BASE64_ENCODEDSTRING, result); + } + +} diff --git a/src/test/java/microsoft/exchange/webservices/data/sync/ChangeCollectionTest.java b/src/test/java/microsoft/exchange/webservices/data/sync/ChangeCollectionTest.java new file mode 100644 index 000000000..0c9e15eae --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/sync/ChangeCollectionTest.java @@ -0,0 +1,112 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.sync; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.verify; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.List; + +@RunWith(MockitoJUnitRunner.class) public class ChangeCollectionTest { + + private static final String STATE = "SOME_STATE"; + @Mock Change change0; + @Mock Change change1; + @Mock Change change2; + + ChangeCollection impl; + @InjectMocks ChangeCollection spiedImpl; + + @Mock(name = "changes") List innerList; + + + @Before public void setUp() throws Exception { + + impl = new ChangeCollection(); + } + + @Test public void testAdd() throws Exception { + + assertEquals(impl.getCount(), 0); + impl.add(change0); + assertEquals(1, impl.getCount()); + impl.add(change1); + assertEquals(2, impl.getCount()); + + } + + + @Test public void testGetChangeAtIndex() throws Exception { + assertEquals(impl.getCount(), 0); + impl.add(change0); + impl.add(change1); + impl.add(change2); + assertSame(change0, impl.getChangeAtIndex(0)); + assertSame(change1, impl.getChangeAtIndex(1)); + assertSame(change2, impl.getChangeAtIndex(2)); + + } + + @Test(expected = IndexOutOfBoundsException.class) + public void testGetChangeAtIndexThrowsIndexOutOfBoundException() throws Exception { + assertEquals(impl.getCount(), 0); + impl.add(change0); + impl.add(change1); + impl.add(change2); + + impl.getChangeAtIndex(99); + } + + @Test public void testGetSyncState() throws Exception { + + impl.setSyncState(STATE); + assertSame(STATE, impl.getSyncState()); + + } + + + @Test public void testGetMoreChangesAvailable() throws Exception { + impl.setMoreChangesAvailable(true); + assertTrue(impl.getMoreChangesAvailable()); + + impl.setMoreChangesAvailable(false); + assertFalse(impl.getMoreChangesAvailable()); + } + + @Test public void testIterator() throws Exception { + spiedImpl.iterator(); + + verify(innerList).iterator(); + } +} diff --git a/src/test/java/microsoft/exchange/webservices/data/util/DateTimeUtilsTest.java b/src/test/java/microsoft/exchange/webservices/data/util/DateTimeUtilsTest.java new file mode 100644 index 000000000..da002e77c --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/util/DateTimeUtilsTest.java @@ -0,0 +1,259 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import microsoft.exchange.webservices.base.util.TestUtils; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +@RunWith(JUnit4.class) +public class DateTimeUtilsTest { + + // Tests for DateTimeUtils.convertDateTimeStringToDate() + + @Test + public void testDateTimeEmpty() { + assertNull(DateTimeUtils.convertDateTimeStringToDate(null)); + assertNull(DateTimeUtils.convertDateTimeStringToDate("")); + } + + @Test + public void testDateTimeZulu() { + String dateString = "2015-01-08T10:11:12Z"; + Date parsed = DateTimeUtils.convertDateTimeStringToDate(dateString); + Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); + calendar.setTime(parsed); + assertEquals(2015, calendar.get(Calendar.YEAR)); + assertEquals(0, calendar.get(Calendar.MONTH)); + assertEquals(8, calendar.get(Calendar.DATE)); + assertEquals(10, calendar.get(Calendar.HOUR_OF_DAY)); + assertEquals(11, calendar.get(Calendar.MINUTE)); + assertEquals(12, calendar.get(Calendar.SECOND)); + } + + @Test + public void testDateTimeZuluLowerZ() { + String dateString = "2015-01-08T10:11:12z"; + Date parsed = DateTimeUtils.convertDateTimeStringToDate(dateString); + Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); + calendar.setTime(parsed); + assertEquals(2015, calendar.get(Calendar.YEAR)); + assertEquals(0, calendar.get(Calendar.MONTH)); + assertEquals(8, calendar.get(Calendar.DATE)); + assertEquals(10, calendar.get(Calendar.HOUR_OF_DAY)); + assertEquals(11, calendar.get(Calendar.MINUTE)); + assertEquals(12, calendar.get(Calendar.SECOND)); + } + + @Test + public void testDateTimeZuluWithPrecision() { + String dateString = "2015-01-08T10:11:12.123Z"; + Date parsed = DateTimeUtils.convertDateTimeStringToDate(dateString); + Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); + calendar.setTime(parsed); + assertEquals(2015, calendar.get(Calendar.YEAR)); + assertEquals(0, calendar.get(Calendar.MONTH)); + assertEquals(8, calendar.get(Calendar.DATE)); + assertEquals(10, calendar.get(Calendar.HOUR_OF_DAY)); + assertEquals(11, calendar.get(Calendar.MINUTE)); + assertEquals(12, calendar.get(Calendar.SECOND)); + } + + @Test + public void testDateTimeZuluWithMilliseconds() { + String dateString = "9999-12-30T23:59:59.9999999Z"; + Date parsed = DateTimeUtils.convertDateTimeStringToDate(dateString); + Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); + calendar.setTime(parsed); + assertEquals(9999, calendar.get(Calendar.YEAR)); + assertEquals(11, calendar.get(Calendar.MONTH)); + assertEquals(30, calendar.get(Calendar.DATE)); + assertEquals(23, calendar.get(Calendar.HOUR_OF_DAY)); + assertEquals(59, calendar.get(Calendar.MINUTE)); + assertEquals(59, calendar.get(Calendar.SECOND)); + } + + @Test + public void testDateTimeWithTimeZone() { + String dateString = "2015-01-08T10:11:12+0200"; + Date parsed = DateTimeUtils.convertDateTimeStringToDate(dateString); + Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); + calendar.setTime(parsed); + assertEquals(2015, calendar.get(Calendar.YEAR)); + assertEquals(0, calendar.get(Calendar.MONTH)); + assertEquals(8, calendar.get(Calendar.DATE)); + assertEquals(8, calendar.get(Calendar.HOUR)); + assertEquals(11, calendar.get(Calendar.MINUTE)); + assertEquals(12, calendar.get(Calendar.SECOND)); + } + + @Test + public void testDateTimeWithTimeZoneWithColon() { + String dateString = "2015-01-08T10:11:12-02:00"; + Date parsed = DateTimeUtils.convertDateTimeStringToDate(dateString); + Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); + calendar.setTime(parsed); + assertEquals(2015, calendar.get(Calendar.YEAR)); + assertEquals(0, calendar.get(Calendar.MONTH)); + assertEquals(8, calendar.get(Calendar.DATE)); + assertEquals(12, calendar.get(Calendar.HOUR_OF_DAY)); + assertEquals(11, calendar.get(Calendar.MINUTE)); + assertEquals(12, calendar.get(Calendar.SECOND)); + } + + @Test + public void testDateTime() { + String dateString = "2015-01-08T10:11:12"; + Date parsed = DateTimeUtils.convertDateTimeStringToDate(dateString); + Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); + calendar.setTime(parsed); + assertEquals(2015, calendar.get(Calendar.YEAR)); + assertEquals(0, calendar.get(Calendar.MONTH)); + assertEquals(8, calendar.get(Calendar.DATE)); + assertEquals(10, calendar.get(Calendar.HOUR_OF_DAY)); + assertEquals(11, calendar.get(Calendar.MINUTE)); + assertEquals(12, calendar.get(Calendar.SECOND)); + } + + @Test + public void testDateZulu() { + String dateString = "2015-01-08Z"; + Date parsed = DateTimeUtils.convertDateTimeStringToDate(dateString); + Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); + calendar.setTime(parsed); + assertEquals(2015, calendar.get(Calendar.YEAR)); + assertEquals(0, calendar.get(Calendar.MONTH)); + assertEquals(8, calendar.get(Calendar.DATE)); + } + + @Test + public void testDateOnly() { + String dateString = "2015-01-08"; + Date parsed = DateTimeUtils.convertDateTimeStringToDate(dateString); + Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); + calendar.setTime(parsed); + assertEquals(2015, calendar.get(Calendar.YEAR)); + assertEquals(0, calendar.get(Calendar.MONTH)); + assertEquals(8, calendar.get(Calendar.DATE)); + } + + + // Tests for DateTimeUtils.convertDateStringToDate() + + @Test + public void testDateOnlyEmpty() { + assertNull(DateTimeUtils.convertDateStringToDate(null)); + assertNull(DateTimeUtils.convertDateStringToDate("")); + } + + @Test + public void testDateOnlyZulu() { + String dateString = "2015-01-08Z"; + Date parsed = DateTimeUtils.convertDateStringToDate(dateString); + Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); + calendar.setTime(parsed); + assertEquals(2015, calendar.get(Calendar.YEAR)); + assertEquals(0, calendar.get(Calendar.MONTH)); + assertEquals(8, calendar.get(Calendar.DATE)); + assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + assertEquals(0, calendar.get(Calendar.MINUTE)); + assertEquals(0, calendar.get(Calendar.SECOND)); + } + + @Test + public void testDateOnlyZuluWithLowerZ() { + String dateString = "2015-01-08z"; + Date parsed = DateTimeUtils.convertDateStringToDate(dateString); + Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); + calendar.setTime(parsed); + assertEquals(2015, calendar.get(Calendar.YEAR)); + assertEquals(0, calendar.get(Calendar.MONTH)); + assertEquals(8, calendar.get(Calendar.DATE)); + assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + assertEquals(0, calendar.get(Calendar.MINUTE)); + assertEquals(0, calendar.get(Calendar.SECOND)); + } + + @Test + public void testDateOnlyWithTimeZone() { + String dateString = "2015-01-08+0200"; + Date parsed = DateTimeUtils.convertDateStringToDate(dateString); + Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); + calendar.setTime(parsed); + assertEquals(2015, calendar.get(Calendar.YEAR)); + assertEquals(0, calendar.get(Calendar.MONTH)); + assertEquals(7, calendar.get(Calendar.DATE)); + assertEquals(22, calendar.get(Calendar.HOUR_OF_DAY)); + assertEquals(0, calendar.get(Calendar.MINUTE)); + assertEquals(0, calendar.get(Calendar.SECOND)); + } + + @Test + public void testDateOnlyWithTimeZoneWithColon() { + String dateString = "2015-01-08-02:00"; + Date parsed = DateTimeUtils.convertDateStringToDate(dateString); + Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); + calendar.setTime(parsed); + assertEquals(2015, calendar.get(Calendar.YEAR)); + assertEquals(0, calendar.get(Calendar.MONTH)); + assertEquals(8, calendar.get(Calendar.DATE)); + assertEquals(2, calendar.get(Calendar.HOUR_OF_DAY)); + assertEquals(0, calendar.get(Calendar.MINUTE)); + assertEquals(0, calendar.get(Calendar.SECOND)); + } + + @Test + public void testDateOnlyWithoutTimeZone() { + String dateString = "2015-01-08"; + Date parsed = DateTimeUtils.convertDateStringToDate(dateString); + Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); + calendar.setTime(parsed); + assertEquals(2015, calendar.get(Calendar.YEAR)); + assertEquals(0, calendar.get(Calendar.MONTH)); + assertEquals(8, calendar.get(Calendar.DATE)); + assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + assertEquals(0, calendar.get(Calendar.MINUTE)); + assertEquals(0, calendar.get(Calendar.SECOND)); + } + + @Test(expected = IllegalArgumentException.class) + public void testConvertDateStringToDateBadFormat() { + DateTimeUtils.convertDateStringToDate("Monday, May, 1988"); + } + + @Test(expected = UnsupportedOperationException.class) + public void testDateTimeUtilsConstructor() throws Throwable { + TestUtils.checkUtilClassConstructor(DateTimeUtils.class); + } + +} diff --git a/src/test/java/microsoft/exchange/webservices/data/util/TimeZoneUtilsTest.java b/src/test/java/microsoft/exchange/webservices/data/util/TimeZoneUtilsTest.java new file mode 100644 index 000000000..92f8c1b91 --- /dev/null +++ b/src/test/java/microsoft/exchange/webservices/data/util/TimeZoneUtilsTest.java @@ -0,0 +1,66 @@ +/* + * The MIT License + * Copyright (c) 2012 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package microsoft.exchange.webservices.data.util; + +import microsoft.exchange.webservices.base.util.TestUtils; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.util.TimeZone; + +@RunWith(JUnit4.class) +public class TimeZoneUtilsTest { + + @Test(expected = UnsupportedOperationException.class) + public void testTimeZoneUtilsConstructor() throws Throwable { + TestUtils.checkUtilClassConstructor(TimeZoneUtils.class); + } + + @Test + public void testGetMicrosoftTimeZoneName() { + checkGetMicrosoftTimeZoneName("Africa/Abidjan", "Greenwich Standard Time"); + } + + @Test + public void testGetMicrosoftTimeZoneNameBad() { + // null-argument is not allowed. + try { + Assert.fail(TimeZoneUtils.getMicrosoftTimeZoneName(null)); + } catch (final IllegalArgumentException ignored) {} + + // TODO: fix this later + // Case-insensitive ID is not supported. + // checkGetMicrosoftTimeZoneName("africa/abidjan", "UTC"); + } + + + private void checkGetMicrosoftTimeZoneName(final String id, final String name) { + final TimeZone timeZone = TimeZone.getTimeZone(id); + final String zoneName = TimeZoneUtils.getMicrosoftTimeZoneName(timeZone); + Assert.assertEquals(name, zoneName); + } + +} diff --git a/src/test/resources/logback-test.xml b/src/test/resources/logback-test.xml new file mode 100644 index 000000000..721bb8aed --- /dev/null +++ b/src/test/resources/logback-test.xml @@ -0,0 +1,42 @@ + + + + + + false + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + + +