diff --git a/README.md b/README.md index b2dde7f1..5ee83d87 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,22 @@ -SonarQube Plugin for Objective C -================================ +# SonarQube Objective-C (Community) Plugin -This repository hosts the Objective-C plugin for [SonarQube](http://www.sonarqube.org/). This plugin enables to analyze and track the quality of iOS (iPhone, iPad) and MacOS developments. +This repository hosts the Objective-C plugin for +[SonarQube](http://www.sonarqube.org/). This plugin aims to analyze and track +the quality of iOS (iPhone, iPad) and MacOS projects, but it can be used with +other Objective-C projects. -This plugin is not supported by SonarSource. SonarSource offers a [commercial SonarSource Objective-C plugin](http://www.sonarsource.com/products/plugins/languages/objective-c/) as well. Both plugins do not offer the same functionalities/support. +This plugin is not supported by SonarSource. SonarSource offers a +[commercial SonarSource Objective-C plugin](http://www.sonarsource.com/products/plugins/languages/objective-c/) +as well. The plugins do not offer the same features/support. -The development of this plugin has always been done thanks to the community. If you wish to contribute, check the [Contributing](https://github.com/octo-technology/sonar-objective-c/wiki/Contributing) wiki page. +The development of this plugin has always been done thanks to the community. +If you wish to contribute, check the +[Contributing](https://github.com/octo-technology/sonar-objective-c/wiki/Contributing) +wiki page. -Find below an example of an iOS SonarQube dashboard: -

- Example iOS SonarQube dashboard -

+## Features -###Features - -- [ ] Complexity +- [x] Complexity - [ ] Design - [x] Documentation - [x] Duplications @@ -22,67 +24,165 @@ Find below an example of an iOS SonarQube dashboard: - [x] Size - [x] Tests -For more details, see the list of [SonarQube metrics](https://github.com/octo-technology/sonar-objective-c/wiki/Features) implemented or pending. +For more details, see the list of +[SonarQube metrics](https://github.com/octo-technology/sonar-objective-c/wiki/Features) +implemented or pending. + -###Compatibility +## Compatibility - Use 0.3.x releases for SonarQube < 4.3 -- Use 0.4.x releases for SonarQube >= 4.3 (4.x and 5.x) +- Use 0.4.x releases for SonarQube 4.3 and 4.4 +- Use 0.5.x releases for SonarQube >= 4.5.2 LTS + -###Download +## Download The latest version is the 0.4.0 and it's available [here](http://bit.ly/18A7OkE). The latest SonarQube 3.x release is the 0.3.1, and it's available [here](http://bit.ly/1fSwd5I). -You can also download the latest build of the plugin from [Cloudbees](https://rfelden.ci.cloudbees.com/job/sonar-objective-c/lastSuccessfulBuild/artifact/target/). +You can also download the latest build of the plugin from +[Cloudbees](https://rfelden.ci.cloudbees.com/job/sonar-objective-c/lastSuccessfulBuild/artifact/target/). -In the worst case, the Maven repository with all snapshots and releases is available here: http://repository-rfelden.forge.cloudbees.com/ +In the worst case, the Maven repository with all snapshots and releases is +available here: http://repository-rfelden.forge.cloudbees.com/ + + +## Prerequisites + +- A Mac with Xcode +- Optional: [Homebrew](http://brew.sh) for easier prerequisite installation +- [SonarQube](http://docs.codehaus.org/display/SONAR/Setup+and+Upgrade) +- [SonarQube Runner](http://docs.codehaus.org/display/SONAR/Installing+and+Configuring+SonarQube+Runner) (```brew install sonar-runner```) + +### JUnit + +Any of the following will produce JUnit XML reports for your project: + +- [xctool](https://github.com/facebook/xctool) (```brew install xctool```) + - This is actually a substitute for xcodebuild, so it will compile your app and run tests as part of the process + - Make sure the version of xctool you use is compatible with the version of Xcode you will be building with +- [xcpretty](https://github.com/supermarin/xcpretty) (```gem install xcpretty```) + - This will parse xcodebuild's output and prettify it, with the option of generating a JUnit XML report and/or JSON compilation database +- [ocunit2junit](https://github.com/ciryon/OCUnit2JUnit) (```gem install ocunit2junit```) + - This will parse xcodebuild's output and generate a JUnit XML report + + +### Coverage + +Run your tests with code coverage enabled, then run one of the following tools +to produce a Cobertura XML report which can be imported by this plugin. + +- With Xcode prior to version 7, use [gcovr](http://gcovr.com) to parse ```*.gcda``` and ```*.gcno``` files +- With Xcode 7 or greater, use [slather](https://github.com/venmo/slather) to parse the ```Coverage.profdata``` file + - Note: at time of writing, support for the ```*.profdata``` format has not been released, but can be installed by running ```gem install specific_install && gem specific_install -l https://github.com/viteinfinite/slather.git -b 61f00988e6ad65f817ba81b08533cf78615fff16``` + - Note: at time of writing, xctool is not capable of producing coverage data when using Xcode 7+ + + +### Clang + +[Clang Static Analyzer](http://clang-analyzer.llvm.org/) can produce Plist +reports which can be imported by this plugin. + +There are different ways to produce the reports, such as using Clang's +[scan-build](http://clang-analyzer.llvm.org/scan-build.html), however it's +probably easiest to use xcodebuild's ```analyze``` action. Xcodebuild will +invoke the analyzer with all the proper arguments and use any additional +analyzer configuration from your settings under ```*.xcodeproj```. By default, +it will produce the Plist reports this plugin needs. + + +### OCLint + +[OCLint](http://docs.oclint.org/en/dev/intro/installation.html) version 0.8.1 recommended +(```brew install https://gist.githubusercontent.com/TonyAnhTran/e1522b93853c5a456b74/raw/157549c7a77261e906fb88bc5606afd8bd727a73/oclint.rb```). +Use it to produce a PMD-formatted XML report that can be imported by this +plugin. -###Prerequisites -- a Mac with Xcode... -- [SonarQube](http://docs.codehaus.org/display/SONAR/Setup+and+Upgrade) and [SonarQube Runner](http://docs.codehaus.org/display/SONAR/Installing+and+Configuring+SonarQube+Runner) installed ([HomeBrew](http://brew.sh) installed and ```brew install sonar-runner```) -- [xctool](https://github.com/facebook/xctool) ([HomeBrew](http://brew.sh) installed and ```brew install xctool```). If you are using Xcode 6, make sure to update xctool (```brew upgrade xctool```) to a version > 0.2.2. -- [OCLint](http://docs.oclint.org/en/dev/intro/installation.html) installed. Version 0.8.1 recommended ([HomeBrew](http://brew.sh) installed and ```brew install https://gist.githubusercontent.com/TonyAnhTran/e1522b93853c5a456b74/raw/157549c7a77261e906fb88bc5606afd8bd727a73/oclint.rb```). -- [gcovr](http://gcovr.com) installed +### Complexity -###Installation (once for all your Objective-C projects) -- Install [the plugin](http://bit.ly/18A7OkE) through the Update Center (of SonarQube) or download it into the $SONARQUBE_HOME/extensions/plugins directory -- Copy [run-sonar.sh](https://rawgithub.com/octo-technology/sonar-objective-c/master/src/main/shell/run-sonar.sh) somewhere in your PATH -- Restart the SonarQube server. +Use [Lizard](https://github.com/terryyin/lizard) (```pip install lizard```) +to produce an XML report that can be imported by this plugin. -###Configuration (once per project) -- Copy [sonar-project.properties](https://rawgithub.com/octo-technology/sonar-objective-c/master/sample/sonar-project.properties) in your Xcode project root folder (along your .xcodeproj file) -- Edit the *sonar-project.properties* file to match your Xcode iOS/MacOS project -**The good news is that you don't have to modify your Xcode project to enable SonarQube!**. Ok, there might be one needed modification if you don't have a specific scheme for your test target, but that's all. +## Installation (once for all your Objective-C projects) -###Analysis -- Run the script ```run-sonar.sh``` in your Xcode project root folder +1. Install [the plugin](http://bit.ly/18A7OkE) through the Update Center (of SonarQube) or download it into the $SONARQUBE_HOME/extensions/plugins directory +2. Restart the SonarQube server. + + +## Configuration (once per project) + +Create a ```sonar-project.properties``` file defining some basic project +configuration and the location of the reports you want to import. + +The good news is that you don't have to modify your Xcode project to enable +SonarQube! Ok, there might be needed modification if you don't have a +specific scheme for your test target or if coverage is not enabled, but that's all. + + +## Analysis + +- Run your build script to produce the various reports +- Run ```sonar-runner``` - Enjoy or file an issue! -###Update (once per plugin update) + +## Troubleshooting + +If the results from a report don't show up, make sure any relative file or +directory paths in the report match the paths of the files as configured +and indexed by SonarQube. Typically files are indexed relative to the base +directory of the project/module being analyzed. + +For JUnit reports, most tools only record the classname, so make sure your +```*.m``` file is named the same as the classname it contains. Otherwise, the +plugin won't be able to find the test class. + + +## Update + - Install the [latest plugin](http://bit.ly/18A7OkE) version -- Copy [run-sonar.sh](https://rawgithub.com/octo-technology/sonar-objective-c/master/src/main/shell/run-sonar.sh) somewhere in your PATH +- Check for documented migration steps + +### Migration to v0.5.x + +- Analysis property names have changed. Check the sample. +- Cobertura, JUnit, OCLint, and Lizard report properties no longer have defaults +- Coverage report property no longer supports pattern matching. Only one coverage XML file is supported. +- ```sonar.language``` key changed from ```objc``` to ```objectivec``` + - As a side effect you may have to reconfigure your Quality Profiles -If you still have *run-sonar.sh* file in each of your project (not recommended), you will need to update all those files. -###Credits -* **Cyril Picat** -* **Gilles Grousset** -* **Denis Bregeon** -* **François Helg** -* **Romain Felden** -* **Mete Balci** +## Contributors -###History +- Cyril Picat +- Gilles Grousset +- Denis Bregeon +- François Helg +- Romain Felden +- Mete Balci +- Andrés Gil Herrera +- Matthew DeTullio + + +## History + +- v0.5.0 (2015/11): + - added support for Clang + - made properties configurable in SonarQube UI + - major refactoring + - decouple report imports from the language so they can also be used with the commercial plugin +- v0.4.1 (2015/05): added support for Lizard to implement complexity metrics. - v0.4.0 (2015/01): support for SonarQube >= 4.3 (4.x & 5.x) - v0.3.1 (2013/10): fix release - v0.3 (2013/10): added support for OCUnit tests and test coverage - v0.2 (2013/10): added OCLint checks as SonarQube violations - v0.0.1 (2012/09): v0 with basic metrics such as nb lines of code, nb lines of comment, nb of files, duplications -###License -SonarQube Plugin for Objective C is released under the GNU LGPL 3 license: +## License + +SonarQube Plugin for Objective-C is released under the GNU LGPL 3 license: http://www.gnu.org/licenses/lgpl.txt diff --git a/build-and-deploy.sh b/build-and-deploy.sh deleted file mode 100755 index f2e7c47b..00000000 --- a/build-and-deploy.sh +++ /dev/null @@ -1,24 +0,0 @@ -#!/bin/sh -# Build and install snapshot plugin in Sonar - -# Build first and check status -mvn clean install -if [ "$?" != 0 ]; then - echo "ERROR - Java build failed!" 1>&2 - exit $? -fi - -# Run shell tests -#shelltest src/test/shell --execdir --diff -#if [ "$?" != 0 ]; then -# echo "ERROR - Shell tests failed!" 1>&2 -# exit $? -#fi - -# Deploy new verion of plugin in Sonar dir -cp target/*.jar $SONARQUBE_HOME/extensions/plugins - -# Stop/start Sonar -$SONARQUBE_HOME/bin/macosx-universal-64/sonar.sh stop -$SONARQUBE_HOME/bin/macosx-universal-64/sonar.sh start - diff --git a/its/plugin/pom.xml b/its/plugin/pom.xml new file mode 100644 index 00000000..2a092b7b --- /dev/null +++ b/its/plugin/pom.xml @@ -0,0 +1,32 @@ + + + 4.0.0 + + + org.sonarqubecommunity.objectivec + objective-c-its + 0.5.0-SNAPSHOT + + + objective-c-its-plugin + + SonarQube Objective-C (Community) :: ITs :: Plugin + pom + + + false + + + + tests + + + + + it-plugin + + false + + + + diff --git a/its/plugin/projects/AFNetworking/.cocoadocs.yml b/its/plugin/projects/AFNetworking/.cocoadocs.yml new file mode 100644 index 00000000..aaf16cb1 --- /dev/null +++ b/its/plugin/projects/AFNetworking/.cocoadocs.yml @@ -0,0 +1,7 @@ +highlight-color: "#F89915" +highlight-dark-color: "#E23B1B" +darker-color: "#D8A688" +darker-dark-color: "#E93D1C" +background-color: "#E9DFDB" +alt-link-color: "#E23B1B" +warning-color: "#E23B1B" diff --git a/its/plugin/projects/AFNetworking/.gitignore b/its/plugin/projects/AFNetworking/.gitignore new file mode 100644 index 00000000..ca205d04 --- /dev/null +++ b/its/plugin/projects/AFNetworking/.gitignore @@ -0,0 +1,29 @@ +# Xcode +.DS_Store +build/ +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +*.xcworkspace +!default.xcworkspace +xcuserdata +profile +*.moved-aside +DerivedData +.idea/ +Tests/Pods +Tests/Podfile.lock +Tests/AFNetworking Tests.xcodeproj/xcshareddata/xcschemes/ +AFNetworking.framework.zip + +# Fastlane +/fastlane/report.xml +/fastlane/.env*private* +fastlane/test-output/* + +Carthage/Build diff --git a/its/plugin/projects/AFNetworking/AFNetworking.podspec b/its/plugin/projects/AFNetworking/AFNetworking.podspec new file mode 100644 index 00000000..3241d77b --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking.podspec @@ -0,0 +1,79 @@ +Pod::Spec.new do |s| + s.name = 'AFNetworking' + s.version = '3.0.4' + s.license = 'MIT' + s.summary = 'A delightful iOS and OS X networking framework.' + s.homepage = 'https://github.com/AFNetworking/AFNetworking' + s.social_media_url = 'https://twitter.com/AFNetworking' + s.authors = { 'Mattt Thompson' => 'm@mattt.me' } + s.source = { :git => 'https://github.com/AFNetworking/AFNetworking.git', :tag => s.version, :submodules => true } + s.requires_arc = true + + s.public_header_files = 'AFNetworking/AFNetworking.h' + s.source_files = 'AFNetworking/AFNetworking.h' + + pch_AF = <<-EOS +#ifndef TARGET_OS_IOS + #define TARGET_OS_IOS TARGET_OS_IPHONE +#endif + +#ifndef TARGET_OS_WATCH + #define TARGET_OS_WATCH 0 +#endif + +#ifndef TARGET_OS_TV + #define TARGET_OS_TV 0 +#endif +EOS + s.prefix_header_contents = pch_AF + + s.ios.deployment_target = '7.0' + s.osx.deployment_target = '10.9' + s.watchos.deployment_target = '2.0' + s.tvos.deployment_target = '9.0' + + s.subspec 'Serialization' do |ss| + ss.source_files = 'AFNetworking/AFURL{Request,Response}Serialization.{h,m}' + ss.public_header_files = 'AFNetworking/AFURL{Request,Response}Serialization.h' + ss.watchos.frameworks = 'MobileCoreServices', 'CoreGraphics' + ss.ios.frameworks = 'MobileCoreServices', 'CoreGraphics' + ss.osx.frameworks = 'CoreServices' + end + + s.subspec 'Security' do |ss| + ss.source_files = 'AFNetworking/AFSecurityPolicy.{h,m}' + ss.public_header_files = 'AFNetworking/AFSecurityPolicy.h' + ss.frameworks = 'Security' + end + + s.subspec 'Reachability' do |ss| + ss.ios.deployment_target = '7.0' + ss.osx.deployment_target = '10.9' + ss.tvos.deployment_target = '9.0' + + ss.source_files = 'AFNetworking/AFNetworkReachabilityManager.{h,m}' + ss.public_header_files = 'AFNetworking/AFNetworkReachabilityManager.h' + + ss.frameworks = 'SystemConfiguration' + end + + s.subspec 'NSURLSession' do |ss| + ss.dependency 'AFNetworking/Serialization' + ss.ios.dependency 'AFNetworking/Reachability' + ss.osx.dependency 'AFNetworking/Reachability' + ss.tvos.dependency 'AFNetworking/Reachability' + ss.dependency 'AFNetworking/Security' + + ss.source_files = 'AFNetworking/AF{URL,HTTP}SessionManager.{h,m}' + ss.public_header_files = 'AFNetworking/AF{URL,HTTP}SessionManager.h' + end + + s.subspec 'UIKit' do |ss| + ss.ios.deployment_target = '7.0' + ss.tvos.deployment_target = '9.0' + ss.dependency 'AFNetworking/NSURLSession' + + ss.public_header_files = 'UIKit+AFNetworking/*.h' + ss.source_files = 'UIKit+AFNetworking' + end +end diff --git a/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/project.pbxproj b/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/project.pbxproj new file mode 100644 index 00000000..337d8707 --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/project.pbxproj @@ -0,0 +1,1512 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 1FE783011C5857A100A73B7C /* httpbinorg_01192017.cer in Resources */ = {isa = PBXBuildFile; fileRef = 1FE783001C58579D00A73B7C /* httpbinorg_01192017.cer */; }; + 1FE783021C5857A100A73B7C /* httpbinorg_01192017.cer in Resources */ = {isa = PBXBuildFile; fileRef = 1FE783001C58579D00A73B7C /* httpbinorg_01192017.cer */; }; + 1FE783031C5857A200A73B7C /* httpbinorg_01192017.cer in Resources */ = {isa = PBXBuildFile; fileRef = 1FE783001C58579D00A73B7C /* httpbinorg_01192017.cer */; }; + 2960BAC31C1B2F1A00BA02F0 /* AFUIButtonTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 2960BAC21C1B2F1A00BA02F0 /* AFUIButtonTests.m */; }; + 297824A31BC2D69A0041C395 /* adn_0.cer in Resources */ = {isa = PBXBuildFile; fileRef = 297824A01BC2D69A0041C395 /* adn_0.cer */; }; + 297824A41BC2D69A0041C395 /* adn_0.cer in Resources */ = {isa = PBXBuildFile; fileRef = 297824A01BC2D69A0041C395 /* adn_0.cer */; }; + 297824A51BC2D69A0041C395 /* adn_1.cer in Resources */ = {isa = PBXBuildFile; fileRef = 297824A11BC2D69A0041C395 /* adn_1.cer */; }; + 297824A61BC2D69A0041C395 /* adn_1.cer in Resources */ = {isa = PBXBuildFile; fileRef = 297824A11BC2D69A0041C395 /* adn_1.cer */; }; + 297824A71BC2D69A0041C395 /* adn_2.cer in Resources */ = {isa = PBXBuildFile; fileRef = 297824A21BC2D69A0041C395 /* adn_2.cer */; }; + 297824A81BC2D69A0041C395 /* adn_2.cer in Resources */ = {isa = PBXBuildFile; fileRef = 297824A21BC2D69A0041C395 /* adn_2.cer */; }; + 297824AA1BC2DAD80041C395 /* AFAutoPurgingImageCacheTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C801BC2C88F00FD3B3E /* AFAutoPurgingImageCacheTests.m */; }; + 297824AB1BC2DB060041C395 /* AFNetworking.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 299522391BBF104D00859F49 /* AFNetworking.framework */; }; + 297824AC1BC2DB450041C395 /* AFImageDownloaderTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C841BC2C88F00FD3B3E /* AFImageDownloaderTests.m */; }; + 297824AD1BC2DBA40041C395 /* AFNetworkActivityManagerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C861BC2C88F00FD3B3E /* AFNetworkActivityManagerTests.m */; }; + 297824AE1BC2DBD80041C395 /* AFUIActivityIndicatorViewTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8C1BC2C88F00FD3B3E /* AFUIActivityIndicatorViewTests.m */; }; + 297824AF1BC2DBEF0041C395 /* AFUIRefreshControlTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8E1BC2C88F00FD3B3E /* AFUIRefreshControlTests.m */; }; + 297824B01BC2DC2D0041C395 /* AFUIImageViewTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8D1BC2C88F00FD3B3E /* AFUIImageViewTests.m */; }; + 2987B0AF1BC408A200179A4C /* AFNetworking.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2987B0A51BC408A200179A4C /* AFNetworking.framework */; }; + 2987B0BC1BC408D900179A4C /* AFHTTPSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522471BBF125A00859F49 /* AFHTTPSessionManager.m */; }; + 2987B0BD1BC408D900179A4C /* AFNetworkReachabilityManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224A1BBF125A00859F49 /* AFNetworkReachabilityManager.m */; }; + 2987B0BE1BC408D900179A4C /* AFSecurityPolicy.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224C1BBF125A00859F49 /* AFSecurityPolicy.m */; }; + 2987B0BF1BC408D900179A4C /* AFURLRequestSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224E1BBF125A00859F49 /* AFURLRequestSerialization.m */; }; + 2987B0C01BC408D900179A4C /* AFURLResponseSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522501BBF125A00859F49 /* AFURLResponseSerialization.m */; }; + 2987B0C11BC408D900179A4C /* AFURLSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522521BBF125A00859F49 /* AFURLSessionManager.m */; }; + 2987B0C21BC408F900179A4C /* AFAutoPurgingImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522871BBF13C700859F49 /* AFAutoPurgingImageCache.m */; }; + 2987B0C31BC408F900179A4C /* AFImageDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522891BBF13C700859F49 /* AFImageDownloader.m */; }; + 2987B0C41BC408F900179A4C /* UIActivityIndicatorView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995228D1BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.m */; }; + 2987B0C51BC408F900179A4C /* UIButton+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522911BBF13C700859F49 /* UIButton+AFNetworking.m */; }; + 2987B0C61BC408F900179A4C /* UIImageView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522941BBF13C700859F49 /* UIImageView+AFNetworking.m */; }; + 2987B0C71BC408F900179A4C /* UIProgressView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522971BBF13C700859F49 /* UIProgressView+AFNetworking.m */; }; + 2987B0CA1BC40A7600179A4C /* AFHTTPRequestSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C811BC2C88F00FD3B3E /* AFHTTPRequestSerializationTests.m */; }; + 2987B0CB1BC40A7600179A4C /* AFHTTPResponseSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C821BC2C88F00FD3B3E /* AFHTTPResponseSerializationTests.m */; }; + 2987B0CC1BC40A7600179A4C /* AFHTTPSessionManagerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C831BC2C88F00FD3B3E /* AFHTTPSessionManagerTests.m */; }; + 2987B0CD1BC40A7600179A4C /* AFJSONSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C851BC2C88F00FD3B3E /* AFJSONSerializationTests.m */; }; + 2987B0CE1BC40A7600179A4C /* AFNetworkReachabilityManagerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C871BC2C88F00FD3B3E /* AFNetworkReachabilityManagerTests.m */; }; + 2987B0CF1BC40A7600179A4C /* AFPropertyListResponseSerializerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C881BC2C88F00FD3B3E /* AFPropertyListResponseSerializerTests.m */; }; + 2987B0D01BC40A7600179A4C /* AFSecurityPolicyTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C891BC2C88F00FD3B3E /* AFSecurityPolicyTests.m */; }; + 2987B0D11BC40A7600179A4C /* AFURLSessionManagerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8F1BC2C88F00FD3B3E /* AFURLSessionManagerTests.m */; }; + 2987B0D21BC40AD800179A4C /* AFTestCase.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8B1BC2C88F00FD3B3E /* AFTestCase.m */; }; + 2987B0D31BC40AE900179A4C /* adn_0.cer in Resources */ = {isa = PBXBuildFile; fileRef = 297824A01BC2D69A0041C395 /* adn_0.cer */; }; + 2987B0D41BC40AE900179A4C /* adn_1.cer in Resources */ = {isa = PBXBuildFile; fileRef = 297824A11BC2D69A0041C395 /* adn_1.cer */; }; + 2987B0D51BC40AE900179A4C /* adn_2.cer in Resources */ = {isa = PBXBuildFile; fileRef = 297824A21BC2D69A0041C395 /* adn_2.cer */; }; + 2987B0D61BC40AEC00179A4C /* ADNNetServerTrustChain in Resources */ = {isa = PBXBuildFile; fileRef = 298D7CDF1BC2CB5A00FD3B3E /* ADNNetServerTrustChain */; }; + 2987B0D71BC40AF000179A4C /* HTTPBinOrgServerTrustChain in Resources */ = {isa = PBXBuildFile; fileRef = 298D7CE21BC2CB7C00FD3B3E /* HTTPBinOrgServerTrustChain */; }; + 2987B0D81BC40AF300179A4C /* AddTrust_External_CA_Root.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C6E1BC2C88F00FD3B3E /* AddTrust_External_CA_Root.cer */; }; + 2987B0D91BC40AF300179A4C /* COMODO_RSA_Certification_Authority.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C6F1BC2C88F00FD3B3E /* COMODO_RSA_Certification_Authority.cer */; }; + 2987B0DA1BC40AF300179A4C /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C701BC2C88F00FD3B3E /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer */; }; + 2987B0DC1BC40AF600179A4C /* logo.png in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C771BC2C88F00FD3B3E /* logo.png */; }; + 2987B0DD1BC40AFB00179A4C /* AltName.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C791BC2C88F00FD3B3E /* AltName.cer */; }; + 2987B0DE1BC40AFB00179A4C /* foobar.com.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C7A1BC2C88F00FD3B3E /* foobar.com.cer */; }; + 2987B0DF1BC40AFB00179A4C /* NoDomains.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C7B1BC2C88F00FD3B3E /* NoDomains.cer */; }; + 2987B0E01BC40B0900179A4C /* AFAutoPurgingImageCacheTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C801BC2C88F00FD3B3E /* AFAutoPurgingImageCacheTests.m */; }; + 2987B0E11BC40B0900179A4C /* AFImageDownloaderTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C841BC2C88F00FD3B3E /* AFImageDownloaderTests.m */; }; + 2987B0E31BC40B0900179A4C /* AFUIActivityIndicatorViewTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8C1BC2C88F00FD3B3E /* AFUIActivityIndicatorViewTests.m */; }; + 2987B0E41BC40B0900179A4C /* AFUIImageViewTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8D1BC2C88F00FD3B3E /* AFUIImageViewTests.m */; }; + 298D7C4F1BC2C7B200FD3B3E /* AFNetworking.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 299522771BBF136400859F49 /* AFNetworking.framework */; }; + 298D7C961BC2C94400FD3B3E /* AFTestCase.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8B1BC2C88F00FD3B3E /* AFTestCase.m */; }; + 298D7C971BC2C94500FD3B3E /* AFTestCase.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8B1BC2C88F00FD3B3E /* AFTestCase.m */; }; + 298D7C981BC2CA2500FD3B3E /* AFURLSessionManagerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8F1BC2C88F00FD3B3E /* AFURLSessionManagerTests.m */; }; + 298D7C991BC2CA2600FD3B3E /* AFURLSessionManagerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8F1BC2C88F00FD3B3E /* AFURLSessionManagerTests.m */; }; + 298D7CB11BC2CA6E00FD3B3E /* AFHTTPRequestSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C811BC2C88F00FD3B3E /* AFHTTPRequestSerializationTests.m */; }; + 298D7CB21BC2CA6E00FD3B3E /* AFHTTPRequestSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C811BC2C88F00FD3B3E /* AFHTTPRequestSerializationTests.m */; }; + 298D7CB91BC2CA9800FD3B3E /* logo.png in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C771BC2C88F00FD3B3E /* logo.png */; }; + 298D7CBA1BC2CA9800FD3B3E /* logo.png in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C771BC2C88F00FD3B3E /* logo.png */; }; + 298D7CBB1BC2CA9C00FD3B3E /* AltName.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C791BC2C88F00FD3B3E /* AltName.cer */; }; + 298D7CBC1BC2CA9C00FD3B3E /* foobar.com.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C7A1BC2C88F00FD3B3E /* foobar.com.cer */; }; + 298D7CBD1BC2CA9C00FD3B3E /* NoDomains.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C7B1BC2C88F00FD3B3E /* NoDomains.cer */; }; + 298D7CBE1BC2CA9D00FD3B3E /* AltName.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C791BC2C88F00FD3B3E /* AltName.cer */; }; + 298D7CBF1BC2CA9D00FD3B3E /* foobar.com.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C7A1BC2C88F00FD3B3E /* foobar.com.cer */; }; + 298D7CC01BC2CA9D00FD3B3E /* NoDomains.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C7B1BC2C88F00FD3B3E /* NoDomains.cer */; }; + 298D7CC11BC2CAA100FD3B3E /* AddTrust_External_CA_Root.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C6E1BC2C88F00FD3B3E /* AddTrust_External_CA_Root.cer */; }; + 298D7CC21BC2CAA100FD3B3E /* COMODO_RSA_Certification_Authority.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C6F1BC2C88F00FD3B3E /* COMODO_RSA_Certification_Authority.cer */; }; + 298D7CC31BC2CAA100FD3B3E /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C701BC2C88F00FD3B3E /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer */; }; + 298D7CC51BC2CAA200FD3B3E /* AddTrust_External_CA_Root.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C6E1BC2C88F00FD3B3E /* AddTrust_External_CA_Root.cer */; }; + 298D7CC61BC2CAA200FD3B3E /* COMODO_RSA_Certification_Authority.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C6F1BC2C88F00FD3B3E /* COMODO_RSA_Certification_Authority.cer */; }; + 298D7CC71BC2CAA200FD3B3E /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C701BC2C88F00FD3B3E /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer */; }; + 298D7CD31BC2CAE800FD3B3E /* AFHTTPResponseSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C821BC2C88F00FD3B3E /* AFHTTPResponseSerializationTests.m */; }; + 298D7CD41BC2CAE900FD3B3E /* AFHTTPResponseSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C821BC2C88F00FD3B3E /* AFHTTPResponseSerializationTests.m */; }; + 298D7CD51BC2CAEC00FD3B3E /* AFHTTPSessionManagerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C831BC2C88F00FD3B3E /* AFHTTPSessionManagerTests.m */; }; + 298D7CD61BC2CAED00FD3B3E /* AFHTTPSessionManagerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C831BC2C88F00FD3B3E /* AFHTTPSessionManagerTests.m */; }; + 298D7CD71BC2CAEF00FD3B3E /* AFJSONSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C851BC2C88F00FD3B3E /* AFJSONSerializationTests.m */; }; + 298D7CD81BC2CAF000FD3B3E /* AFJSONSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C851BC2C88F00FD3B3E /* AFJSONSerializationTests.m */; }; + 298D7CD91BC2CAF200FD3B3E /* AFNetworkReachabilityManagerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C871BC2C88F00FD3B3E /* AFNetworkReachabilityManagerTests.m */; }; + 298D7CDA1BC2CAF300FD3B3E /* AFNetworkReachabilityManagerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C871BC2C88F00FD3B3E /* AFNetworkReachabilityManagerTests.m */; }; + 298D7CDB1BC2CAF500FD3B3E /* AFPropertyListResponseSerializerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C881BC2C88F00FD3B3E /* AFPropertyListResponseSerializerTests.m */; }; + 298D7CDC1BC2CAF500FD3B3E /* AFPropertyListResponseSerializerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C881BC2C88F00FD3B3E /* AFPropertyListResponseSerializerTests.m */; }; + 298D7CDD1BC2CAF700FD3B3E /* AFSecurityPolicyTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C891BC2C88F00FD3B3E /* AFSecurityPolicyTests.m */; }; + 298D7CDE1BC2CAF800FD3B3E /* AFSecurityPolicyTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C891BC2C88F00FD3B3E /* AFSecurityPolicyTests.m */; }; + 298D7CE01BC2CB5A00FD3B3E /* ADNNetServerTrustChain in Resources */ = {isa = PBXBuildFile; fileRef = 298D7CDF1BC2CB5A00FD3B3E /* ADNNetServerTrustChain */; }; + 298D7CE11BC2CB5A00FD3B3E /* ADNNetServerTrustChain in Resources */ = {isa = PBXBuildFile; fileRef = 298D7CDF1BC2CB5A00FD3B3E /* ADNNetServerTrustChain */; }; + 298D7CE31BC2CB7C00FD3B3E /* HTTPBinOrgServerTrustChain in Resources */ = {isa = PBXBuildFile; fileRef = 298D7CE21BC2CB7C00FD3B3E /* HTTPBinOrgServerTrustChain */; }; + 298D7CE41BC2CB7C00FD3B3E /* HTTPBinOrgServerTrustChain in Resources */ = {isa = PBXBuildFile; fileRef = 298D7CE21BC2CB7C00FD3B3E /* HTTPBinOrgServerTrustChain */; }; + 2995223D1BBF104D00859F49 /* AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995223C1BBF104D00859F49 /* AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522531BBF125A00859F49 /* AFHTTPSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522461BBF125A00859F49 /* AFHTTPSessionManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522541BBF125A00859F49 /* AFHTTPSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522471BBF125A00859F49 /* AFHTTPSessionManager.m */; }; + 299522561BBF125A00859F49 /* AFNetworkReachabilityManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522491BBF125A00859F49 /* AFNetworkReachabilityManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522571BBF125A00859F49 /* AFNetworkReachabilityManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224A1BBF125A00859F49 /* AFNetworkReachabilityManager.m */; }; + 299522581BBF125A00859F49 /* AFSecurityPolicy.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224B1BBF125A00859F49 /* AFSecurityPolicy.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522591BBF125A00859F49 /* AFSecurityPolicy.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224C1BBF125A00859F49 /* AFSecurityPolicy.m */; }; + 2995225A1BBF125A00859F49 /* AFURLRequestSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224D1BBF125A00859F49 /* AFURLRequestSerialization.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2995225B1BBF125A00859F49 /* AFURLRequestSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224E1BBF125A00859F49 /* AFURLRequestSerialization.m */; }; + 2995225C1BBF125A00859F49 /* AFURLResponseSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224F1BBF125A00859F49 /* AFURLResponseSerialization.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2995225D1BBF125A00859F49 /* AFURLResponseSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522501BBF125A00859F49 /* AFURLResponseSerialization.m */; }; + 2995225E1BBF125A00859F49 /* AFURLSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522511BBF125A00859F49 /* AFURLSessionManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2995225F1BBF125A00859F49 /* AFURLSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522521BBF125A00859F49 /* AFURLSessionManager.m */; }; + 2995226D1BBF133400859F49 /* AFHTTPSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522471BBF125A00859F49 /* AFHTTPSessionManager.m */; }; + 2995226E1BBF133400859F49 /* AFSecurityPolicy.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224C1BBF125A00859F49 /* AFSecurityPolicy.m */; }; + 2995226F1BBF133400859F49 /* AFURLRequestSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224E1BBF125A00859F49 /* AFURLRequestSerialization.m */; }; + 299522701BBF133400859F49 /* AFURLResponseSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522501BBF125A00859F49 /* AFURLResponseSerialization.m */; }; + 299522711BBF133400859F49 /* AFURLSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522521BBF125A00859F49 /* AFURLSessionManager.m */; }; + 2995227F1BBF13A100859F49 /* AFHTTPSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522471BBF125A00859F49 /* AFHTTPSessionManager.m */; }; + 299522801BBF13A100859F49 /* AFNetworkReachabilityManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224A1BBF125A00859F49 /* AFNetworkReachabilityManager.m */; }; + 299522811BBF13A100859F49 /* AFSecurityPolicy.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224C1BBF125A00859F49 /* AFSecurityPolicy.m */; }; + 299522821BBF13A100859F49 /* AFURLRequestSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224E1BBF125A00859F49 /* AFURLRequestSerialization.m */; }; + 299522831BBF13A100859F49 /* AFURLResponseSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522501BBF125A00859F49 /* AFURLResponseSerialization.m */; }; + 299522841BBF13A100859F49 /* AFURLSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522521BBF125A00859F49 /* AFURLSessionManager.m */; }; + 2995229C1BBF13C700859F49 /* AFAutoPurgingImageCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522861BBF13C700859F49 /* AFAutoPurgingImageCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2995229D1BBF13C700859F49 /* AFAutoPurgingImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522871BBF13C700859F49 /* AFAutoPurgingImageCache.m */; }; + 2995229E1BBF13C700859F49 /* AFImageDownloader.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522881BBF13C700859F49 /* AFImageDownloader.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2995229F1BBF13C700859F49 /* AFImageDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522891BBF13C700859F49 /* AFImageDownloader.m */; }; + 299522A01BBF13C700859F49 /* AFNetworkActivityIndicatorManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995228A1BBF13C700859F49 /* AFNetworkActivityIndicatorManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522A11BBF13C700859F49 /* AFNetworkActivityIndicatorManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995228B1BBF13C700859F49 /* AFNetworkActivityIndicatorManager.m */; }; + 299522A21BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995228C1BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522A31BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995228D1BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.m */; }; + 299522A61BBF13C700859F49 /* UIButton+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522901BBF13C700859F49 /* UIButton+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522A71BBF13C700859F49 /* UIButton+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522911BBF13C700859F49 /* UIButton+AFNetworking.m */; }; + 299522A81BBF13C700859F49 /* UIImage+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522921BBF13C700859F49 /* UIImage+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522A91BBF13C700859F49 /* UIImageView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522931BBF13C700859F49 /* UIImageView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522AA1BBF13C700859F49 /* UIImageView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522941BBF13C700859F49 /* UIImageView+AFNetworking.m */; }; + 299522AC1BBF13C700859F49 /* UIProgressView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522961BBF13C700859F49 /* UIProgressView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522AD1BBF13C700859F49 /* UIProgressView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522971BBF13C700859F49 /* UIProgressView+AFNetworking.m */; }; + 299522AE1BBF13C700859F49 /* UIRefreshControl+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522981BBF13C700859F49 /* UIRefreshControl+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522AF1BBF13C700859F49 /* UIRefreshControl+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522991BBF13C700859F49 /* UIRefreshControl+AFNetworking.m */; }; + 299522B01BBF13C700859F49 /* UIWebView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995229A1BBF13C700859F49 /* UIWebView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522B11BBF13C700859F49 /* UIWebView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995229B1BBF13C700859F49 /* UIWebView+AFNetworking.m */; }; + 29D3413F1C20D46400A7D266 /* AFCompoundResponseSerializerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 29D3413E1C20D46400A7D266 /* AFCompoundResponseSerializerTests.m */; }; + 29D341401C20D46400A7D266 /* AFCompoundResponseSerializerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 29D3413E1C20D46400A7D266 /* AFCompoundResponseSerializerTests.m */; }; + 29D341411C20D46400A7D266 /* AFCompoundResponseSerializerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 29D3413E1C20D46400A7D266 /* AFCompoundResponseSerializerTests.m */; }; + 29D96E7A1BCC3D6000F571A5 /* AFHTTPSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522461BBF125A00859F49 /* AFHTTPSessionManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E7C1BCC3D6000F571A5 /* AFSecurityPolicy.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224B1BBF125A00859F49 /* AFSecurityPolicy.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E7D1BCC3D6000F571A5 /* AFURLRequestSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224D1BBF125A00859F49 /* AFURLRequestSerialization.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E7E1BCC3D6000F571A5 /* AFURLResponseSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224F1BBF125A00859F49 /* AFURLResponseSerialization.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E7F1BCC3D6000F571A5 /* AFURLSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522511BBF125A00859F49 /* AFURLSessionManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E801BCC3D6000F571A5 /* AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995223C1BBF104D00859F49 /* AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E811BCC3D7200F571A5 /* AFHTTPSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522461BBF125A00859F49 /* AFHTTPSessionManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E821BCC3D7200F571A5 /* AFNetworkReachabilityManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522491BBF125A00859F49 /* AFNetworkReachabilityManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E831BCC3D7200F571A5 /* AFSecurityPolicy.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224B1BBF125A00859F49 /* AFSecurityPolicy.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E841BCC3D7200F571A5 /* AFURLRequestSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224D1BBF125A00859F49 /* AFURLRequestSerialization.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E851BCC3D7200F571A5 /* AFURLResponseSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224F1BBF125A00859F49 /* AFURLResponseSerialization.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E861BCC3D7200F571A5 /* AFURLSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522511BBF125A00859F49 /* AFURLSessionManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E871BCC3D7200F571A5 /* AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995223C1BBF104D00859F49 /* AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E881BCC3D7D00F571A5 /* AFHTTPSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522461BBF125A00859F49 /* AFHTTPSessionManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E891BCC3D7D00F571A5 /* AFNetworkReachabilityManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522491BBF125A00859F49 /* AFNetworkReachabilityManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E8A1BCC3D7D00F571A5 /* AFSecurityPolicy.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224B1BBF125A00859F49 /* AFSecurityPolicy.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E8B1BCC3D7D00F571A5 /* AFURLRequestSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224D1BBF125A00859F49 /* AFURLRequestSerialization.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E8C1BCC3D7D00F571A5 /* AFURLResponseSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224F1BBF125A00859F49 /* AFURLResponseSerialization.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E8D1BCC3D7D00F571A5 /* AFURLSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522511BBF125A00859F49 /* AFURLSessionManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E8E1BCC3D7D00F571A5 /* AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995223C1BBF104D00859F49 /* AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E941BCC406B00F571A5 /* AFAutoPurgingImageCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522861BBF13C700859F49 /* AFAutoPurgingImageCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E951BCC406B00F571A5 /* AFImageDownloader.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522881BBF13C700859F49 /* AFImageDownloader.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E961BCC406B00F571A5 /* UIActivityIndicatorView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995228C1BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E971BCC406B00F571A5 /* UIButton+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522901BBF13C700859F49 /* UIButton+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E981BCC406B00F571A5 /* UIImage+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522921BBF13C700859F49 /* UIImage+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E991BCC406B00F571A5 /* UIImageView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522931BBF13C700859F49 /* UIImageView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E9A1BCC406B00F571A5 /* UIProgressView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522961BBF13C700859F49 /* UIProgressView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29F5EF031C47E64F008B976A /* AFUIWebViewTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 29F5EF021C47E64F008B976A /* AFUIWebViewTests.m */; }; + 5F4323BB1BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323B31BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer */; }; + 5F4323BC1BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323B31BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer */; }; + 5F4323BD1BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323B31BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer */; }; + 5F4323BE1BF63741003B8749 /* GeoTrust_Global_CA-cross.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323B41BF63741003B8749 /* GeoTrust_Global_CA-cross.cer */; }; + 5F4323BF1BF63741003B8749 /* GeoTrust_Global_CA-cross.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323B41BF63741003B8749 /* GeoTrust_Global_CA-cross.cer */; }; + 5F4323C01BF63741003B8749 /* GeoTrust_Global_CA-cross.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323B41BF63741003B8749 /* GeoTrust_Global_CA-cross.cer */; }; + 5F4323C11BF63741003B8749 /* google.com.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323B51BF63741003B8749 /* google.com.cer */; }; + 5F4323C21BF63741003B8749 /* google.com.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323B51BF63741003B8749 /* google.com.cer */; }; + 5F4323C31BF63741003B8749 /* google.com.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323B51BF63741003B8749 /* google.com.cer */; }; + 5F4323CD1BF63741003B8749 /* GoogleInternetAuthorityG2.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323BA1BF63741003B8749 /* GoogleInternetAuthorityG2.cer */; }; + 5F4323CE1BF63741003B8749 /* GoogleInternetAuthorityG2.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323BA1BF63741003B8749 /* GoogleInternetAuthorityG2.cer */; }; + 5F4323CF1BF63741003B8749 /* GoogleInternetAuthorityG2.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323BA1BF63741003B8749 /* GoogleInternetAuthorityG2.cer */; }; + 5F4323D51BF63CB0003B8749 /* GoogleComServerTrustChainPath1 in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323D41BF63CB0003B8749 /* GoogleComServerTrustChainPath1 */; }; + 5F4323D61BF63CB0003B8749 /* GoogleComServerTrustChainPath1 in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323D41BF63CB0003B8749 /* GoogleComServerTrustChainPath1 */; }; + 5F4323D71BF63CB0003B8749 /* GoogleComServerTrustChainPath1 in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323D41BF63CB0003B8749 /* GoogleComServerTrustChainPath1 */; }; + 5F4323D91BF63CBA003B8749 /* GoogleComServerTrustChainPath2 in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323D81BF63CBA003B8749 /* GoogleComServerTrustChainPath2 */; }; + 5F4323DA1BF63CBA003B8749 /* GoogleComServerTrustChainPath2 in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323D81BF63CBA003B8749 /* GoogleComServerTrustChainPath2 */; }; + 5F4323DB1BF63CBA003B8749 /* GoogleComServerTrustChainPath2 in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323D81BF63CBA003B8749 /* GoogleComServerTrustChainPath2 */; }; + 5F4323DD1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323DC1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer */; }; + 5F4323DE1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323DC1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer */; }; + 5F4323DF1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323DC1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 2987B0B01BC408A200179A4C /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 299522301BBF104D00859F49 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 2987B0A41BC408A200179A4C; + remoteInfo = "AFNetworking tvOS"; + }; + 298D7C411BC2C79500FD3B3E /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 299522301BBF104D00859F49 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 299522381BBF104D00859F49; + remoteInfo = "AFNetworking iOS"; + }; + 298D7C501BC2C7B200FD3B3E /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 299522301BBF104D00859F49 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 299522761BBF136400859F49; + remoteInfo = "AFNetworking OS X"; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 1FE783001C58579D00A73B7C /* httpbinorg_01192017.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = httpbinorg_01192017.cer; sourceTree = ""; }; + 2960BAC21C1B2F1A00BA02F0 /* AFUIButtonTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFUIButtonTests.m; sourceTree = ""; }; + 297824A01BC2D69A0041C395 /* adn_0.cer */ = {isa = PBXFileReference; lastKnownFileType = file; name = adn_0.cer; path = ADNNetServerTrustChain/adn_0.cer; sourceTree = ""; }; + 297824A11BC2D69A0041C395 /* adn_1.cer */ = {isa = PBXFileReference; lastKnownFileType = file; name = adn_1.cer; path = ADNNetServerTrustChain/adn_1.cer; sourceTree = ""; }; + 297824A21BC2D69A0041C395 /* adn_2.cer */ = {isa = PBXFileReference; lastKnownFileType = file; name = adn_2.cer; path = ADNNetServerTrustChain/adn_2.cer; sourceTree = ""; }; + 2987B0A51BC408A200179A4C /* AFNetworking.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = AFNetworking.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 2987B0AE1BC408A200179A4C /* AFNetworking tvOS Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "AFNetworking tvOS Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; + 298D7C3B1BC2C79500FD3B3E /* AFNetworking iOS Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "AFNetworking iOS Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; + 298D7C4A1BC2C7B200FD3B3E /* AFNetworking Mac OS X Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "AFNetworking Mac OS X Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; + 298D7C6E1BC2C88F00FD3B3E /* AddTrust_External_CA_Root.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = AddTrust_External_CA_Root.cer; sourceTree = ""; }; + 298D7C6F1BC2C88F00FD3B3E /* COMODO_RSA_Certification_Authority.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = COMODO_RSA_Certification_Authority.cer; sourceTree = ""; }; + 298D7C701BC2C88F00FD3B3E /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = COMODO_RSA_Domain_Validation_Secure_Server_CA.cer; sourceTree = ""; }; + 298D7C771BC2C88F00FD3B3E /* logo.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = logo.png; sourceTree = ""; }; + 298D7C791BC2C88F00FD3B3E /* AltName.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = AltName.cer; sourceTree = ""; }; + 298D7C7A1BC2C88F00FD3B3E /* foobar.com.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = foobar.com.cer; sourceTree = ""; }; + 298D7C7B1BC2C88F00FD3B3E /* NoDomains.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = NoDomains.cer; sourceTree = ""; }; + 298D7C801BC2C88F00FD3B3E /* AFAutoPurgingImageCacheTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFAutoPurgingImageCacheTests.m; sourceTree = ""; }; + 298D7C811BC2C88F00FD3B3E /* AFHTTPRequestSerializationTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFHTTPRequestSerializationTests.m; sourceTree = ""; }; + 298D7C821BC2C88F00FD3B3E /* AFHTTPResponseSerializationTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFHTTPResponseSerializationTests.m; sourceTree = ""; }; + 298D7C831BC2C88F00FD3B3E /* AFHTTPSessionManagerTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFHTTPSessionManagerTests.m; sourceTree = ""; }; + 298D7C841BC2C88F00FD3B3E /* AFImageDownloaderTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFImageDownloaderTests.m; sourceTree = ""; }; + 298D7C851BC2C88F00FD3B3E /* AFJSONSerializationTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFJSONSerializationTests.m; sourceTree = ""; }; + 298D7C861BC2C88F00FD3B3E /* AFNetworkActivityManagerTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFNetworkActivityManagerTests.m; sourceTree = ""; }; + 298D7C871BC2C88F00FD3B3E /* AFNetworkReachabilityManagerTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFNetworkReachabilityManagerTests.m; sourceTree = ""; }; + 298D7C881BC2C88F00FD3B3E /* AFPropertyListResponseSerializerTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFPropertyListResponseSerializerTests.m; sourceTree = ""; }; + 298D7C891BC2C88F00FD3B3E /* AFSecurityPolicyTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFSecurityPolicyTests.m; sourceTree = ""; }; + 298D7C8A1BC2C88F00FD3B3E /* AFTestCase.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AFTestCase.h; sourceTree = ""; }; + 298D7C8B1BC2C88F00FD3B3E /* AFTestCase.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFTestCase.m; sourceTree = ""; }; + 298D7C8C1BC2C88F00FD3B3E /* AFUIActivityIndicatorViewTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFUIActivityIndicatorViewTests.m; sourceTree = ""; }; + 298D7C8D1BC2C88F00FD3B3E /* AFUIImageViewTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFUIImageViewTests.m; sourceTree = ""; }; + 298D7C8E1BC2C88F00FD3B3E /* AFUIRefreshControlTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFUIRefreshControlTests.m; sourceTree = ""; }; + 298D7C8F1BC2C88F00FD3B3E /* AFURLSessionManagerTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFURLSessionManagerTests.m; sourceTree = ""; }; + 298D7CDF1BC2CB5A00FD3B3E /* ADNNetServerTrustChain */ = {isa = PBXFileReference; lastKnownFileType = folder; path = ADNNetServerTrustChain; sourceTree = ""; }; + 298D7CE21BC2CB7C00FD3B3E /* HTTPBinOrgServerTrustChain */ = {isa = PBXFileReference; lastKnownFileType = folder; path = HTTPBinOrgServerTrustChain; sourceTree = ""; }; + 299522391BBF104D00859F49 /* AFNetworking.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = AFNetworking.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 2995223C1BBF104D00859F49 /* AFNetworking.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = AFNetworking.h; path = ../Framework/AFNetworking.h; sourceTree = ""; }; + 2995223E1BBF104D00859F49 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = ../Framework/Info.plist; sourceTree = ""; }; + 299522461BBF125A00859F49 /* AFHTTPSessionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFHTTPSessionManager.h; sourceTree = ""; }; + 299522471BBF125A00859F49 /* AFHTTPSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFHTTPSessionManager.m; sourceTree = ""; }; + 299522491BBF125A00859F49 /* AFNetworkReachabilityManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworkReachabilityManager.h; sourceTree = ""; }; + 2995224A1BBF125A00859F49 /* AFNetworkReachabilityManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFNetworkReachabilityManager.m; sourceTree = ""; }; + 2995224B1BBF125A00859F49 /* AFSecurityPolicy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFSecurityPolicy.h; sourceTree = ""; }; + 2995224C1BBF125A00859F49 /* AFSecurityPolicy.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFSecurityPolicy.m; sourceTree = ""; }; + 2995224D1BBF125A00859F49 /* AFURLRequestSerialization.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLRequestSerialization.h; sourceTree = ""; }; + 2995224E1BBF125A00859F49 /* AFURLRequestSerialization.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLRequestSerialization.m; sourceTree = ""; }; + 2995224F1BBF125A00859F49 /* AFURLResponseSerialization.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLResponseSerialization.h; sourceTree = ""; }; + 299522501BBF125A00859F49 /* AFURLResponseSerialization.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLResponseSerialization.m; sourceTree = ""; }; + 299522511BBF125A00859F49 /* AFURLSessionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLSessionManager.h; sourceTree = ""; }; + 299522521BBF125A00859F49 /* AFURLSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLSessionManager.m; sourceTree = ""; }; + 299522651BBF129200859F49 /* AFNetworking.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = AFNetworking.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 299522771BBF136400859F49 /* AFNetworking.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = AFNetworking.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 299522861BBF13C700859F49 /* AFAutoPurgingImageCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFAutoPurgingImageCache.h; sourceTree = ""; }; + 299522871BBF13C700859F49 /* AFAutoPurgingImageCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFAutoPurgingImageCache.m; sourceTree = ""; }; + 299522881BBF13C700859F49 /* AFImageDownloader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFImageDownloader.h; sourceTree = ""; }; + 299522891BBF13C700859F49 /* AFImageDownloader.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFImageDownloader.m; sourceTree = ""; }; + 2995228A1BBF13C700859F49 /* AFNetworkActivityIndicatorManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworkActivityIndicatorManager.h; sourceTree = ""; }; + 2995228B1BBF13C700859F49 /* AFNetworkActivityIndicatorManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFNetworkActivityIndicatorManager.m; sourceTree = ""; }; + 2995228C1BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIActivityIndicatorView+AFNetworking.h"; sourceTree = ""; }; + 2995228D1BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIActivityIndicatorView+AFNetworking.m"; sourceTree = ""; }; + 299522901BBF13C700859F49 /* UIButton+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIButton+AFNetworking.h"; sourceTree = ""; }; + 299522911BBF13C700859F49 /* UIButton+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIButton+AFNetworking.m"; sourceTree = ""; }; + 299522921BBF13C700859F49 /* UIImage+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImage+AFNetworking.h"; sourceTree = ""; }; + 299522931BBF13C700859F49 /* UIImageView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImageView+AFNetworking.h"; sourceTree = ""; }; + 299522941BBF13C700859F49 /* UIImageView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImageView+AFNetworking.m"; sourceTree = ""; }; + 299522951BBF13C700859F49 /* UIKit+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIKit+AFNetworking.h"; sourceTree = ""; }; + 299522961BBF13C700859F49 /* UIProgressView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIProgressView+AFNetworking.h"; sourceTree = ""; }; + 299522971BBF13C700859F49 /* UIProgressView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIProgressView+AFNetworking.m"; sourceTree = ""; }; + 299522981BBF13C700859F49 /* UIRefreshControl+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIRefreshControl+AFNetworking.h"; sourceTree = ""; }; + 299522991BBF13C700859F49 /* UIRefreshControl+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIRefreshControl+AFNetworking.m"; sourceTree = ""; }; + 2995229A1BBF13C700859F49 /* UIWebView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIWebView+AFNetworking.h"; sourceTree = ""; }; + 2995229B1BBF13C700859F49 /* UIWebView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIWebView+AFNetworking.m"; sourceTree = ""; }; + 29D3413E1C20D46400A7D266 /* AFCompoundResponseSerializerTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFCompoundResponseSerializerTests.m; sourceTree = ""; }; + 29F5EF021C47E64F008B976A /* AFUIWebViewTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFUIWebViewTests.m; sourceTree = ""; }; + 5F4323B31BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = Equifax_Secure_Certificate_Authority_Root.cer; sourceTree = ""; }; + 5F4323B41BF63741003B8749 /* GeoTrust_Global_CA-cross.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = "GeoTrust_Global_CA-cross.cer"; sourceTree = ""; }; + 5F4323B51BF63741003B8749 /* google.com.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = google.com.cer; sourceTree = ""; }; + 5F4323BA1BF63741003B8749 /* GoogleInternetAuthorityG2.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = GoogleInternetAuthorityG2.cer; sourceTree = ""; }; + 5F4323D41BF63CB0003B8749 /* GoogleComServerTrustChainPath1 */ = {isa = PBXFileReference; lastKnownFileType = folder; path = GoogleComServerTrustChainPath1; sourceTree = ""; }; + 5F4323D81BF63CBA003B8749 /* GoogleComServerTrustChainPath2 */ = {isa = PBXFileReference; lastKnownFileType = folder; path = GoogleComServerTrustChainPath2; sourceTree = ""; }; + 5F4323DC1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = GeoTrust_Global_CA_Root.cer; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 2987B0A11BC408A200179A4C /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2987B0AB1BC408A200179A4C /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 2987B0AF1BC408A200179A4C /* AFNetworking.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 298D7C381BC2C79500FD3B3E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 297824AB1BC2DB060041C395 /* AFNetworking.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 298D7C471BC2C7B200FD3B3E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 298D7C4F1BC2C7B200FD3B3E /* AFNetworking.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522351BBF104D00859F49 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522611BBF129200859F49 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522731BBF136400859F49 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 298D7C561BC2C88F00FD3B3E /* Tests */ = { + isa = PBXGroup; + children = ( + 298D7C671BC2C88F00FD3B3E /* Resources */, + 298D7C7F1BC2C88F00FD3B3E /* Tests */, + ); + path = Tests; + sourceTree = ""; + }; + 298D7C671BC2C88F00FD3B3E /* Resources */ = { + isa = PBXGroup; + children = ( + 298D7C681BC2C88F00FD3B3E /* ADN.net */, + 298D7C6D1BC2C88F00FD3B3E /* HTTPBin.org */, + 298D7C771BC2C88F00FD3B3E /* logo.png */, + 298D7C781BC2C88F00FD3B3E /* SelfSigned */, + 5F4323B21BF63741003B8749 /* Google.com */, + ); + path = Resources; + sourceTree = ""; + }; + 298D7C681BC2C88F00FD3B3E /* ADN.net */ = { + isa = PBXGroup; + children = ( + 297824A01BC2D69A0041C395 /* adn_0.cer */, + 297824A11BC2D69A0041C395 /* adn_1.cer */, + 297824A21BC2D69A0041C395 /* adn_2.cer */, + 298D7CDF1BC2CB5A00FD3B3E /* ADNNetServerTrustChain */, + ); + path = ADN.net; + sourceTree = ""; + }; + 298D7C6D1BC2C88F00FD3B3E /* HTTPBin.org */ = { + isa = PBXGroup; + children = ( + 298D7CE21BC2CB7C00FD3B3E /* HTTPBinOrgServerTrustChain */, + 298D7C6E1BC2C88F00FD3B3E /* AddTrust_External_CA_Root.cer */, + 298D7C6F1BC2C88F00FD3B3E /* COMODO_RSA_Certification_Authority.cer */, + 298D7C701BC2C88F00FD3B3E /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer */, + 1FE783001C58579D00A73B7C /* httpbinorg_01192017.cer */, + ); + path = HTTPBin.org; + sourceTree = ""; + }; + 298D7C781BC2C88F00FD3B3E /* SelfSigned */ = { + isa = PBXGroup; + children = ( + 298D7C791BC2C88F00FD3B3E /* AltName.cer */, + 298D7C7A1BC2C88F00FD3B3E /* foobar.com.cer */, + 298D7C7B1BC2C88F00FD3B3E /* NoDomains.cer */, + ); + path = SelfSigned; + sourceTree = ""; + }; + 298D7C7F1BC2C88F00FD3B3E /* Tests */ = { + isa = PBXGroup; + children = ( + 298D7CD21BC2CAD500FD3B3E /* AFNetworking UIKit Tests */, + 298D7CD11BC2CABE00FD3B3E /* AFNetworking Tests */, + 298D7C8A1BC2C88F00FD3B3E /* AFTestCase.h */, + 298D7C8B1BC2C88F00FD3B3E /* AFTestCase.m */, + ); + path = Tests; + sourceTree = ""; + }; + 298D7CD11BC2CABE00FD3B3E /* AFNetworking Tests */ = { + isa = PBXGroup; + children = ( + 298D7C811BC2C88F00FD3B3E /* AFHTTPRequestSerializationTests.m */, + 298D7C821BC2C88F00FD3B3E /* AFHTTPResponseSerializationTests.m */, + 298D7C831BC2C88F00FD3B3E /* AFHTTPSessionManagerTests.m */, + 298D7C851BC2C88F00FD3B3E /* AFJSONSerializationTests.m */, + 298D7C881BC2C88F00FD3B3E /* AFPropertyListResponseSerializerTests.m */, + 29D3413E1C20D46400A7D266 /* AFCompoundResponseSerializerTests.m */, + 298D7C871BC2C88F00FD3B3E /* AFNetworkReachabilityManagerTests.m */, + 298D7C891BC2C88F00FD3B3E /* AFSecurityPolicyTests.m */, + 298D7C8F1BC2C88F00FD3B3E /* AFURLSessionManagerTests.m */, + ); + name = "AFNetworking Tests"; + sourceTree = ""; + }; + 298D7CD21BC2CAD500FD3B3E /* AFNetworking UIKit Tests */ = { + isa = PBXGroup; + children = ( + 298D7C801BC2C88F00FD3B3E /* AFAutoPurgingImageCacheTests.m */, + 298D7C841BC2C88F00FD3B3E /* AFImageDownloaderTests.m */, + 298D7C861BC2C88F00FD3B3E /* AFNetworkActivityManagerTests.m */, + 298D7C8C1BC2C88F00FD3B3E /* AFUIActivityIndicatorViewTests.m */, + 298D7C8D1BC2C88F00FD3B3E /* AFUIImageViewTests.m */, + 298D7C8E1BC2C88F00FD3B3E /* AFUIRefreshControlTests.m */, + 2960BAC21C1B2F1A00BA02F0 /* AFUIButtonTests.m */, + 29F5EF021C47E64F008B976A /* AFUIWebViewTests.m */, + ); + name = "AFNetworking UIKit Tests"; + sourceTree = ""; + }; + 2995222F1BBF104D00859F49 = { + isa = PBXGroup; + children = ( + 299522451BBF125A00859F49 /* AFNetworking */, + 299522851BBF13C700859F49 /* UIKit+AFNetworking */, + 2995223B1BBF104D00859F49 /* Supporting Files */, + 298D7C561BC2C88F00FD3B3E /* Tests */, + 2995223A1BBF104D00859F49 /* Products */, + ); + indentWidth = 4; + sourceTree = ""; + tabWidth = 4; + usesTabs = 0; + }; + 2995223A1BBF104D00859F49 /* Products */ = { + isa = PBXGroup; + children = ( + 299522391BBF104D00859F49 /* AFNetworking.framework */, + 299522651BBF129200859F49 /* AFNetworking.framework */, + 299522771BBF136400859F49 /* AFNetworking.framework */, + 298D7C3B1BC2C79500FD3B3E /* AFNetworking iOS Tests.xctest */, + 298D7C4A1BC2C7B200FD3B3E /* AFNetworking Mac OS X Tests.xctest */, + 2987B0A51BC408A200179A4C /* AFNetworking.framework */, + 2987B0AE1BC408A200179A4C /* AFNetworking tvOS Tests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 2995223B1BBF104D00859F49 /* Supporting Files */ = { + isa = PBXGroup; + children = ( + 2995223C1BBF104D00859F49 /* AFNetworking.h */, + 2995223E1BBF104D00859F49 /* Info.plist */, + ); + name = "Supporting Files"; + path = AFNetworking; + sourceTree = ""; + }; + 299522451BBF125A00859F49 /* AFNetworking */ = { + isa = PBXGroup; + children = ( + 299522461BBF125A00859F49 /* AFHTTPSessionManager.h */, + 299522471BBF125A00859F49 /* AFHTTPSessionManager.m */, + 299522491BBF125A00859F49 /* AFNetworkReachabilityManager.h */, + 2995224A1BBF125A00859F49 /* AFNetworkReachabilityManager.m */, + 2995224B1BBF125A00859F49 /* AFSecurityPolicy.h */, + 2995224C1BBF125A00859F49 /* AFSecurityPolicy.m */, + 2995224D1BBF125A00859F49 /* AFURLRequestSerialization.h */, + 2995224E1BBF125A00859F49 /* AFURLRequestSerialization.m */, + 2995224F1BBF125A00859F49 /* AFURLResponseSerialization.h */, + 299522501BBF125A00859F49 /* AFURLResponseSerialization.m */, + 299522511BBF125A00859F49 /* AFURLSessionManager.h */, + 299522521BBF125A00859F49 /* AFURLSessionManager.m */, + ); + path = AFNetworking; + sourceTree = ""; + }; + 299522851BBF13C700859F49 /* UIKit+AFNetworking */ = { + isa = PBXGroup; + children = ( + 299522861BBF13C700859F49 /* AFAutoPurgingImageCache.h */, + 299522871BBF13C700859F49 /* AFAutoPurgingImageCache.m */, + 299522881BBF13C700859F49 /* AFImageDownloader.h */, + 299522891BBF13C700859F49 /* AFImageDownloader.m */, + 2995228A1BBF13C700859F49 /* AFNetworkActivityIndicatorManager.h */, + 2995228B1BBF13C700859F49 /* AFNetworkActivityIndicatorManager.m */, + 2995228C1BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.h */, + 2995228D1BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.m */, + 299522901BBF13C700859F49 /* UIButton+AFNetworking.h */, + 299522911BBF13C700859F49 /* UIButton+AFNetworking.m */, + 299522921BBF13C700859F49 /* UIImage+AFNetworking.h */, + 299522931BBF13C700859F49 /* UIImageView+AFNetworking.h */, + 299522941BBF13C700859F49 /* UIImageView+AFNetworking.m */, + 299522951BBF13C700859F49 /* UIKit+AFNetworking.h */, + 299522961BBF13C700859F49 /* UIProgressView+AFNetworking.h */, + 299522971BBF13C700859F49 /* UIProgressView+AFNetworking.m */, + 299522981BBF13C700859F49 /* UIRefreshControl+AFNetworking.h */, + 299522991BBF13C700859F49 /* UIRefreshControl+AFNetworking.m */, + 2995229A1BBF13C700859F49 /* UIWebView+AFNetworking.h */, + 2995229B1BBF13C700859F49 /* UIWebView+AFNetworking.m */, + ); + path = "UIKit+AFNetworking"; + sourceTree = ""; + }; + 5F4323B21BF63741003B8749 /* Google.com */ = { + isa = PBXGroup; + children = ( + 5F4323D41BF63CB0003B8749 /* GoogleComServerTrustChainPath1 */, + 5F4323D81BF63CBA003B8749 /* GoogleComServerTrustChainPath2 */, + 5F4323B31BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer */, + 5F4323DC1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer */, + 5F4323B41BF63741003B8749 /* GeoTrust_Global_CA-cross.cer */, + 5F4323BA1BF63741003B8749 /* GoogleInternetAuthorityG2.cer */, + 5F4323B51BF63741003B8749 /* google.com.cer */, + ); + path = Google.com; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 2987B0A21BC408A200179A4C /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 29D96E881BCC3D7D00F571A5 /* AFHTTPSessionManager.h in Headers */, + 29D96E891BCC3D7D00F571A5 /* AFNetworkReachabilityManager.h in Headers */, + 29D96E8A1BCC3D7D00F571A5 /* AFSecurityPolicy.h in Headers */, + 29D96E8B1BCC3D7D00F571A5 /* AFURLRequestSerialization.h in Headers */, + 29D96E8C1BCC3D7D00F571A5 /* AFURLResponseSerialization.h in Headers */, + 29D96E8D1BCC3D7D00F571A5 /* AFURLSessionManager.h in Headers */, + 29D96E941BCC406B00F571A5 /* AFAutoPurgingImageCache.h in Headers */, + 29D96E951BCC406B00F571A5 /* AFImageDownloader.h in Headers */, + 29D96E961BCC406B00F571A5 /* UIActivityIndicatorView+AFNetworking.h in Headers */, + 29D96E971BCC406B00F571A5 /* UIButton+AFNetworking.h in Headers */, + 29D96E981BCC406B00F571A5 /* UIImage+AFNetworking.h in Headers */, + 29D96E991BCC406B00F571A5 /* UIImageView+AFNetworking.h in Headers */, + 29D96E9A1BCC406B00F571A5 /* UIProgressView+AFNetworking.h in Headers */, + 29D96E8E1BCC3D7D00F571A5 /* AFNetworking.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522361BBF104D00859F49 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 2995225A1BBF125A00859F49 /* AFURLRequestSerialization.h in Headers */, + 299522A81BBF13C700859F49 /* UIImage+AFNetworking.h in Headers */, + 299522531BBF125A00859F49 /* AFHTTPSessionManager.h in Headers */, + 2995229C1BBF13C700859F49 /* AFAutoPurgingImageCache.h in Headers */, + 299522581BBF125A00859F49 /* AFSecurityPolicy.h in Headers */, + 299522561BBF125A00859F49 /* AFNetworkReachabilityManager.h in Headers */, + 299522A91BBF13C700859F49 /* UIImageView+AFNetworking.h in Headers */, + 2995229E1BBF13C700859F49 /* AFImageDownloader.h in Headers */, + 2995225E1BBF125A00859F49 /* AFURLSessionManager.h in Headers */, + 2995225C1BBF125A00859F49 /* AFURLResponseSerialization.h in Headers */, + 299522A21BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.h in Headers */, + 2995223D1BBF104D00859F49 /* AFNetworking.h in Headers */, + 299522B01BBF13C700859F49 /* UIWebView+AFNetworking.h in Headers */, + 299522AC1BBF13C700859F49 /* UIProgressView+AFNetworking.h in Headers */, + 299522A61BBF13C700859F49 /* UIButton+AFNetworking.h in Headers */, + 299522A01BBF13C700859F49 /* AFNetworkActivityIndicatorManager.h in Headers */, + 299522AE1BBF13C700859F49 /* UIRefreshControl+AFNetworking.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522621BBF129200859F49 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 29D96E7A1BCC3D6000F571A5 /* AFHTTPSessionManager.h in Headers */, + 29D96E7C1BCC3D6000F571A5 /* AFSecurityPolicy.h in Headers */, + 29D96E7D1BCC3D6000F571A5 /* AFURLRequestSerialization.h in Headers */, + 29D96E7E1BCC3D6000F571A5 /* AFURLResponseSerialization.h in Headers */, + 29D96E7F1BCC3D6000F571A5 /* AFURLSessionManager.h in Headers */, + 29D96E801BCC3D6000F571A5 /* AFNetworking.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522741BBF136400859F49 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 29D96E811BCC3D7200F571A5 /* AFHTTPSessionManager.h in Headers */, + 29D96E821BCC3D7200F571A5 /* AFNetworkReachabilityManager.h in Headers */, + 29D96E831BCC3D7200F571A5 /* AFSecurityPolicy.h in Headers */, + 29D96E841BCC3D7200F571A5 /* AFURLRequestSerialization.h in Headers */, + 29D96E851BCC3D7200F571A5 /* AFURLResponseSerialization.h in Headers */, + 29D96E861BCC3D7200F571A5 /* AFURLSessionManager.h in Headers */, + 29D96E871BCC3D7200F571A5 /* AFNetworking.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 2987B0A41BC408A200179A4C /* AFNetworking tvOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = 2987B0BA1BC408A200179A4C /* Build configuration list for PBXNativeTarget "AFNetworking tvOS" */; + buildPhases = ( + 2987B0A01BC408A200179A4C /* Sources */, + 2987B0A11BC408A200179A4C /* Frameworks */, + 2987B0A21BC408A200179A4C /* Headers */, + 2987B0A31BC408A200179A4C /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "AFNetworking tvOS"; + productName = "AFNetworking tvOS"; + productReference = 2987B0A51BC408A200179A4C /* AFNetworking.framework */; + productType = "com.apple.product-type.framework"; + }; + 2987B0AD1BC408A200179A4C /* AFNetworking tvOS Tests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 2987B0BB1BC408A200179A4C /* Build configuration list for PBXNativeTarget "AFNetworking tvOS Tests" */; + buildPhases = ( + 2987B0AA1BC408A200179A4C /* Sources */, + 2987B0AB1BC408A200179A4C /* Frameworks */, + 2987B0AC1BC408A200179A4C /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 2987B0B11BC408A200179A4C /* PBXTargetDependency */, + ); + name = "AFNetworking tvOS Tests"; + productName = "AFNetworking tvOSTests"; + productReference = 2987B0AE1BC408A200179A4C /* AFNetworking tvOS Tests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 298D7C3A1BC2C79500FD3B3E /* AFNetworking iOS Tests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 298D7C451BC2C79600FD3B3E /* Build configuration list for PBXNativeTarget "AFNetworking iOS Tests" */; + buildPhases = ( + 298D7C371BC2C79500FD3B3E /* Sources */, + 298D7C381BC2C79500FD3B3E /* Frameworks */, + 298D7C391BC2C79500FD3B3E /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 298D7C421BC2C79500FD3B3E /* PBXTargetDependency */, + ); + name = "AFNetworking iOS Tests"; + productName = "AFNetworking iOS Tests"; + productReference = 298D7C3B1BC2C79500FD3B3E /* AFNetworking iOS Tests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 298D7C491BC2C7B200FD3B3E /* AFNetworking Mac OS X Tests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 298D7C521BC2C7B200FD3B3E /* Build configuration list for PBXNativeTarget "AFNetworking Mac OS X Tests" */; + buildPhases = ( + 298D7C461BC2C7B200FD3B3E /* Sources */, + 298D7C471BC2C7B200FD3B3E /* Frameworks */, + 298D7C481BC2C7B200FD3B3E /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 298D7C511BC2C7B200FD3B3E /* PBXTargetDependency */, + ); + name = "AFNetworking Mac OS X Tests"; + productName = "AFNetworking Mac OS X Tests"; + productReference = 298D7C4A1BC2C7B200FD3B3E /* AFNetworking Mac OS X Tests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 299522381BBF104D00859F49 /* AFNetworking iOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = 299522411BBF104D00859F49 /* Build configuration list for PBXNativeTarget "AFNetworking iOS" */; + buildPhases = ( + 299522341BBF104D00859F49 /* Sources */, + 299522351BBF104D00859F49 /* Frameworks */, + 299522361BBF104D00859F49 /* Headers */, + 299522371BBF104D00859F49 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "AFNetworking iOS"; + productName = AFNetworking; + productReference = 299522391BBF104D00859F49 /* AFNetworking.framework */; + productType = "com.apple.product-type.framework"; + }; + 299522641BBF129200859F49 /* AFNetworking watchOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = 2995226A1BBF129200859F49 /* Build configuration list for PBXNativeTarget "AFNetworking watchOS" */; + buildPhases = ( + 299522601BBF129200859F49 /* Sources */, + 299522611BBF129200859F49 /* Frameworks */, + 299522621BBF129200859F49 /* Headers */, + 299522631BBF129200859F49 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "AFNetworking watchOS"; + productName = "AFNetworking watchOS"; + productReference = 299522651BBF129200859F49 /* AFNetworking.framework */; + productType = "com.apple.product-type.framework"; + }; + 299522761BBF136400859F49 /* AFNetworking OS X */ = { + isa = PBXNativeTarget; + buildConfigurationList = 2995227C1BBF136400859F49 /* Build configuration list for PBXNativeTarget "AFNetworking OS X" */; + buildPhases = ( + 299522721BBF136400859F49 /* Sources */, + 299522731BBF136400859F49 /* Frameworks */, + 299522741BBF136400859F49 /* Headers */, + 299522751BBF136400859F49 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "AFNetworking OS X"; + productName = "AFNetworking OS X"; + productReference = 299522771BBF136400859F49 /* AFNetworking.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 299522301BBF104D00859F49 /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 0700; + ORGANIZATIONNAME = AFNetworking; + TargetAttributes = { + 2987B0A41BC408A200179A4C = { + CreatedOnToolsVersion = 7.1; + }; + 2987B0AD1BC408A200179A4C = { + CreatedOnToolsVersion = 7.1; + }; + 298D7C3A1BC2C79500FD3B3E = { + CreatedOnToolsVersion = 7.0.1; + }; + 298D7C491BC2C7B200FD3B3E = { + CreatedOnToolsVersion = 7.0.1; + }; + 299522381BBF104D00859F49 = { + CreatedOnToolsVersion = 7.0.1; + }; + 299522641BBF129200859F49 = { + CreatedOnToolsVersion = 7.0.1; + }; + 299522761BBF136400859F49 = { + CreatedOnToolsVersion = 7.0.1; + }; + }; + }; + buildConfigurationList = 299522331BBF104D00859F49 /* Build configuration list for PBXProject "AFNetworking" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 2995222F1BBF104D00859F49; + productRefGroup = 2995223A1BBF104D00859F49 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 299522381BBF104D00859F49 /* AFNetworking iOS */, + 299522641BBF129200859F49 /* AFNetworking watchOS */, + 299522761BBF136400859F49 /* AFNetworking OS X */, + 2987B0A41BC408A200179A4C /* AFNetworking tvOS */, + 298D7C3A1BC2C79500FD3B3E /* AFNetworking iOS Tests */, + 298D7C491BC2C7B200FD3B3E /* AFNetworking Mac OS X Tests */, + 2987B0AD1BC408A200179A4C /* AFNetworking tvOS Tests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 2987B0A31BC408A200179A4C /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2987B0AC1BC408A200179A4C /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2987B0DE1BC40AFB00179A4C /* foobar.com.cer in Resources */, + 2987B0D61BC40AEC00179A4C /* ADNNetServerTrustChain in Resources */, + 2987B0D91BC40AF300179A4C /* COMODO_RSA_Certification_Authority.cer in Resources */, + 2987B0DF1BC40AFB00179A4C /* NoDomains.cer in Resources */, + 2987B0D41BC40AE900179A4C /* adn_1.cer in Resources */, + 2987B0DD1BC40AFB00179A4C /* AltName.cer in Resources */, + 2987B0D71BC40AF000179A4C /* HTTPBinOrgServerTrustChain in Resources */, + 2987B0D31BC40AE900179A4C /* adn_0.cer in Resources */, + 2987B0DC1BC40AF600179A4C /* logo.png in Resources */, + 2987B0D81BC40AF300179A4C /* AddTrust_External_CA_Root.cer in Resources */, + 2987B0D51BC40AE900179A4C /* adn_2.cer in Resources */, + 2987B0DA1BC40AF300179A4C /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer in Resources */, + 5F4323D71BF63CB0003B8749 /* GoogleComServerTrustChainPath1 in Resources */, + 5F4323DB1BF63CBA003B8749 /* GoogleComServerTrustChainPath2 in Resources */, + 5F4323BD1BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer in Resources */, + 5F4323DF1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer in Resources */, + 1FE783031C5857A200A73B7C /* httpbinorg_01192017.cer in Resources */, + 5F4323C01BF63741003B8749 /* GeoTrust_Global_CA-cross.cer in Resources */, + 5F4323CF1BF63741003B8749 /* GoogleInternetAuthorityG2.cer in Resources */, + 5F4323C31BF63741003B8749 /* google.com.cer in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 298D7C391BC2C79500FD3B3E /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 298D7CC51BC2CAA200FD3B3E /* AddTrust_External_CA_Root.cer in Resources */, + 298D7CBF1BC2CA9D00FD3B3E /* foobar.com.cer in Resources */, + 298D7CBA1BC2CA9800FD3B3E /* logo.png in Resources */, + 298D7CC61BC2CAA200FD3B3E /* COMODO_RSA_Certification_Authority.cer in Resources */, + 297824A31BC2D69A0041C395 /* adn_0.cer in Resources */, + 298D7CC71BC2CAA200FD3B3E /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer in Resources */, + 298D7CE31BC2CB7C00FD3B3E /* HTTPBinOrgServerTrustChain in Resources */, + 297824A71BC2D69A0041C395 /* adn_2.cer in Resources */, + 297824A51BC2D69A0041C395 /* adn_1.cer in Resources */, + 298D7CC01BC2CA9D00FD3B3E /* NoDomains.cer in Resources */, + 298D7CE01BC2CB5A00FD3B3E /* ADNNetServerTrustChain in Resources */, + 298D7CBE1BC2CA9D00FD3B3E /* AltName.cer in Resources */, + 5F4323D51BF63CB0003B8749 /* GoogleComServerTrustChainPath1 in Resources */, + 5F4323D91BF63CBA003B8749 /* GoogleComServerTrustChainPath2 in Resources */, + 5F4323BB1BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer in Resources */, + 5F4323DD1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer in Resources */, + 1FE783011C5857A100A73B7C /* httpbinorg_01192017.cer in Resources */, + 5F4323BE1BF63741003B8749 /* GeoTrust_Global_CA-cross.cer in Resources */, + 5F4323CD1BF63741003B8749 /* GoogleInternetAuthorityG2.cer in Resources */, + 5F4323C11BF63741003B8749 /* google.com.cer in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 298D7C481BC2C7B200FD3B3E /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 298D7CC11BC2CAA100FD3B3E /* AddTrust_External_CA_Root.cer in Resources */, + 298D7CBC1BC2CA9C00FD3B3E /* foobar.com.cer in Resources */, + 298D7CB91BC2CA9800FD3B3E /* logo.png in Resources */, + 298D7CC21BC2CAA100FD3B3E /* COMODO_RSA_Certification_Authority.cer in Resources */, + 297824A41BC2D69A0041C395 /* adn_0.cer in Resources */, + 298D7CC31BC2CAA100FD3B3E /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer in Resources */, + 298D7CE41BC2CB7C00FD3B3E /* HTTPBinOrgServerTrustChain in Resources */, + 297824A81BC2D69A0041C395 /* adn_2.cer in Resources */, + 297824A61BC2D69A0041C395 /* adn_1.cer in Resources */, + 298D7CBD1BC2CA9C00FD3B3E /* NoDomains.cer in Resources */, + 298D7CE11BC2CB5A00FD3B3E /* ADNNetServerTrustChain in Resources */, + 298D7CBB1BC2CA9C00FD3B3E /* AltName.cer in Resources */, + 5F4323D61BF63CB0003B8749 /* GoogleComServerTrustChainPath1 in Resources */, + 5F4323DA1BF63CBA003B8749 /* GoogleComServerTrustChainPath2 in Resources */, + 5F4323BC1BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer in Resources */, + 5F4323CE1BF63741003B8749 /* GoogleInternetAuthorityG2.cer in Resources */, + 1FE783021C5857A100A73B7C /* httpbinorg_01192017.cer in Resources */, + 5F4323DE1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer in Resources */, + 5F4323BF1BF63741003B8749 /* GeoTrust_Global_CA-cross.cer in Resources */, + 5F4323C21BF63741003B8749 /* google.com.cer in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522371BBF104D00859F49 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522631BBF129200859F49 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522751BBF136400859F49 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 2987B0A01BC408A200179A4C /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2987B0BD1BC408D900179A4C /* AFNetworkReachabilityManager.m in Sources */, + 2987B0BE1BC408D900179A4C /* AFSecurityPolicy.m in Sources */, + 2987B0BC1BC408D900179A4C /* AFHTTPSessionManager.m in Sources */, + 2987B0C11BC408D900179A4C /* AFURLSessionManager.m in Sources */, + 2987B0C71BC408F900179A4C /* UIProgressView+AFNetworking.m in Sources */, + 2987B0BF1BC408D900179A4C /* AFURLRequestSerialization.m in Sources */, + 2987B0C21BC408F900179A4C /* AFAutoPurgingImageCache.m in Sources */, + 2987B0C51BC408F900179A4C /* UIButton+AFNetworking.m in Sources */, + 2987B0C41BC408F900179A4C /* UIActivityIndicatorView+AFNetworking.m in Sources */, + 2987B0C01BC408D900179A4C /* AFURLResponseSerialization.m in Sources */, + 2987B0C61BC408F900179A4C /* UIImageView+AFNetworking.m in Sources */, + 2987B0C31BC408F900179A4C /* AFImageDownloader.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2987B0AA1BC408A200179A4C /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2987B0CC1BC40A7600179A4C /* AFHTTPSessionManagerTests.m in Sources */, + 2987B0E41BC40B0900179A4C /* AFUIImageViewTests.m in Sources */, + 2987B0D11BC40A7600179A4C /* AFURLSessionManagerTests.m in Sources */, + 2987B0E31BC40B0900179A4C /* AFUIActivityIndicatorViewTests.m in Sources */, + 2987B0D01BC40A7600179A4C /* AFSecurityPolicyTests.m in Sources */, + 2987B0CB1BC40A7600179A4C /* AFHTTPResponseSerializationTests.m in Sources */, + 2987B0CE1BC40A7600179A4C /* AFNetworkReachabilityManagerTests.m in Sources */, + 2987B0E01BC40B0900179A4C /* AFAutoPurgingImageCacheTests.m in Sources */, + 2987B0CA1BC40A7600179A4C /* AFHTTPRequestSerializationTests.m in Sources */, + 29D341411C20D46400A7D266 /* AFCompoundResponseSerializerTests.m in Sources */, + 2987B0E11BC40B0900179A4C /* AFImageDownloaderTests.m in Sources */, + 2987B0CF1BC40A7600179A4C /* AFPropertyListResponseSerializerTests.m in Sources */, + 2987B0D21BC40AD800179A4C /* AFTestCase.m in Sources */, + 2987B0CD1BC40A7600179A4C /* AFJSONSerializationTests.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 298D7C371BC2C79500FD3B3E /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 29D3413F1C20D46400A7D266 /* AFCompoundResponseSerializerTests.m in Sources */, + 2960BAC31C1B2F1A00BA02F0 /* AFUIButtonTests.m in Sources */, + 298D7C961BC2C94400FD3B3E /* AFTestCase.m in Sources */, + 298D7CB11BC2CA6E00FD3B3E /* AFHTTPRequestSerializationTests.m in Sources */, + 297824AE1BC2DBD80041C395 /* AFUIActivityIndicatorViewTests.m in Sources */, + 297824AD1BC2DBA40041C395 /* AFNetworkActivityManagerTests.m in Sources */, + 298D7CDD1BC2CAF700FD3B3E /* AFSecurityPolicyTests.m in Sources */, + 298D7CD31BC2CAE800FD3B3E /* AFHTTPResponseSerializationTests.m in Sources */, + 297824B01BC2DC2D0041C395 /* AFUIImageViewTests.m in Sources */, + 297824AF1BC2DBEF0041C395 /* AFUIRefreshControlTests.m in Sources */, + 298D7CD91BC2CAF200FD3B3E /* AFNetworkReachabilityManagerTests.m in Sources */, + 297824AA1BC2DAD80041C395 /* AFAutoPurgingImageCacheTests.m in Sources */, + 298D7C981BC2CA2500FD3B3E /* AFURLSessionManagerTests.m in Sources */, + 297824AC1BC2DB450041C395 /* AFImageDownloaderTests.m in Sources */, + 29F5EF031C47E64F008B976A /* AFUIWebViewTests.m in Sources */, + 298D7CD51BC2CAEC00FD3B3E /* AFHTTPSessionManagerTests.m in Sources */, + 298D7CD71BC2CAEF00FD3B3E /* AFJSONSerializationTests.m in Sources */, + 298D7CDB1BC2CAF500FD3B3E /* AFPropertyListResponseSerializerTests.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 298D7C461BC2C7B200FD3B3E /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 298D7CD41BC2CAE900FD3B3E /* AFHTTPResponseSerializationTests.m in Sources */, + 29D341401C20D46400A7D266 /* AFCompoundResponseSerializerTests.m in Sources */, + 298D7CB21BC2CA6E00FD3B3E /* AFHTTPRequestSerializationTests.m in Sources */, + 298D7CDE1BC2CAF800FD3B3E /* AFSecurityPolicyTests.m in Sources */, + 298D7C971BC2C94500FD3B3E /* AFTestCase.m in Sources */, + 298D7CD81BC2CAF000FD3B3E /* AFJSONSerializationTests.m in Sources */, + 298D7CDC1BC2CAF500FD3B3E /* AFPropertyListResponseSerializerTests.m in Sources */, + 298D7CD61BC2CAED00FD3B3E /* AFHTTPSessionManagerTests.m in Sources */, + 298D7CDA1BC2CAF300FD3B3E /* AFNetworkReachabilityManagerTests.m in Sources */, + 298D7C991BC2CA2600FD3B3E /* AFURLSessionManagerTests.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522341BBF104D00859F49 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 299522AD1BBF13C700859F49 /* UIProgressView+AFNetworking.m in Sources */, + 299522571BBF125A00859F49 /* AFNetworkReachabilityManager.m in Sources */, + 299522AF1BBF13C700859F49 /* UIRefreshControl+AFNetworking.m in Sources */, + 299522AA1BBF13C700859F49 /* UIImageView+AFNetworking.m in Sources */, + 299522B11BBF13C700859F49 /* UIWebView+AFNetworking.m in Sources */, + 299522591BBF125A00859F49 /* AFSecurityPolicy.m in Sources */, + 299522A71BBF13C700859F49 /* UIButton+AFNetworking.m in Sources */, + 299522541BBF125A00859F49 /* AFHTTPSessionManager.m in Sources */, + 2995225F1BBF125A00859F49 /* AFURLSessionManager.m in Sources */, + 2995225B1BBF125A00859F49 /* AFURLRequestSerialization.m in Sources */, + 2995229D1BBF13C700859F49 /* AFAutoPurgingImageCache.m in Sources */, + 299522A31BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.m in Sources */, + 2995225D1BBF125A00859F49 /* AFURLResponseSerialization.m in Sources */, + 2995229F1BBF13C700859F49 /* AFImageDownloader.m in Sources */, + 299522A11BBF13C700859F49 /* AFNetworkActivityIndicatorManager.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522601BBF129200859F49 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 299522711BBF133400859F49 /* AFURLSessionManager.m in Sources */, + 2995226F1BBF133400859F49 /* AFURLRequestSerialization.m in Sources */, + 2995226E1BBF133400859F49 /* AFSecurityPolicy.m in Sources */, + 299522701BBF133400859F49 /* AFURLResponseSerialization.m in Sources */, + 2995226D1BBF133400859F49 /* AFHTTPSessionManager.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522721BBF136400859F49 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 299522801BBF13A100859F49 /* AFNetworkReachabilityManager.m in Sources */, + 299522811BBF13A100859F49 /* AFSecurityPolicy.m in Sources */, + 2995227F1BBF13A100859F49 /* AFHTTPSessionManager.m in Sources */, + 299522841BBF13A100859F49 /* AFURLSessionManager.m in Sources */, + 299522821BBF13A100859F49 /* AFURLRequestSerialization.m in Sources */, + 299522831BBF13A100859F49 /* AFURLResponseSerialization.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 2987B0B11BC408A200179A4C /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 2987B0A41BC408A200179A4C /* AFNetworking tvOS */; + targetProxy = 2987B0B01BC408A200179A4C /* PBXContainerItemProxy */; + }; + 298D7C421BC2C79500FD3B3E /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 299522381BBF104D00859F49 /* AFNetworking iOS */; + targetProxy = 298D7C411BC2C79500FD3B3E /* PBXContainerItemProxy */; + }; + 298D7C511BC2C7B200FD3B3E /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 299522761BBF136400859F49 /* AFNetworking OS X */; + targetProxy = 298D7C501BC2C7B200FD3B3E /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 2987B0B61BC408A200179A4C /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BITCODE_GENERATION_MODE = marker; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = ./Framework/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.alamofire.AFNetworking; + PRODUCT_NAME = AFNetworking; + SDKROOT = appletvos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = 3; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Debug; + }; + 2987B0B71BC408A200179A4C /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BITCODE_GENERATION_MODE = bitcode; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = ./Framework/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.alamofire.AFNetworking; + PRODUCT_NAME = AFNetworking; + SDKROOT = appletvos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = 3; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Release; + }; + 2987B0B81BC408A200179A4C /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + INFOPLIST_FILE = ./Tests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.alamofire.AFNetworking-tvOSTests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = appletvos; + TVOS_DEPLOYMENT_TARGET = 9.0; + }; + name = Debug; + }; + 2987B0B91BC408A200179A4C /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + INFOPLIST_FILE = ./Tests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.alamofire.AFNetworking-tvOSTests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = appletvos; + TVOS_DEPLOYMENT_TARGET = 9.0; + }; + name = Release; + }; + 298D7C431BC2C79500FD3B3E /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_IDENTITY = "iPhone Developer"; + GCC_PREFIX_HEADER = "$(PROJECT_DIR)/Tests/Tests-Prefix.pch"; + INFOPLIST_FILE = ./Tests/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.alamofire.AFNetworking-iOS-Tests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 298D7C441BC2C79500FD3B3E /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_IDENTITY = "iPhone Developer"; + GCC_PREFIX_HEADER = "$(PROJECT_DIR)/Tests/Tests-Prefix.pch"; + INFOPLIST_FILE = ./Tests/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.alamofire.AFNetworking-iOS-Tests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; + 298D7C531BC2C7B200FD3B3E /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + COMBINE_HIDPI_IMAGES = YES; + GCC_PREFIX_HEADER = "$(PROJECT_DIR)/Tests/Tests-Prefix.pch"; + INFOPLIST_FILE = ./Tests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 10.9; + PRODUCT_BUNDLE_IDENTIFIER = "com.alamofire.AFNetworking-Mac-OS-X-Tests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = macosx; + }; + name = Debug; + }; + 298D7C541BC2C7B200FD3B3E /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + COMBINE_HIDPI_IMAGES = YES; + GCC_PREFIX_HEADER = "$(PROJECT_DIR)/Tests/Tests-Prefix.pch"; + INFOPLIST_FILE = ./Tests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 10.9; + PRODUCT_BUNDLE_IDENTIFIER = "com.alamofire.AFNetworking-Mac-OS-X-Tests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = macosx; + }; + name = Release; + }; + 2995223F1BBF104D00859F49 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MACOSX_DEPLOYMENT_TARGET = 10.9; + MODULEMAP_FILE = "$(PROJECT_DIR)/Framework/module.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + TVOS_DEPLOYMENT_TARGET = 9.0; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Debug; + }; + 299522401BBF104D00859F49 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MACOSX_DEPLOYMENT_TARGET = 10.9; + MODULEMAP_FILE = "$(PROJECT_DIR)/Framework/module.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + TVOS_DEPLOYMENT_TARGET = 9.0; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Release; + }; + 299522421BBF104D00859F49 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BITCODE_GENERATION_MODE = marker; + CODE_SIGN_IDENTITY = "iPhone Developer"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_WARN_SHADOW = YES; + INFOPLIST_FILE = ./Framework/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.alamofire.AFNetworking; + PRODUCT_NAME = AFNetworking; + SKIP_INSTALL = YES; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Debug; + }; + 299522431BBF104D00859F49 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BITCODE_GENERATION_MODE = bitcode; + CODE_SIGN_IDENTITY = "iPhone Developer"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_WARN_SHADOW = YES; + INFOPLIST_FILE = ./Framework/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.alamofire.AFNetworking; + PRODUCT_NAME = AFNetworking; + SKIP_INSTALL = YES; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Release; + }; + 2995226B1BBF129200859F49 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BITCODE_GENERATION_MODE = marker; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = ./Framework/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.alamofire.AFNetworking-watchOS"; + PRODUCT_NAME = AFNetworking; + SDKROOT = watchos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = 4; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Debug; + }; + 2995226C1BBF129200859F49 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BITCODE_GENERATION_MODE = bitcode; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = ./Framework/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.alamofire.AFNetworking-watchOS"; + PRODUCT_NAME = AFNetworking; + SDKROOT = watchos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = 4; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Release; + }; + 2995227D1BBF136400859F49 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BITCODE_GENERATION_MODE = marker; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + COMBINE_HIDPI_IMAGES = YES; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + FRAMEWORK_VERSION = A; + INFOPLIST_FILE = ./Framework/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 10.9; + PRODUCT_BUNDLE_IDENTIFIER = com.alamofire.AFNetworking; + PRODUCT_NAME = AFNetworking; + SDKROOT = macosx; + SKIP_INSTALL = YES; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Debug; + }; + 2995227E1BBF136400859F49 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BITCODE_GENERATION_MODE = bitcode; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + COMBINE_HIDPI_IMAGES = YES; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + FRAMEWORK_VERSION = A; + INFOPLIST_FILE = ./Framework/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 10.9; + PRODUCT_BUNDLE_IDENTIFIER = com.alamofire.AFNetworking; + PRODUCT_NAME = AFNetworking; + SDKROOT = macosx; + SKIP_INSTALL = YES; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 2987B0BA1BC408A200179A4C /* Build configuration list for PBXNativeTarget "AFNetworking tvOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2987B0B61BC408A200179A4C /* Debug */, + 2987B0B71BC408A200179A4C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2987B0BB1BC408A200179A4C /* Build configuration list for PBXNativeTarget "AFNetworking tvOS Tests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2987B0B81BC408A200179A4C /* Debug */, + 2987B0B91BC408A200179A4C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 298D7C451BC2C79600FD3B3E /* Build configuration list for PBXNativeTarget "AFNetworking iOS Tests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 298D7C431BC2C79500FD3B3E /* Debug */, + 298D7C441BC2C79500FD3B3E /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 298D7C521BC2C7B200FD3B3E /* Build configuration list for PBXNativeTarget "AFNetworking Mac OS X Tests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 298D7C531BC2C7B200FD3B3E /* Debug */, + 298D7C541BC2C7B200FD3B3E /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 299522331BBF104D00859F49 /* Build configuration list for PBXProject "AFNetworking" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2995223F1BBF104D00859F49 /* Debug */, + 299522401BBF104D00859F49 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 299522411BBF104D00859F49 /* Build configuration list for PBXNativeTarget "AFNetworking iOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 299522421BBF104D00859F49 /* Debug */, + 299522431BBF104D00859F49 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2995226A1BBF129200859F49 /* Build configuration list for PBXNativeTarget "AFNetworking watchOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2995226B1BBF129200859F49 /* Debug */, + 2995226C1BBF129200859F49 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2995227C1BBF136400859F49 /* Build configuration list for PBXNativeTarget "AFNetworking OS X" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2995227D1BBF136400859F49 /* Debug */, + 2995227E1BBF136400859F49 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 299522301BBF104D00859F49 /* Project object */; +} diff --git a/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking OS X.xcscheme b/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking OS X.xcscheme new file mode 100644 index 00000000..04cfe1e6 --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking OS X.xcscheme @@ -0,0 +1,105 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking iOS.xcscheme b/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking iOS.xcscheme new file mode 100644 index 00000000..e4eb272f --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking iOS.xcscheme @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking tvOS.xcscheme b/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking tvOS.xcscheme new file mode 100644 index 00000000..23072b32 --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking tvOS.xcscheme @@ -0,0 +1,104 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking watchOS.xcscheme b/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking watchOS.xcscheme new file mode 100644 index 00000000..7f3f3ef6 --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking watchOS.xcscheme @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFHTTPSessionManager.h b/its/plugin/projects/AFNetworking/AFNetworking/AFHTTPSessionManager.h new file mode 100644 index 00000000..61e1042c --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFHTTPSessionManager.h @@ -0,0 +1,295 @@ +// AFHTTPSessionManager.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import +#if !TARGET_OS_WATCH +#import +#endif +#import + +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV +#import +#else +#import +#endif + +#import "AFURLSessionManager.h" + +/** + `AFHTTPSessionManager` is a subclass of `AFURLSessionManager` with convenience methods for making HTTP requests. When a `baseURL` is provided, requests made with the `GET` / `POST` / et al. convenience methods can be made with relative paths. + + ## Subclassing Notes + + Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application. + + For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect. + + ## Methods to Override + + To change the behavior of all data task operation construction, which is also used in the `GET` / `POST` / et al. convenience methods, override `dataTaskWithRequest:completionHandler:`. + + ## Serialization + + Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to ``. + + Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `` + + ## URL Construction Using Relative Paths + + For HTTP convenience methods, the request serializer constructs URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`, when provided. If `baseURL` is `nil`, `path` needs to resolve to a valid `NSURL` object using `NSURL +URLWithString:`. + + Below are a few examples of how `baseURL` and relative paths interact: + + NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"]; + [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo + [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz + [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo + [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo + [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/ + [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/ + + Also important to note is that a trailing slash will be added to any `baseURL` without one. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash. + + @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance. + */ + +NS_ASSUME_NONNULL_BEGIN + +@interface AFHTTPSessionManager : AFURLSessionManager + +/** + The URL used to construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods. + */ +@property (readonly, nonatomic, strong, nullable) NSURL *baseURL; + +/** + Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `AFHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies. + + @warning `requestSerializer` must not be `nil`. + */ +@property (nonatomic, strong) AFHTTPRequestSerializer * requestSerializer; + +/** + Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`. + + @warning `responseSerializer` must not be `nil`. + */ +@property (nonatomic, strong) AFHTTPResponseSerializer * responseSerializer; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Creates and returns an `AFHTTPSessionManager` object. + */ ++ (instancetype)manager; + +/** + Initializes an `AFHTTPSessionManager` object with the specified base URL. + + @param url The base URL for the HTTP client. + + @return The newly-initialized HTTP client + */ +- (instancetype)initWithBaseURL:(nullable NSURL *)url; + +/** + Initializes an `AFHTTPSessionManager` object with the specified base URL. + + This is the designated initializer. + + @param url The base URL for the HTTP client. + @param configuration The configuration used to create the managed session. + + @return The newly-initialized HTTP client + */ +- (instancetype)initWithBaseURL:(nullable NSURL *)url + sessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; + +///--------------------------- +/// @name Making HTTP Requests +///--------------------------- + +/** + Creates and runs an `NSURLSessionDataTask` with a `GET` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; + + +/** + Creates and runs an `NSURLSessionDataTask` with a `GET` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param progress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: + */ +- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(nullable id)parameters + progress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `HEAD` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes a single arguments: the data task. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)HEAD:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; + +/** + Creates and runs an `NSURLSessionDataTask` with a `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param progress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: + */ +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + progress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + constructingBodyWithBlock:(nullable void (^)(id formData))block + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; + +/** + Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. + @param progress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: + */ +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + constructingBodyWithBlock:(nullable void (^)(id formData))block + progress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `PUT` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)PUT:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `PATCH` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)PATCH:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `DELETE` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)DELETE:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +@end + +NS_ASSUME_NONNULL_END diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFHTTPSessionManager.m b/its/plugin/projects/AFNetworking/AFNetworking/AFHTTPSessionManager.m new file mode 100644 index 00000000..249631bc --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFHTTPSessionManager.m @@ -0,0 +1,361 @@ +// AFHTTPSessionManager.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "AFHTTPSessionManager.h" + +#import "AFURLRequestSerialization.h" +#import "AFURLResponseSerialization.h" + +#import +#import +#import + +#import +#import +#import +#import +#import + +#if TARGET_OS_IOS || TARGET_OS_TV +#import +#elif TARGET_OS_WATCH +#import +#endif + +@interface AFHTTPSessionManager () +@property (readwrite, nonatomic, strong) NSURL *baseURL; +@end + +@implementation AFHTTPSessionManager +@dynamic responseSerializer; + ++ (instancetype)manager { + return [[[self class] alloc] initWithBaseURL:nil]; +} + +- (instancetype)init { + return [self initWithBaseURL:nil]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url { + return [self initWithBaseURL:url sessionConfiguration:nil]; +} + +- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration { + return [self initWithBaseURL:nil sessionConfiguration:configuration]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url + sessionConfiguration:(NSURLSessionConfiguration *)configuration +{ + self = [super initWithSessionConfiguration:configuration]; + if (!self) { + return nil; + } + + // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected + if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) { + url = [url URLByAppendingPathComponent:@""]; + } + + self.baseURL = url; + + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + self.responseSerializer = [AFJSONResponseSerializer serializer]; + + return self; +} + +#pragma mark - + +- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { + NSParameterAssert(requestSerializer); + + _requestSerializer = requestSerializer; +} + +- (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { + NSParameterAssert(responseSerializer); + + [super setResponseSerializer:responseSerializer]; +} + +#pragma mark - + +- (NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + + return [self GET:URLString parameters:parameters progress:nil success:success failure:failure]; +} + +- (NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(id)parameters + progress:(void (^)(NSProgress * _Nonnull))downloadProgress + success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success + failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure +{ + + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET" + URLString:URLString + parameters:parameters + uploadProgress:nil + downloadProgress:downloadProgress + success:success + failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)HEAD:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, __unused id responseObject) { + if (success) { + success(task); + } + } failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + return [self POST:URLString parameters:parameters progress:nil success:success failure:failure]; +} + +- (NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(id)parameters + progress:(void (^)(NSProgress * _Nonnull))uploadProgress + success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success + failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters uploadProgress:uploadProgress downloadProgress:nil success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + constructingBodyWithBlock:(nullable void (^)(id _Nonnull))block + success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure +{ + return [self POST:URLString parameters:parameters constructingBodyWithBlock:block progress:nil success:success failure:failure]; +} + +- (NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(id)parameters + constructingBodyWithBlock:(void (^)(id formData))block + progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSError *serializationError = nil; + NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError]; + if (serializationError) { + if (failure) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ + failure(nil, serializationError); + }); +#pragma clang diagnostic pop + } + + return nil; + } + + __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { + if (error) { + if (failure) { + failure(task, error); + } + } else { + if (success) { + success(task, responseObject); + } + } + }]; + + [task resume]; + + return task; +} + +- (NSURLSessionDataTask *)PUT:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)PATCH:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)DELETE:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(id)parameters + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress + success:(void (^)(NSURLSessionDataTask *, id))success + failure:(void (^)(NSURLSessionDataTask *, NSError *))failure +{ + NSError *serializationError = nil; + NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError]; + if (serializationError) { + if (failure) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ + failure(nil, serializationError); + }); +#pragma clang diagnostic pop + } + + return nil; + } + + __block NSURLSessionDataTask *dataTask = nil; + dataTask = [self dataTaskWithRequest:request + uploadProgress:uploadProgress + downloadProgress:downloadProgress + completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { + if (error) { + if (failure) { + failure(dataTask, error); + } + } else { + if (success) { + success(dataTask, responseObject); + } + } + }]; + + return dataTask; +} + +#pragma mark - NSObject + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue]; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))]; + NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; + if (!configuration) { + NSString *configurationIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:@"identifier"]; + if (configurationIdentifier) { +#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1100) + configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier]; +#else + configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:configurationIdentifier]; +#endif + } + } + + self = [self initWithBaseURL:baseURL sessionConfiguration:configuration]; + if (!self) { + return nil; + } + + self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))]; + self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; + AFSecurityPolicy *decodedPolicy = [decoder decodeObjectOfClass:[AFSecurityPolicy class] forKey:NSStringFromSelector(@selector(securityPolicy))]; + if (decodedPolicy) { + self.securityPolicy = decodedPolicy; + } + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))]; + if ([self.session.configuration conformsToProtocol:@protocol(NSCoding)]) { + [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"]; + } else { + [coder encodeObject:self.session.configuration.identifier forKey:@"identifier"]; + } + [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))]; + [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; + [coder encodeObject:self.securityPolicy forKey:NSStringFromSelector(@selector(securityPolicy))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration]; + + HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone]; + HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone]; + HTTPClient.securityPolicy = [self.securityPolicy copyWithZone:zone]; + return HTTPClient; +} + +@end diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h b/its/plugin/projects/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h new file mode 100644 index 00000000..88d9181f --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h @@ -0,0 +1,206 @@ +// AFNetworkReachabilityManager.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import + +#if !TARGET_OS_WATCH +#import + +typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { + AFNetworkReachabilityStatusUnknown = -1, + AFNetworkReachabilityStatusNotReachable = 0, + AFNetworkReachabilityStatusReachableViaWWAN = 1, + AFNetworkReachabilityStatusReachableViaWiFi = 2, +}; + +NS_ASSUME_NONNULL_BEGIN + +/** + `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. + + Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability. + + See Apple's Reachability Sample Code (https://developer.apple.com/library/ios/samplecode/reachability/) + + @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined. + */ +@interface AFNetworkReachabilityManager : NSObject + +/** + The current network reachability status. + */ +@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; + +/** + Whether or not the network is currently reachable. + */ +@property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable; + +/** + Whether or not the network is currently reachable via WWAN. + */ +@property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN; + +/** + Whether or not the network is currently reachable via WiFi. + */ +@property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Returns the shared network reachability manager. + */ ++ (instancetype)sharedManager; + +/** + Creates and returns a network reachability manager with the default socket address. + + @return An initialized network reachability manager, actively monitoring the default socket address. + */ ++ (instancetype)manager; + +/** + Creates and returns a network reachability manager for the specified domain. + + @param domain The domain used to evaluate network reachability. + + @return An initialized network reachability manager, actively monitoring the specified domain. + */ ++ (instancetype)managerForDomain:(NSString *)domain; + +/** + Creates and returns a network reachability manager for the socket address. + + @param address The socket address (`sockaddr_in6`) used to evaluate network reachability. + + @return An initialized network reachability manager, actively monitoring the specified socket address. + */ ++ (instancetype)managerForAddress:(const void *)address; + +/** + Initializes an instance of a network reachability manager from the specified reachability object. + + @param reachability The reachability object to monitor. + + @return An initialized network reachability manager, actively monitoring the specified reachability. + */ +- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER; + +///-------------------------------------------------- +/// @name Starting & Stopping Reachability Monitoring +///-------------------------------------------------- + +/** + Starts monitoring for changes in network reachability status. + */ +- (void)startMonitoring; + +/** + Stops monitoring for changes in network reachability status. + */ +- (void)stopMonitoring; + +///------------------------------------------------- +/// @name Getting Localized Reachability Description +///------------------------------------------------- + +/** + Returns a localized string representation of the current network reachability status. + */ +- (NSString *)localizedNetworkReachabilityStatusString; + +///--------------------------------------------------- +/// @name Setting Network Reachability Change Callback +///--------------------------------------------------- + +/** + Sets a callback to be executed when the network availability of the `baseURL` host changes. + + @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`. + */ +- (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block; + +@end + +///---------------- +/// @name Constants +///---------------- + +/** + ## Network Reachability + + The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses. + + enum { + AFNetworkReachabilityStatusUnknown, + AFNetworkReachabilityStatusNotReachable, + AFNetworkReachabilityStatusReachableViaWWAN, + AFNetworkReachabilityStatusReachableViaWiFi, + } + + `AFNetworkReachabilityStatusUnknown` + The `baseURL` host reachability is not known. + + `AFNetworkReachabilityStatusNotReachable` + The `baseURL` host cannot be reached. + + `AFNetworkReachabilityStatusReachableViaWWAN` + The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS. + + `AFNetworkReachabilityStatusReachableViaWiFi` + The `baseURL` host can be reached via a Wi-Fi connection. + + ### Keys for Notification UserInfo Dictionary + + Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification. + + `AFNetworkingReachabilityNotificationStatusItem` + A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification. + The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status. + */ + +///-------------------- +/// @name Notifications +///-------------------- + +/** + Posted when network reachability changes. + This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability. + + @warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import ` to the header prefix of the project (`Prefix.pch`). + */ +FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification; +FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem; + +///-------------------- +/// @name Functions +///-------------------- + +/** + Returns a localized string representation of an `AFNetworkReachabilityStatus` value. + */ +FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status); + +NS_ASSUME_NONNULL_END +#endif diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m b/its/plugin/projects/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m new file mode 100644 index 00000000..d39b81bc --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m @@ -0,0 +1,263 @@ +// AFNetworkReachabilityManager.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "AFNetworkReachabilityManager.h" +#if !TARGET_OS_WATCH + +#import +#import +#import +#import +#import + +NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change"; +NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem"; + +typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status); + +NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) { + switch (status) { + case AFNetworkReachabilityStatusNotReachable: + return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil); + case AFNetworkReachabilityStatusReachableViaWWAN: + return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil); + case AFNetworkReachabilityStatusReachableViaWiFi: + return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil); + case AFNetworkReachabilityStatusUnknown: + default: + return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil); + } +} + +static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) { + BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0); + BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0); + BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0)); + BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0); + BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction)); + + AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown; + if (isNetworkReachable == NO) { + status = AFNetworkReachabilityStatusNotReachable; + } +#if TARGET_OS_IPHONE + else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) { + status = AFNetworkReachabilityStatusReachableViaWWAN; + } +#endif + else { + status = AFNetworkReachabilityStatusReachableViaWiFi; + } + + return status; +} + +/** + * Queue a status change notification for the main thread. + * + * This is done to ensure that the notifications are received in the same order + * as they are sent. If notifications are sent directly, it is possible that + * a queued notification (for an earlier status condition) is processed after + * the later update, resulting in the listener being left in the wrong state. + */ +static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFNetworkReachabilityStatusBlock block) { + AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); + dispatch_async(dispatch_get_main_queue(), ^{ + if (block) { + block(status); + } + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) }; + [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo]; + }); +} + +static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) { + AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusBlock)info); +} + + +static const void * AFNetworkReachabilityRetainCallback(const void *info) { + return Block_copy(info); +} + +static void AFNetworkReachabilityReleaseCallback(const void *info) { + if (info) { + Block_release(info); + } +} + +@interface AFNetworkReachabilityManager () +@property (readonly, nonatomic, assign) SCNetworkReachabilityRef networkReachability; +@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; +@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock; +@end + +@implementation AFNetworkReachabilityManager + ++ (instancetype)sharedManager { + static AFNetworkReachabilityManager *_sharedManager = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _sharedManager = [self manager]; + }); + + return _sharedManager; +} + ++ (instancetype)managerForDomain:(NSString *)domain { + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]); + + AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; + + CFRelease(reachability); + + return manager; +} + ++ (instancetype)managerForAddress:(const void *)address { + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address); + AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; + + CFRelease(reachability); + + return manager; +} + ++ (instancetype)manager +{ +#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 90000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + struct sockaddr_in6 address; + bzero(&address, sizeof(address)); + address.sin6_len = sizeof(address); + address.sin6_family = AF_INET6; +#else + struct sockaddr_in address; + bzero(&address, sizeof(address)); + address.sin_len = sizeof(address); + address.sin_family = AF_INET; +#endif + return [self managerForAddress:&address]; +} + +- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability { + self = [super init]; + if (!self) { + return nil; + } + + _networkReachability = CFRetain(reachability); + self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown; + + return self; +} + +- (instancetype)init NS_UNAVAILABLE +{ + return nil; +} + +- (void)dealloc { + [self stopMonitoring]; + + if (_networkReachability != NULL) { + CFRelease(_networkReachability); + } +} + +#pragma mark - + +- (BOOL)isReachable { + return [self isReachableViaWWAN] || [self isReachableViaWiFi]; +} + +- (BOOL)isReachableViaWWAN { + return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN; +} + +- (BOOL)isReachableViaWiFi { + return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi; +} + +#pragma mark - + +- (void)startMonitoring { + [self stopMonitoring]; + + if (!self.networkReachability) { + return; + } + + __weak __typeof(self)weakSelf = self; + AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + + strongSelf.networkReachabilityStatus = status; + if (strongSelf.networkReachabilityStatusBlock) { + strongSelf.networkReachabilityStatusBlock(status); + } + + }; + + SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL}; + SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context); + SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); + + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{ + SCNetworkReachabilityFlags flags; + if (SCNetworkReachabilityGetFlags(self.networkReachability, &flags)) { + AFPostReachabilityStatusChange(flags, callback); + } + }); +} + +- (void)stopMonitoring { + if (!self.networkReachability) { + return; + } + + SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); +} + +#pragma mark - + +- (NSString *)localizedNetworkReachabilityStatusString { + return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus); +} + +#pragma mark - + +- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block { + self.networkReachabilityStatusBlock = block; +} + +#pragma mark - NSKeyValueObserving + ++ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key { + if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) { + return [NSSet setWithObject:@"networkReachabilityStatus"]; + } + + return [super keyPathsForValuesAffectingValueForKey:key]; +} + +@end +#endif diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFNetworking.h b/its/plugin/projects/AFNetworking/AFNetworking/AFNetworking.h new file mode 100644 index 00000000..e2fb2f44 --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFNetworking.h @@ -0,0 +1,41 @@ +// AFNetworking.h +// +// Copyright (c) 2013 AFNetworking (http://afnetworking.com/) +// +// 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. + +#import +#import +#import + +#ifndef _AFNETWORKING_ + #define _AFNETWORKING_ + + #import "AFURLRequestSerialization.h" + #import "AFURLResponseSerialization.h" + #import "AFSecurityPolicy.h" + +#if !TARGET_OS_WATCH + #import "AFNetworkReachabilityManager.h" +#endif + + #import "AFURLSessionManager.h" + #import "AFHTTPSessionManager.h" + +#endif /* _AFNETWORKING_ */ diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFSecurityPolicy.h b/its/plugin/projects/AFNetworking/AFNetworking/AFSecurityPolicy.h new file mode 100644 index 00000000..de3ce924 --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFSecurityPolicy.h @@ -0,0 +1,154 @@ +// AFSecurityPolicy.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import +#import + +typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { + AFSSLPinningModeNone, + AFSSLPinningModePublicKey, + AFSSLPinningModeCertificate, +}; + +/** + `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. + + Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled. + */ + +NS_ASSUME_NONNULL_BEGIN + +@interface AFSecurityPolicy : NSObject + +/** + The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`. + */ +@property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode; + +/** + The certificates used to evaluate server trust according to the SSL pinning mode. + + By default, this property is set to any (`.cer`) certificates included in the target compiling AFNetworking. Note that if you are using AFNetworking as embedded framework, no certificates will be pinned by default. Use `certificatesInBundle` to load certificates from your target, and then create a new policy by calling `policyWithPinningMode:withPinnedCertificates`. + + Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches. + */ +@property (nonatomic, strong, nullable) NSSet *pinnedCertificates; + +/** + Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`. + */ +@property (nonatomic, assign) BOOL allowInvalidCertificates; + +/** + Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`. + */ +@property (nonatomic, assign) BOOL validatesDomainName; + +///----------------------------------------- +/// @name Getting Certificates from the Bundle +///----------------------------------------- + +/** + Returns any certificates included in the bundle. If you are using AFNetworking as an embedded framework, you must use this method to find the certificates you have included in your app bundle, and use them when creating your security policy by calling `policyWithPinningMode:withPinnedCertificates`. + + @return The certificates included in the given bundle. + */ ++ (NSSet *)certificatesInBundle:(NSBundle *)bundle; + +///----------------------------------------- +/// @name Getting Specific Security Policies +///----------------------------------------- + +/** + Returns the shared default security policy, which does not allow invalid certificates, validates domain name, and does not validate against pinned certificates or public keys. + + @return The default security policy. + */ ++ (instancetype)defaultPolicy; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Creates and returns a security policy with the specified pinning mode. + + @param pinningMode The SSL pinning mode. + + @return A new security policy. + */ ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode; + +/** + Creates and returns a security policy with the specified pinning mode. + + @param pinningMode The SSL pinning mode. + @param pinnedCertificates The certificates to pin against. + + @return A new security policy. + */ ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates; + +///------------------------------ +/// @name Evaluating Server Trust +///------------------------------ + +/** + Whether or not the specified server trust should be accepted, based on the security policy. + + This method should be used when responding to an authentication challenge from a server. + + @param serverTrust The X.509 certificate trust of the server. + @param domain The domain of serverTrust. If `nil`, the domain will not be validated. + + @return Whether or not to trust the server. + */ +- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust + forDomain:(nullable NSString *)domain; + +@end + +NS_ASSUME_NONNULL_END + +///---------------- +/// @name Constants +///---------------- + +/** + ## SSL Pinning Modes + + The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes. + + enum { + AFSSLPinningModeNone, + AFSSLPinningModePublicKey, + AFSSLPinningModeCertificate, + } + + `AFSSLPinningModeNone` + Do not used pinned certificates to validate servers. + + `AFSSLPinningModePublicKey` + Validate host certificates against public keys of pinned certificates. + + `AFSSLPinningModeCertificate` + Validate host certificates against pinned certificates. +*/ diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFSecurityPolicy.m b/its/plugin/projects/AFNetworking/AFNetworking/AFSecurityPolicy.m new file mode 100644 index 00000000..2ec602bd --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFSecurityPolicy.m @@ -0,0 +1,353 @@ +// AFSecurityPolicy.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "AFSecurityPolicy.h" + +#import + +#if !TARGET_OS_IOS && !TARGET_OS_WATCH && !TARGET_OS_TV +static NSData * AFSecKeyGetData(SecKeyRef key) { + CFDataRef data = NULL; + + __Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out); + + return (__bridge_transfer NSData *)data; + +_out: + if (data) { + CFRelease(data); + } + + return nil; +} +#endif + +static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) { +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV + return [(__bridge id)key1 isEqual:(__bridge id)key2]; +#else + return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)]; +#endif +} + +static id AFPublicKeyForCertificate(NSData *certificate) { + id allowedPublicKey = nil; + SecCertificateRef allowedCertificate; + SecCertificateRef allowedCertificates[1]; + CFArrayRef tempCertificates = nil; + SecPolicyRef policy = nil; + SecTrustRef allowedTrust = nil; + SecTrustResultType result; + + allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate); + __Require_Quiet(allowedCertificate != NULL, _out); + + allowedCertificates[0] = allowedCertificate; + tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL); + + policy = SecPolicyCreateBasicX509(); + __Require_noErr_Quiet(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out); + __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out); + + allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust); + +_out: + if (allowedTrust) { + CFRelease(allowedTrust); + } + + if (policy) { + CFRelease(policy); + } + + if (tempCertificates) { + CFRelease(tempCertificates); + } + + if (allowedCertificate) { + CFRelease(allowedCertificate); + } + + return allowedPublicKey; +} + +static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) { + BOOL isValid = NO; + SecTrustResultType result; + __Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out); + + isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed); + +_out: + return isValid; +} + +static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) { + CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); + NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; + + for (CFIndex i = 0; i < certificateCount; i++) { + SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); + [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]; + } + + return [NSArray arrayWithArray:trustChain]; +} + +static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) { + SecPolicyRef policy = SecPolicyCreateBasicX509(); + CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); + NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; + for (CFIndex i = 0; i < certificateCount; i++) { + SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); + + SecCertificateRef someCertificates[] = {certificate}; + CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL); + + SecTrustRef trust; + __Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out); + + SecTrustResultType result; + __Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out); + + [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)]; + + _out: + if (trust) { + CFRelease(trust); + } + + if (certificates) { + CFRelease(certificates); + } + + continue; + } + CFRelease(policy); + + return [NSArray arrayWithArray:trustChain]; +} + +#pragma mark - + +@interface AFSecurityPolicy() +@property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode; +@property (readwrite, nonatomic, strong) NSSet *pinnedPublicKeys; +@end + +@implementation AFSecurityPolicy + ++ (NSSet *)certificatesInBundle:(NSBundle *)bundle { + NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."]; + + NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]]; + for (NSString *path in paths) { + NSData *certificateData = [NSData dataWithContentsOfFile:path]; + [certificates addObject:certificateData]; + } + + return [NSSet setWithSet:certificates]; +} + ++ (NSSet *)defaultPinnedCertificates { + static NSSet *_defaultPinnedCertificates = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSBundle *bundle = [NSBundle bundleForClass:[self class]]; + _defaultPinnedCertificates = [self certificatesInBundle:bundle]; + }); + + return _defaultPinnedCertificates; +} + ++ (instancetype)defaultPolicy { + AFSecurityPolicy *securityPolicy = [[self alloc] init]; + securityPolicy.SSLPinningMode = AFSSLPinningModeNone; + + return securityPolicy; +} + ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode { + return [self policyWithPinningMode:pinningMode withPinnedCertificates:[self defaultPinnedCertificates]]; +} + ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates { + AFSecurityPolicy *securityPolicy = [[self alloc] init]; + securityPolicy.SSLPinningMode = pinningMode; + + [securityPolicy setPinnedCertificates:pinnedCertificates]; + + return securityPolicy; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.validatesDomainName = YES; + + return self; +} + +- (void)setPinnedCertificates:(NSSet *)pinnedCertificates { + _pinnedCertificates = pinnedCertificates; + + if (self.pinnedCertificates) { + NSMutableSet *mutablePinnedPublicKeys = [NSMutableSet setWithCapacity:[self.pinnedCertificates count]]; + for (NSData *certificate in self.pinnedCertificates) { + id publicKey = AFPublicKeyForCertificate(certificate); + if (!publicKey) { + continue; + } + [mutablePinnedPublicKeys addObject:publicKey]; + } + self.pinnedPublicKeys = [NSSet setWithSet:mutablePinnedPublicKeys]; + } else { + self.pinnedPublicKeys = nil; + } +} + +#pragma mark - + +- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust + forDomain:(NSString *)domain +{ + if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) { + // https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html + // According to the docs, you should only trust your provided certs for evaluation. + // Pinned certificates are added to the trust. Without pinned certificates, + // there is nothing to evaluate against. + // + // From Apple Docs: + // "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors). + // Instead, add your own (self-signed) CA certificate to the list of trusted anchors." + NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning."); + return NO; + } + + NSMutableArray *policies = [NSMutableArray array]; + if (self.validatesDomainName) { + [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)]; + } else { + [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()]; + } + + SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies); + + if (self.SSLPinningMode == AFSSLPinningModeNone) { + return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust); + } else if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) { + return NO; + } + + switch (self.SSLPinningMode) { + case AFSSLPinningModeNone: + default: + return NO; + case AFSSLPinningModeCertificate: { + NSMutableArray *pinnedCertificates = [NSMutableArray array]; + for (NSData *certificateData in self.pinnedCertificates) { + [pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)]; + } + SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates); + + if (!AFServerTrustIsValid(serverTrust)) { + return NO; + } + + // obtain the chain after being validated, which *should* contain the pinned certificate in the last position (if it's the Root CA) + NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust); + + for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) { + if ([self.pinnedCertificates containsObject:trustChainCertificate]) { + return YES; + } + } + + return NO; + } + case AFSSLPinningModePublicKey: { + NSUInteger trustedPublicKeyCount = 0; + NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust); + + for (id trustChainPublicKey in publicKeys) { + for (id pinnedPublicKey in self.pinnedPublicKeys) { + if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) { + trustedPublicKeyCount += 1; + } + } + } + return trustedPublicKeyCount > 0; + } + } + + return NO; +} + +#pragma mark - NSKeyValueObserving + ++ (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys { + return [NSSet setWithObject:@"pinnedCertificates"]; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + + self = [self init]; + if (!self) { + return nil; + } + + self.SSLPinningMode = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(SSLPinningMode))] unsignedIntegerValue]; + self.allowInvalidCertificates = [decoder decodeBoolForKey:NSStringFromSelector(@selector(allowInvalidCertificates))]; + self.validatesDomainName = [decoder decodeBoolForKey:NSStringFromSelector(@selector(validatesDomainName))]; + self.pinnedCertificates = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(pinnedCertificates))]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [coder encodeObject:[NSNumber numberWithUnsignedInteger:self.SSLPinningMode] forKey:NSStringFromSelector(@selector(SSLPinningMode))]; + [coder encodeBool:self.allowInvalidCertificates forKey:NSStringFromSelector(@selector(allowInvalidCertificates))]; + [coder encodeBool:self.validatesDomainName forKey:NSStringFromSelector(@selector(validatesDomainName))]; + [coder encodeObject:self.pinnedCertificates forKey:NSStringFromSelector(@selector(pinnedCertificates))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFSecurityPolicy *securityPolicy = [[[self class] allocWithZone:zone] init]; + securityPolicy.SSLPinningMode = self.SSLPinningMode; + securityPolicy.allowInvalidCertificates = self.allowInvalidCertificates; + securityPolicy.validatesDomainName = self.validatesDomainName; + securityPolicy.pinnedCertificates = [self.pinnedCertificates copyWithZone:zone]; + + return securityPolicy; +} + +@end diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFURLRequestSerialization.h b/its/plugin/projects/AFNetworking/AFNetworking/AFURLRequestSerialization.h new file mode 100644 index 00000000..a6f179bf --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFURLRequestSerialization.h @@ -0,0 +1,479 @@ +// AFURLRequestSerialization.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import +#import + +#if TARGET_OS_IOS || TARGET_OS_TV +#import +#elif TARGET_OS_WATCH +#import +#endif + +NS_ASSUME_NONNULL_BEGIN + +/** + Returns a percent-escaped string following RFC 3986 for a query string key or value. + RFC 3986 states that the following characters are "reserved" characters. + - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + + In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + should be percent-escaped in the query string. + + @param string The string to be percent-escaped. + + @return The percent-escaped string. + */ +FOUNDATION_EXPORT NSString * AFPercentEscapedStringFromString(NSString *string); + +/** + A helper method to generate encoded url query parameters for appending to the end of a URL. + + @param parameters A dictionary of key/values to be encoded. + + @return A url encoded query string + */ +FOUNDATION_EXPORT NSString * AFQueryStringFromParameters(NSDictionary *parameters); + +/** + The `AFURLRequestSerialization` protocol is adopted by an object that encodes parameters for a specified HTTP requests. Request serializers may encode parameters as query strings, HTTP bodies, setting the appropriate HTTP header fields as necessary. + + For example, a JSON request serializer may set the HTTP body of the request to a JSON representation, and set the `Content-Type` HTTP header field value to `application/json`. + */ +@protocol AFURLRequestSerialization + +/** + Returns a request with the specified parameters encoded into a copy of the original request. + + @param request The original request. + @param parameters The parameters to be encoded. + @param error The error that occurred while attempting to encode the request parameters. + + @return A serialized request. + */ +- (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(nullable id)parameters + error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW; + +@end + +#pragma mark - + +/** + + */ +typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) { + AFHTTPRequestQueryStringDefaultStyle = 0, +}; + +@protocol AFMultipartFormData; + +/** + `AFHTTPRequestSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation. + + Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPRequestSerializer` in order to ensure consistent default behavior. + */ +@interface AFHTTPRequestSerializer : NSObject + +/** + The string encoding used to serialize parameters. `NSUTF8StringEncoding` by default. + */ +@property (nonatomic, assign) NSStringEncoding stringEncoding; + +/** + Whether created requests can use the device’s cellular radio (if present). `YES` by default. + + @see NSMutableURLRequest -setAllowsCellularAccess: + */ +@property (nonatomic, assign) BOOL allowsCellularAccess; + +/** + The cache policy of created requests. `NSURLRequestUseProtocolCachePolicy` by default. + + @see NSMutableURLRequest -setCachePolicy: + */ +@property (nonatomic, assign) NSURLRequestCachePolicy cachePolicy; + +/** + Whether created requests should use the default cookie handling. `YES` by default. + + @see NSMutableURLRequest -setHTTPShouldHandleCookies: + */ +@property (nonatomic, assign) BOOL HTTPShouldHandleCookies; + +/** + Whether created requests can continue transmitting data before receiving a response from an earlier transmission. `NO` by default + + @see NSMutableURLRequest -setHTTPShouldUsePipelining: + */ +@property (nonatomic, assign) BOOL HTTPShouldUsePipelining; + +/** + The network service type for created requests. `NSURLNetworkServiceTypeDefault` by default. + + @see NSMutableURLRequest -setNetworkServiceType: + */ +@property (nonatomic, assign) NSURLRequestNetworkServiceType networkServiceType; + +/** + The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds. + + @see NSMutableURLRequest -setTimeoutInterval: + */ +@property (nonatomic, assign) NSTimeInterval timeoutInterval; + +///--------------------------------------- +/// @name Configuring HTTP Request Headers +///--------------------------------------- + +/** + Default HTTP header field values to be applied to serialized requests. By default, these include the following: + + - `Accept-Language` with the contents of `NSLocale +preferredLanguages` + - `User-Agent` with the contents of various bundle identifiers and OS designations + + @discussion To add or remove default request headers, use `setValue:forHTTPHeaderField:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *HTTPRequestHeaders; + +/** + Creates and returns a serializer with default configuration. + */ ++ (instancetype)serializer; + +/** + Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header. + + @param field The HTTP header to set a default value for + @param value The value set as default for the specified header, or `nil` + */ +- (void)setValue:(nullable NSString *)value +forHTTPHeaderField:(NSString *)field; + +/** + Returns the value for the HTTP headers set in the request serializer. + + @param field The HTTP header to retrieve the default value for + + @return The value set as default for the specified header, or `nil` + */ +- (nullable NSString *)valueForHTTPHeaderField:(NSString *)field; + +/** + Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header. + + @param username The HTTP basic auth username + @param password The HTTP basic auth password + */ +- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username + password:(NSString *)password; + +/** + Clears any existing value for the "Authorization" HTTP header. + */ +- (void)clearAuthorizationHeader; + +///------------------------------------------------------- +/// @name Configuring Query String Parameter Serialization +///------------------------------------------------------- + +/** + HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default. + */ +@property (nonatomic, strong) NSSet *HTTPMethodsEncodingParametersInURI; + +/** + Set the method of query string serialization according to one of the pre-defined styles. + + @param style The serialization style. + + @see AFHTTPRequestQueryStringSerializationStyle + */ +- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style; + +/** + Set the a custom method of query string serialization according to the specified block. + + @param block A block that defines a process of encoding parameters into a query string. This block returns the query string and takes three arguments: the request, the parameters to encode, and the error that occurred when attempting to encode parameters for the given request. + */ +- (void)setQueryStringSerializationWithBlock:(nullable NSString * (^)(NSURLRequest *request, id parameters, NSError * __autoreleasing *error))block; + +///------------------------------- +/// @name Creating Request Objects +///------------------------------- + +/** + Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string. + + If the HTTP method is `GET`, `HEAD`, or `DELETE`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body. + + @param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`. + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body. + @param error The error that occurred while constructing the request. + + @return An `NSMutableURLRequest` object. + */ +- (NSMutableURLRequest *)requestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(nullable id)parameters + error:(NSError * _Nullable __autoreleasing *)error; + +/** + Creates an `NSMutableURLRequest` object with the specified HTTP method and URLString, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2 + + Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting `NSMutableURLRequest` object has an `HTTPBodyStream` property, so refrain from setting `HTTPBodyStream` or `HTTPBody` on this request object, as it will clear out the multipart form body stream. + + @param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`. + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded and set in the request HTTP body. + @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. + @param error The error that occurred while constructing the request. + + @return An `NSMutableURLRequest` object + */ +- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(nullable NSDictionary *)parameters + constructingBodyWithBlock:(nullable void (^)(id formData))block + error:(NSError * _Nullable __autoreleasing *)error; + +/** + Creates an `NSMutableURLRequest` by removing the `HTTPBodyStream` from a request, and asynchronously writing its contents into the specified file, invoking the completion handler when finished. + + @param request The multipart form request. The `HTTPBodyStream` property of `request` must not be `nil`. + @param fileURL The file URL to write multipart form contents to. + @param handler A handler block to execute. + + @discussion There is a bug in `NSURLSessionTask` that causes requests to not send a `Content-Length` header when streaming contents from an HTTP body, which is notably problematic when interacting with the Amazon S3 webservice. As a workaround, this method takes a request constructed with `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:`, or any other request with an `HTTPBodyStream`, writes the contents to the specified file and returns a copy of the original request with the `HTTPBodyStream` property set to `nil`. From here, the file can either be passed to `AFURLSessionManager -uploadTaskWithRequest:fromFile:progress:completionHandler:`, or have its contents read into an `NSData` that's assigned to the `HTTPBody` property of the request. + + @see https://github.com/AFNetworking/AFNetworking/issues/1398 + */ +- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request + writingStreamContentsToFile:(NSURL *)fileURL + completionHandler:(nullable void (^)(NSError * _Nullable error))handler; + +@end + +#pragma mark - + +/** + The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`. + */ +@protocol AFMultipartFormData + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{generated filename}; name=#{name}"` and `Content-Type: #{generated mimeType}`, followed by the encoded file data and the multipart form boundary. + + The filename and MIME type for this data in the form will be automatically generated, using the last path component of the `fileURL` and system associated MIME type for the `fileURL` extension, respectively. + + @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + @param error If an error occurs, upon return contains an `NSError` object that describes the problem. + + @return `YES` if the file data was successfully appended, otherwise `NO`. + */ +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + error:(NSError * _Nullable __autoreleasing *)error; + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary. + + @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + @param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`. + @param mimeType The declared MIME type of the file data. This parameter must not be `nil`. + @param error If an error occurs, upon return contains an `NSError` object that describes the problem. + + @return `YES` if the file data was successfully appended otherwise `NO`. + */ +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType + error:(NSError * _Nullable __autoreleasing *)error; + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary. + + @param inputStream The input stream to be appended to the form data + @param name The name to be associated with the specified input stream. This parameter must not be `nil`. + @param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`. + @param length The length of the specified input stream in bytes. + @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`. + */ +- (void)appendPartWithInputStream:(nullable NSInputStream *)inputStream + name:(NSString *)name + fileName:(NSString *)fileName + length:(int64_t)length + mimeType:(NSString *)mimeType; + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary. + + @param data The data to be encoded and appended to the form data. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + @param fileName The filename to be associated with the specified data. This parameter must not be `nil`. + @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`. + */ +- (void)appendPartWithFileData:(NSData *)data + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType; + +/** + Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary. + + @param data The data to be encoded and appended to the form data. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + */ + +- (void)appendPartWithFormData:(NSData *)data + name:(NSString *)name; + + +/** + Appends HTTP headers, followed by the encoded data and the multipart form boundary. + + @param headers The HTTP headers to be appended to the form data. + @param body The data to be encoded and appended to the form data. This parameter must not be `nil`. + */ +- (void)appendPartWithHeaders:(nullable NSDictionary *)headers + body:(NSData *)body; + +/** + Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream. + + When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFUploadStream3GSuggestedPacketSize` and `kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, there is no definite way to distinguish between a 3G, EDGE, or LTE connection over `NSURLConnection`. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth. + + @param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 16kb. + @param delay Duration of delay each time a packet is read. By default, no delay is set. + */ +- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes + delay:(NSTimeInterval)delay; + +@end + +#pragma mark - + +/** + `AFJSONRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSJSONSerialization`, setting the `Content-Type` of the encoded request to `application/json`. + */ +@interface AFJSONRequestSerializer : AFHTTPRequestSerializer + +/** + Options for writing the request JSON data from Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONWritingOptions". `0` by default. + */ +@property (nonatomic, assign) NSJSONWritingOptions writingOptions; + +/** + Creates and returns a JSON serializer with specified reading and writing options. + + @param writingOptions The specified JSON writing options. + */ ++ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions; + +@end + +#pragma mark - + +/** + `AFPropertyListRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSPropertyListSerializer`, setting the `Content-Type` of the encoded request to `application/x-plist`. + */ +@interface AFPropertyListRequestSerializer : AFHTTPRequestSerializer + +/** + The property list format. Possible values are described in "NSPropertyListFormat". + */ +@property (nonatomic, assign) NSPropertyListFormat format; + +/** + @warning The `writeOptions` property is currently unused. + */ +@property (nonatomic, assign) NSPropertyListWriteOptions writeOptions; + +/** + Creates and returns a property list serializer with a specified format, read options, and write options. + + @param format The property list format. + @param writeOptions The property list write options. + + @warning The `writeOptions` property is currently unused. + */ ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + writeOptions:(NSPropertyListWriteOptions)writeOptions; + +@end + +#pragma mark - + +///---------------- +/// @name Constants +///---------------- + +/** + ## Error Domains + + The following error domain is predefined. + + - `NSString * const AFURLRequestSerializationErrorDomain` + + ### Constants + + `AFURLRequestSerializationErrorDomain` + AFURLRequestSerializer errors. Error codes for `AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. + */ +FOUNDATION_EXPORT NSString * const AFURLRequestSerializationErrorDomain; + +/** + ## User info dictionary keys + + These keys may exist in the user info dictionary, in addition to those defined for NSError. + + - `NSString * const AFNetworkingOperationFailingURLRequestErrorKey` + + ### Constants + + `AFNetworkingOperationFailingURLRequestErrorKey` + The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFURLRequestSerializationErrorDomain`. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLRequestErrorKey; + +/** + ## Throttling Bandwidth for HTTP Request Input Streams + + @see -throttleBandwidthWithPacketSize:delay: + + ### Constants + + `kAFUploadStream3GSuggestedPacketSize` + Maximum packet size, in number of bytes. Equal to 16kb. + + `kAFUploadStream3GSuggestedDelay` + Duration of delay each time a packet is read. Equal to 0.2 seconds. + */ +FOUNDATION_EXPORT NSUInteger const kAFUploadStream3GSuggestedPacketSize; +FOUNDATION_EXPORT NSTimeInterval const kAFUploadStream3GSuggestedDelay; + +NS_ASSUME_NONNULL_END diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFURLRequestSerialization.m b/its/plugin/projects/AFNetworking/AFNetworking/AFURLRequestSerialization.m new file mode 100644 index 00000000..086e6747 --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFURLRequestSerialization.m @@ -0,0 +1,1376 @@ +// AFURLRequestSerialization.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "AFURLRequestSerialization.h" + +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV +#import +#else +#import +#endif + +NSString * const AFURLRequestSerializationErrorDomain = @"com.alamofire.error.serialization.request"; +NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"com.alamofire.serialization.request.error.response"; + +typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, id parameters, NSError *__autoreleasing *error); + +/** + Returns a percent-escaped string following RFC 3986 for a query string key or value. + RFC 3986 states that the following characters are "reserved" characters. + - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + + In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + should be percent-escaped in the query string. + - parameter string: The string to be percent-escaped. + - returns: The percent-escaped string. + */ +NSString * AFPercentEscapedStringFromString(NSString *string) { + static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4 + static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;="; + + NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy]; + [allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]]; + + // FIXME: https://github.com/AFNetworking/AFNetworking/pull/3028 + // return [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; + + static NSUInteger const batchSize = 50; + + NSUInteger index = 0; + NSMutableString *escaped = @"".mutableCopy; + + while (index < string.length) { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wgnu" + NSUInteger length = MIN(string.length - index, batchSize); +#pragma GCC diagnostic pop + NSRange range = NSMakeRange(index, length); + + // To avoid breaking up character sequences such as 👴🏻👮🏽 + range = [string rangeOfComposedCharacterSequencesForRange:range]; + + NSString *substring = [string substringWithRange:range]; + NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; + [escaped appendString:encoded]; + + index += range.length; + } + + return escaped; +} + +#pragma mark - + +@interface AFQueryStringPair : NSObject +@property (readwrite, nonatomic, strong) id field; +@property (readwrite, nonatomic, strong) id value; + +- (instancetype)initWithField:(id)field value:(id)value; + +- (NSString *)URLEncodedStringValue; +@end + +@implementation AFQueryStringPair + +- (instancetype)initWithField:(id)field value:(id)value { + self = [super init]; + if (!self) { + return nil; + } + + self.field = field; + self.value = value; + + return self; +} + +- (NSString *)URLEncodedStringValue { + if (!self.value || [self.value isEqual:[NSNull null]]) { + return AFPercentEscapedStringFromString([self.field description]); + } else { + return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedStringFromString([self.field description]), AFPercentEscapedStringFromString([self.value description])]; + } +} + +@end + +#pragma mark - + +FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary); +FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value); + +NSString * AFQueryStringFromParameters(NSDictionary *parameters) { + NSMutableArray *mutablePairs = [NSMutableArray array]; + for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { + [mutablePairs addObject:[pair URLEncodedStringValue]]; + } + + return [mutablePairs componentsJoinedByString:@"&"]; +} + +NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) { + return AFQueryStringPairsFromKeyAndValue(nil, dictionary); +} + +NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) { + NSMutableArray *mutableQueryStringComponents = [NSMutableArray array]; + + NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)]; + + if ([value isKindOfClass:[NSDictionary class]]) { + NSDictionary *dictionary = value; + // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries + for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) { + id nestedValue = dictionary[nestedKey]; + if (nestedValue) { + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)]; + } + } + } else if ([value isKindOfClass:[NSArray class]]) { + NSArray *array = value; + for (id nestedValue in array) { + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)]; + } + } else if ([value isKindOfClass:[NSSet class]]) { + NSSet *set = value; + for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) { + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue(key, obj)]; + } + } else { + [mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]]; + } + + return mutableQueryStringComponents; +} + +#pragma mark - + +@interface AFStreamingMultipartFormData : NSObject +- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest + stringEncoding:(NSStringEncoding)encoding; + +- (NSMutableURLRequest *)requestByFinalizingMultipartFormData; +@end + +#pragma mark - + +static NSArray * AFHTTPRequestSerializerObservedKeyPaths() { + static NSArray *_AFHTTPRequestSerializerObservedKeyPaths = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _AFHTTPRequestSerializerObservedKeyPaths = @[NSStringFromSelector(@selector(allowsCellularAccess)), NSStringFromSelector(@selector(cachePolicy)), NSStringFromSelector(@selector(HTTPShouldHandleCookies)), NSStringFromSelector(@selector(HTTPShouldUsePipelining)), NSStringFromSelector(@selector(networkServiceType)), NSStringFromSelector(@selector(timeoutInterval))]; + }); + + return _AFHTTPRequestSerializerObservedKeyPaths; +} + +static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerObserverContext; + +@interface AFHTTPRequestSerializer () +@property (readwrite, nonatomic, strong) NSMutableSet *mutableObservedChangedKeyPaths; +@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableHTTPRequestHeaders; +@property (readwrite, nonatomic, assign) AFHTTPRequestQueryStringSerializationStyle queryStringSerializationStyle; +@property (readwrite, nonatomic, copy) AFQueryStringSerializationBlock queryStringSerialization; +@end + +@implementation AFHTTPRequestSerializer + ++ (instancetype)serializer { + return [[self alloc] init]; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.stringEncoding = NSUTF8StringEncoding; + + self.mutableHTTPRequestHeaders = [NSMutableDictionary dictionary]; + + // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 + NSMutableArray *acceptLanguagesComponents = [NSMutableArray array]; + [[NSLocale preferredLanguages] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + float q = 1.0f - (idx * 0.1f); + [acceptLanguagesComponents addObject:[NSString stringWithFormat:@"%@;q=%0.1g", obj, q]]; + *stop = q <= 0.5f; + }]; + [self setValue:[acceptLanguagesComponents componentsJoinedByString:@", "] forHTTPHeaderField:@"Accept-Language"]; + + NSString *userAgent = nil; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" +#if TARGET_OS_IOS + // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 + userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]; +#elif TARGET_OS_WATCH + // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 + userAgent = [NSString stringWithFormat:@"%@/%@ (%@; watchOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[WKInterfaceDevice currentDevice] model], [[WKInterfaceDevice currentDevice] systemVersion], [[WKInterfaceDevice currentDevice] screenScale]]; +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) + userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]]; +#endif +#pragma clang diagnostic pop + if (userAgent) { + if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) { + NSMutableString *mutableUserAgent = [userAgent mutableCopy]; + if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) { + userAgent = mutableUserAgent; + } + } + [self setValue:userAgent forHTTPHeaderField:@"User-Agent"]; + } + + // HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html + self.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", @"DELETE", nil]; + + self.mutableObservedChangedKeyPaths = [NSMutableSet set]; + for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { + if ([self respondsToSelector:NSSelectorFromString(keyPath)]) { + [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext]; + } + } + + return self; +} + +- (void)dealloc { + for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { + if ([self respondsToSelector:NSSelectorFromString(keyPath)]) { + [self removeObserver:self forKeyPath:keyPath context:AFHTTPRequestSerializerObserverContext]; + } + } +} + +#pragma mark - + +// Workarounds for crashing behavior using Key-Value Observing with XCTest +// See https://github.com/AFNetworking/AFNetworking/issues/2523 + +- (void)setAllowsCellularAccess:(BOOL)allowsCellularAccess { + [self willChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))]; + _allowsCellularAccess = allowsCellularAccess; + [self didChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))]; +} + +- (void)setCachePolicy:(NSURLRequestCachePolicy)cachePolicy { + [self willChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))]; + _cachePolicy = cachePolicy; + [self didChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))]; +} + +- (void)setHTTPShouldHandleCookies:(BOOL)HTTPShouldHandleCookies { + [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))]; + _HTTPShouldHandleCookies = HTTPShouldHandleCookies; + [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))]; +} + +- (void)setHTTPShouldUsePipelining:(BOOL)HTTPShouldUsePipelining { + [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))]; + _HTTPShouldUsePipelining = HTTPShouldUsePipelining; + [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))]; +} + +- (void)setNetworkServiceType:(NSURLRequestNetworkServiceType)networkServiceType { + [self willChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))]; + _networkServiceType = networkServiceType; + [self didChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))]; +} + +- (void)setTimeoutInterval:(NSTimeInterval)timeoutInterval { + [self willChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))]; + _timeoutInterval = timeoutInterval; + [self didChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))]; +} + +#pragma mark - + +- (NSDictionary *)HTTPRequestHeaders { + return [NSDictionary dictionaryWithDictionary:self.mutableHTTPRequestHeaders]; +} + +- (void)setValue:(NSString *)value +forHTTPHeaderField:(NSString *)field +{ + [self.mutableHTTPRequestHeaders setValue:value forKey:field]; +} + +- (NSString *)valueForHTTPHeaderField:(NSString *)field { + return [self.mutableHTTPRequestHeaders valueForKey:field]; +} + +- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username + password:(NSString *)password +{ + NSData *basicAuthCredentials = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding]; + NSString *base64AuthCredentials = [basicAuthCredentials base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0]; + [self setValue:[NSString stringWithFormat:@"Basic %@", base64AuthCredentials] forHTTPHeaderField:@"Authorization"]; +} + +- (void)clearAuthorizationHeader { + [self.mutableHTTPRequestHeaders removeObjectForKey:@"Authorization"]; +} + +#pragma mark - + +- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style { + self.queryStringSerializationStyle = style; + self.queryStringSerialization = nil; +} + +- (void)setQueryStringSerializationWithBlock:(NSString *(^)(NSURLRequest *, id, NSError *__autoreleasing *))block { + self.queryStringSerialization = block; +} + +#pragma mark - + +- (NSMutableURLRequest *)requestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(method); + NSParameterAssert(URLString); + + NSURL *url = [NSURL URLWithString:URLString]; + + NSParameterAssert(url); + + NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url]; + mutableRequest.HTTPMethod = method; + + for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { + if ([self.mutableObservedChangedKeyPaths containsObject:keyPath]) { + [mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath]; + } + } + + mutableRequest = [[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error] mutableCopy]; + + return mutableRequest; +} + +- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(NSDictionary *)parameters + constructingBodyWithBlock:(void (^)(id formData))block + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(method); + NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]); + + NSMutableURLRequest *mutableRequest = [self requestWithMethod:method URLString:URLString parameters:nil error:error]; + + __block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:mutableRequest stringEncoding:NSUTF8StringEncoding]; + + if (parameters) { + for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { + NSData *data = nil; + if ([pair.value isKindOfClass:[NSData class]]) { + data = pair.value; + } else if ([pair.value isEqual:[NSNull null]]) { + data = [NSData data]; + } else { + data = [[pair.value description] dataUsingEncoding:self.stringEncoding]; + } + + if (data) { + [formData appendPartWithFormData:data name:[pair.field description]]; + } + } + } + + if (block) { + block(formData); + } + + return [formData requestByFinalizingMultipartFormData]; +} + +- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request + writingStreamContentsToFile:(NSURL *)fileURL + completionHandler:(void (^)(NSError *error))handler +{ + NSParameterAssert(request.HTTPBodyStream); + NSParameterAssert([fileURL isFileURL]); + + NSInputStream *inputStream = request.HTTPBodyStream; + NSOutputStream *outputStream = [[NSOutputStream alloc] initWithURL:fileURL append:NO]; + __block NSError *error = nil; + + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + + [inputStream open]; + [outputStream open]; + + while ([inputStream hasBytesAvailable] && [outputStream hasSpaceAvailable]) { + uint8_t buffer[1024]; + + NSInteger bytesRead = [inputStream read:buffer maxLength:1024]; + if (inputStream.streamError || bytesRead < 0) { + error = inputStream.streamError; + break; + } + + NSInteger bytesWritten = [outputStream write:buffer maxLength:(NSUInteger)bytesRead]; + if (outputStream.streamError || bytesWritten < 0) { + error = outputStream.streamError; + break; + } + + if (bytesRead == 0 && bytesWritten == 0) { + break; + } + } + + [outputStream close]; + [inputStream close]; + + if (handler) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler(error); + }); + } + }); + + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + mutableRequest.HTTPBodyStream = nil; + + return mutableRequest; +} + +#pragma mark - AFURLRequestSerialization + +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(request); + + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + + [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { + if (![request valueForHTTPHeaderField:field]) { + [mutableRequest setValue:value forHTTPHeaderField:field]; + } + }]; + + NSString *query = nil; + if (parameters) { + if (self.queryStringSerialization) { + NSError *serializationError; + query = self.queryStringSerialization(request, parameters, &serializationError); + + if (serializationError) { + if (error) { + *error = serializationError; + } + + return nil; + } + } else { + switch (self.queryStringSerializationStyle) { + case AFHTTPRequestQueryStringDefaultStyle: + query = AFQueryStringFromParameters(parameters); + break; + } + } + } + + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { + if (query) { + mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]]; + } + } else { + // #2864: an empty string is a valid x-www-form-urlencoded payload + if (!query) { + query = @""; + } + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { + [mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; + } + [mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]]; + } + + return mutableRequest; +} + +#pragma mark - NSKeyValueObserving + ++ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key { + if ([AFHTTPRequestSerializerObservedKeyPaths() containsObject:key]) { + return NO; + } + + return [super automaticallyNotifiesObserversForKey:key]; +} + +- (void)observeValueForKeyPath:(NSString *)keyPath + ofObject:(__unused id)object + change:(NSDictionary *)change + context:(void *)context +{ + if (context == AFHTTPRequestSerializerObserverContext) { + if ([change[NSKeyValueChangeNewKey] isEqual:[NSNull null]]) { + [self.mutableObservedChangedKeyPaths removeObject:keyPath]; + } else { + [self.mutableObservedChangedKeyPaths addObject:keyPath]; + } + } +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [self init]; + if (!self) { + return nil; + } + + self.mutableHTTPRequestHeaders = [[decoder decodeObjectOfClass:[NSDictionary class] forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))] mutableCopy]; + self.queryStringSerializationStyle = (AFHTTPRequestQueryStringSerializationStyle)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [coder encodeObject:self.mutableHTTPRequestHeaders forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))]; + [coder encodeInteger:self.queryStringSerializationStyle forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init]; + serializer.mutableHTTPRequestHeaders = [self.mutableHTTPRequestHeaders mutableCopyWithZone:zone]; + serializer.queryStringSerializationStyle = self.queryStringSerializationStyle; + serializer.queryStringSerialization = self.queryStringSerialization; + + return serializer; +} + +@end + +#pragma mark - + +static NSString * AFCreateMultipartFormBoundary() { + return [NSString stringWithFormat:@"Boundary+%08X%08X", arc4random(), arc4random()]; +} + +static NSString * const kAFMultipartFormCRLF = @"\r\n"; + +static inline NSString * AFMultipartFormInitialBoundary(NSString *boundary) { + return [NSString stringWithFormat:@"--%@%@", boundary, kAFMultipartFormCRLF]; +} + +static inline NSString * AFMultipartFormEncapsulationBoundary(NSString *boundary) { + return [NSString stringWithFormat:@"%@--%@%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF]; +} + +static inline NSString * AFMultipartFormFinalBoundary(NSString *boundary) { + return [NSString stringWithFormat:@"%@--%@--%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF]; +} + +static inline NSString * AFContentTypeForPathExtension(NSString *extension) { + NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL); + NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType); + if (!contentType) { + return @"application/octet-stream"; + } else { + return contentType; + } +} + +NSUInteger const kAFUploadStream3GSuggestedPacketSize = 1024 * 16; +NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2; + +@interface AFHTTPBodyPart : NSObject +@property (nonatomic, assign) NSStringEncoding stringEncoding; +@property (nonatomic, strong) NSDictionary *headers; +@property (nonatomic, copy) NSString *boundary; +@property (nonatomic, strong) id body; +@property (nonatomic, assign) unsigned long long bodyContentLength; +@property (nonatomic, strong) NSInputStream *inputStream; + +@property (nonatomic, assign) BOOL hasInitialBoundary; +@property (nonatomic, assign) BOOL hasFinalBoundary; + +@property (readonly, nonatomic, assign, getter = hasBytesAvailable) BOOL bytesAvailable; +@property (readonly, nonatomic, assign) unsigned long long contentLength; + +- (NSInteger)read:(uint8_t *)buffer + maxLength:(NSUInteger)length; +@end + +@interface AFMultipartBodyStream : NSInputStream +@property (nonatomic, assign) NSUInteger numberOfBytesInPacket; +@property (nonatomic, assign) NSTimeInterval delay; +@property (nonatomic, strong) NSInputStream *inputStream; +@property (readonly, nonatomic, assign) unsigned long long contentLength; +@property (readonly, nonatomic, assign, getter = isEmpty) BOOL empty; + +- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding; +- (void)setInitialAndFinalBoundaries; +- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart; +@end + +#pragma mark - + +@interface AFStreamingMultipartFormData () +@property (readwrite, nonatomic, copy) NSMutableURLRequest *request; +@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding; +@property (readwrite, nonatomic, copy) NSString *boundary; +@property (readwrite, nonatomic, strong) AFMultipartBodyStream *bodyStream; +@end + +@implementation AFStreamingMultipartFormData + +- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest + stringEncoding:(NSStringEncoding)encoding +{ + self = [super init]; + if (!self) { + return nil; + } + + self.request = urlRequest; + self.stringEncoding = encoding; + self.boundary = AFCreateMultipartFormBoundary(); + self.bodyStream = [[AFMultipartBodyStream alloc] initWithStringEncoding:encoding]; + + return self; +} + +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + error:(NSError * __autoreleasing *)error +{ + NSParameterAssert(fileURL); + NSParameterAssert(name); + + NSString *fileName = [fileURL lastPathComponent]; + NSString *mimeType = AFContentTypeForPathExtension([fileURL pathExtension]); + + return [self appendPartWithFileURL:fileURL name:name fileName:fileName mimeType:mimeType error:error]; +} + +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType + error:(NSError * __autoreleasing *)error +{ + NSParameterAssert(fileURL); + NSParameterAssert(name); + NSParameterAssert(fileName); + NSParameterAssert(mimeType); + + if (![fileURL isFileURL]) { + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"AFNetworking", nil)}; + if (error) { + *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo]; + } + + return NO; + } else if ([fileURL checkResourceIsReachableAndReturnError:error] == NO) { + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"File URL not reachable.", @"AFNetworking", nil)}; + if (error) { + *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo]; + } + + return NO; + } + + NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:error]; + if (!fileAttributes) { + return NO; + } + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; + [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; + + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = mutableHeaders; + bodyPart.boundary = self.boundary; + bodyPart.body = fileURL; + bodyPart.bodyContentLength = [fileAttributes[NSFileSize] unsignedLongLongValue]; + [self.bodyStream appendHTTPBodyPart:bodyPart]; + + return YES; +} + +- (void)appendPartWithInputStream:(NSInputStream *)inputStream + name:(NSString *)name + fileName:(NSString *)fileName + length:(int64_t)length + mimeType:(NSString *)mimeType +{ + NSParameterAssert(name); + NSParameterAssert(fileName); + NSParameterAssert(mimeType); + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; + [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; + + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = mutableHeaders; + bodyPart.boundary = self.boundary; + bodyPart.body = inputStream; + + bodyPart.bodyContentLength = (unsigned long long)length; + + [self.bodyStream appendHTTPBodyPart:bodyPart]; +} + +- (void)appendPartWithFileData:(NSData *)data + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType +{ + NSParameterAssert(name); + NSParameterAssert(fileName); + NSParameterAssert(mimeType); + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; + [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; + + [self appendPartWithHeaders:mutableHeaders body:data]; +} + +- (void)appendPartWithFormData:(NSData *)data + name:(NSString *)name +{ + NSParameterAssert(name); + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"]; + + [self appendPartWithHeaders:mutableHeaders body:data]; +} + +- (void)appendPartWithHeaders:(NSDictionary *)headers + body:(NSData *)body +{ + NSParameterAssert(body); + + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = headers; + bodyPart.boundary = self.boundary; + bodyPart.bodyContentLength = [body length]; + bodyPart.body = body; + + [self.bodyStream appendHTTPBodyPart:bodyPart]; +} + +- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes + delay:(NSTimeInterval)delay +{ + self.bodyStream.numberOfBytesInPacket = numberOfBytes; + self.bodyStream.delay = delay; +} + +- (NSMutableURLRequest *)requestByFinalizingMultipartFormData { + if ([self.bodyStream isEmpty]) { + return self.request; + } + + // Reset the initial and final boundaries to ensure correct Content-Length + [self.bodyStream setInitialAndFinalBoundaries]; + [self.request setHTTPBodyStream:self.bodyStream]; + + [self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", self.boundary] forHTTPHeaderField:@"Content-Type"]; + [self.request setValue:[NSString stringWithFormat:@"%llu", [self.bodyStream contentLength]] forHTTPHeaderField:@"Content-Length"]; + + return self.request; +} + +@end + +#pragma mark - + +@interface NSStream () +@property (readwrite) NSStreamStatus streamStatus; +@property (readwrite, copy) NSError *streamError; +@end + +@interface AFMultipartBodyStream () +@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding; +@property (readwrite, nonatomic, strong) NSMutableArray *HTTPBodyParts; +@property (readwrite, nonatomic, strong) NSEnumerator *HTTPBodyPartEnumerator; +@property (readwrite, nonatomic, strong) AFHTTPBodyPart *currentHTTPBodyPart; +@property (readwrite, nonatomic, strong) NSOutputStream *outputStream; +@property (readwrite, nonatomic, strong) NSMutableData *buffer; +@end + +@implementation AFMultipartBodyStream +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wimplicit-atomic-properties" +#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1100) +@synthesize delegate; +#endif +@synthesize streamStatus; +@synthesize streamError; +#pragma clang diagnostic pop + +- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding { + self = [super init]; + if (!self) { + return nil; + } + + self.stringEncoding = encoding; + self.HTTPBodyParts = [NSMutableArray array]; + self.numberOfBytesInPacket = NSIntegerMax; + + return self; +} + +- (void)setInitialAndFinalBoundaries { + if ([self.HTTPBodyParts count] > 0) { + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { + bodyPart.hasInitialBoundary = NO; + bodyPart.hasFinalBoundary = NO; + } + + [[self.HTTPBodyParts firstObject] setHasInitialBoundary:YES]; + [[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES]; + } +} + +- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart { + [self.HTTPBodyParts addObject:bodyPart]; +} + +- (BOOL)isEmpty { + return [self.HTTPBodyParts count] == 0; +} + +#pragma mark - NSInputStream + +- (NSInteger)read:(uint8_t *)buffer + maxLength:(NSUInteger)length +{ + if ([self streamStatus] == NSStreamStatusClosed) { + return 0; + } + + NSInteger totalNumberOfBytesRead = 0; + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + while ((NSUInteger)totalNumberOfBytesRead < MIN(length, self.numberOfBytesInPacket)) { + if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) { + if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) { + break; + } + } else { + NSUInteger maxLength = MIN(length, self.numberOfBytesInPacket) - (NSUInteger)totalNumberOfBytesRead; + NSInteger numberOfBytesRead = [self.currentHTTPBodyPart read:&buffer[totalNumberOfBytesRead] maxLength:maxLength]; + if (numberOfBytesRead == -1) { + self.streamError = self.currentHTTPBodyPart.inputStream.streamError; + break; + } else { + totalNumberOfBytesRead += numberOfBytesRead; + + if (self.delay > 0.0f) { + [NSThread sleepForTimeInterval:self.delay]; + } + } + } + } +#pragma clang diagnostic pop + + return totalNumberOfBytesRead; +} + +- (BOOL)getBuffer:(__unused uint8_t **)buffer + length:(__unused NSUInteger *)len +{ + return NO; +} + +- (BOOL)hasBytesAvailable { + return [self streamStatus] == NSStreamStatusOpen; +} + +#pragma mark - NSStream + +- (void)open { + if (self.streamStatus == NSStreamStatusOpen) { + return; + } + + self.streamStatus = NSStreamStatusOpen; + + [self setInitialAndFinalBoundaries]; + self.HTTPBodyPartEnumerator = [self.HTTPBodyParts objectEnumerator]; +} + +- (void)close { + self.streamStatus = NSStreamStatusClosed; +} + +- (id)propertyForKey:(__unused NSString *)key { + return nil; +} + +- (BOOL)setProperty:(__unused id)property + forKey:(__unused NSString *)key +{ + return NO; +} + +- (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop + forMode:(__unused NSString *)mode +{} + +- (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop + forMode:(__unused NSString *)mode +{} + +- (unsigned long long)contentLength { + unsigned long long length = 0; + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { + length += [bodyPart contentLength]; + } + + return length; +} + +#pragma mark - Undocumented CFReadStream Bridged Methods + +- (void)_scheduleInCFRunLoop:(__unused CFRunLoopRef)aRunLoop + forMode:(__unused CFStringRef)aMode +{} + +- (void)_unscheduleFromCFRunLoop:(__unused CFRunLoopRef)aRunLoop + forMode:(__unused CFStringRef)aMode +{} + +- (BOOL)_setCFClientFlags:(__unused CFOptionFlags)inFlags + callback:(__unused CFReadStreamClientCallBack)inCallback + context:(__unused CFStreamClientContext *)inContext { + return NO; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding]; + + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { + [bodyStreamCopy appendHTTPBodyPart:[bodyPart copy]]; + } + + [bodyStreamCopy setInitialAndFinalBoundaries]; + + return bodyStreamCopy; +} + +@end + +#pragma mark - + +typedef enum { + AFEncapsulationBoundaryPhase = 1, + AFHeaderPhase = 2, + AFBodyPhase = 3, + AFFinalBoundaryPhase = 4, +} AFHTTPBodyPartReadPhase; + +@interface AFHTTPBodyPart () { + AFHTTPBodyPartReadPhase _phase; + NSInputStream *_inputStream; + unsigned long long _phaseReadOffset; +} + +- (BOOL)transitionToNextPhase; +- (NSInteger)readData:(NSData *)data + intoBuffer:(uint8_t *)buffer + maxLength:(NSUInteger)length; +@end + +@implementation AFHTTPBodyPart + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + [self transitionToNextPhase]; + + return self; +} + +- (void)dealloc { + if (_inputStream) { + [_inputStream close]; + _inputStream = nil; + } +} + +- (NSInputStream *)inputStream { + if (!_inputStream) { + if ([self.body isKindOfClass:[NSData class]]) { + _inputStream = [NSInputStream inputStreamWithData:self.body]; + } else if ([self.body isKindOfClass:[NSURL class]]) { + _inputStream = [NSInputStream inputStreamWithURL:self.body]; + } else if ([self.body isKindOfClass:[NSInputStream class]]) { + _inputStream = self.body; + } else { + _inputStream = [NSInputStream inputStreamWithData:[NSData data]]; + } + } + + return _inputStream; +} + +- (NSString *)stringForHeaders { + NSMutableString *headerString = [NSMutableString string]; + for (NSString *field in [self.headers allKeys]) { + [headerString appendString:[NSString stringWithFormat:@"%@: %@%@", field, [self.headers valueForKey:field], kAFMultipartFormCRLF]]; + } + [headerString appendString:kAFMultipartFormCRLF]; + + return [NSString stringWithString:headerString]; +} + +- (unsigned long long)contentLength { + unsigned long long length = 0; + + NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding]; + length += [encapsulationBoundaryData length]; + + NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding]; + length += [headersData length]; + + length += _bodyContentLength; + + NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]); + length += [closingBoundaryData length]; + + return length; +} + +- (BOOL)hasBytesAvailable { + // Allows `read:maxLength:` to be called again if `AFMultipartFormFinalBoundary` doesn't fit into the available buffer + if (_phase == AFFinalBoundaryPhase) { + return YES; + } + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wcovered-switch-default" + switch (self.inputStream.streamStatus) { + case NSStreamStatusNotOpen: + case NSStreamStatusOpening: + case NSStreamStatusOpen: + case NSStreamStatusReading: + case NSStreamStatusWriting: + return YES; + case NSStreamStatusAtEnd: + case NSStreamStatusClosed: + case NSStreamStatusError: + default: + return NO; + } +#pragma clang diagnostic pop +} + +- (NSInteger)read:(uint8_t *)buffer + maxLength:(NSUInteger)length +{ + NSInteger totalNumberOfBytesRead = 0; + + if (_phase == AFEncapsulationBoundaryPhase) { + NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding]; + totalNumberOfBytesRead += [self readData:encapsulationBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + } + + if (_phase == AFHeaderPhase) { + NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding]; + totalNumberOfBytesRead += [self readData:headersData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + } + + if (_phase == AFBodyPhase) { + NSInteger numberOfBytesRead = 0; + + numberOfBytesRead = [self.inputStream read:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + if (numberOfBytesRead == -1) { + return -1; + } else { + totalNumberOfBytesRead += numberOfBytesRead; + + if ([self.inputStream streamStatus] >= NSStreamStatusAtEnd) { + [self transitionToNextPhase]; + } + } + } + + if (_phase == AFFinalBoundaryPhase) { + NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]); + totalNumberOfBytesRead += [self readData:closingBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + } + + return totalNumberOfBytesRead; +} + +- (NSInteger)readData:(NSData *)data + intoBuffer:(uint8_t *)buffer + maxLength:(NSUInteger)length +{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length)); + [data getBytes:buffer range:range]; +#pragma clang diagnostic pop + + _phaseReadOffset += range.length; + + if (((NSUInteger)_phaseReadOffset) >= [data length]) { + [self transitionToNextPhase]; + } + + return (NSInteger)range.length; +} + +- (BOOL)transitionToNextPhase { + if (![[NSThread currentThread] isMainThread]) { + dispatch_sync(dispatch_get_main_queue(), ^{ + [self transitionToNextPhase]; + }); + return YES; + } + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wcovered-switch-default" + switch (_phase) { + case AFEncapsulationBoundaryPhase: + _phase = AFHeaderPhase; + break; + case AFHeaderPhase: + [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; + [self.inputStream open]; + _phase = AFBodyPhase; + break; + case AFBodyPhase: + [self.inputStream close]; + _phase = AFFinalBoundaryPhase; + break; + case AFFinalBoundaryPhase: + default: + _phase = AFEncapsulationBoundaryPhase; + break; + } + _phaseReadOffset = 0; +#pragma clang diagnostic pop + + return YES; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init]; + + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = self.headers; + bodyPart.bodyContentLength = self.bodyContentLength; + bodyPart.body = self.body; + bodyPart.boundary = self.boundary; + + return bodyPart; +} + +@end + +#pragma mark - + +@implementation AFJSONRequestSerializer + ++ (instancetype)serializer { + return [self serializerWithWritingOptions:(NSJSONWritingOptions)0]; +} + ++ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions +{ + AFJSONRequestSerializer *serializer = [[self alloc] init]; + serializer.writingOptions = writingOptions; + + return serializer; +} + +#pragma mark - AFURLRequestSerialization + +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(request); + + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { + return [super requestBySerializingRequest:request withParameters:parameters error:error]; + } + + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + + [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { + if (![request valueForHTTPHeaderField:field]) { + [mutableRequest setValue:value forHTTPHeaderField:field]; + } + }]; + + if (parameters) { + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { + [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; + } + + [mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]]; + } + + return mutableRequest; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.writingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writingOptions))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeInteger:self.writingOptions forKey:NSStringFromSelector(@selector(writingOptions))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFJSONRequestSerializer *serializer = [super copyWithZone:zone]; + serializer.writingOptions = self.writingOptions; + + return serializer; +} + +@end + +#pragma mark - + +@implementation AFPropertyListRequestSerializer + ++ (instancetype)serializer { + return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 writeOptions:0]; +} + ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + writeOptions:(NSPropertyListWriteOptions)writeOptions +{ + AFPropertyListRequestSerializer *serializer = [[self alloc] init]; + serializer.format = format; + serializer.writeOptions = writeOptions; + + return serializer; +} + +#pragma mark - AFURLRequestSerializer + +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(request); + + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { + return [super requestBySerializingRequest:request withParameters:parameters error:error]; + } + + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + + [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { + if (![request valueForHTTPHeaderField:field]) { + [mutableRequest setValue:value forHTTPHeaderField:field]; + } + }]; + + if (parameters) { + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { + [mutableRequest setValue:@"application/x-plist" forHTTPHeaderField:@"Content-Type"]; + } + + [mutableRequest setHTTPBody:[NSPropertyListSerialization dataWithPropertyList:parameters format:self.format options:self.writeOptions error:error]]; + } + + return mutableRequest; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; + self.writeOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writeOptions))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeInteger:self.format forKey:NSStringFromSelector(@selector(format))]; + [coder encodeObject:@(self.writeOptions) forKey:NSStringFromSelector(@selector(writeOptions))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFPropertyListRequestSerializer *serializer = [super copyWithZone:zone]; + serializer.format = self.format; + serializer.writeOptions = self.writeOptions; + + return serializer; +} + +@end diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFURLResponseSerialization.h b/its/plugin/projects/AFNetworking/AFNetworking/AFURLResponseSerialization.h new file mode 100644 index 00000000..c1357aed --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFURLResponseSerialization.h @@ -0,0 +1,311 @@ +// AFURLResponseSerialization.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + The `AFURLResponseSerialization` protocol is adopted by an object that decodes data into a more useful object representation, according to details in the server response. Response serializers may additionally perform validation on the incoming response and data. + + For example, a JSON response serializer may check for an acceptable status code (`2XX` range) and content type (`application/json`), decoding a valid JSON response into an object. + */ +@protocol AFURLResponseSerialization + +/** + The response object decoded from the data associated with a specified response. + + @param response The response to be processed. + @param data The response data to be decoded. + @param error The error that occurred while attempting to decode the response data. + + @return The object decoded from the specified response data. + */ +- (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response + data:(nullable NSData *)data + error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW; + +@end + +#pragma mark - + +/** + `AFHTTPResponseSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation. + + Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPResponseSerializer` in order to ensure consistent default behavior. + */ +@interface AFHTTPResponseSerializer : NSObject + +- (instancetype)init; + +/** + The string encoding used to serialize data received from the server, when no string encoding is specified by the response. `NSUTF8StringEncoding` by default. + */ +@property (nonatomic, assign) NSStringEncoding stringEncoding; + +/** + Creates and returns a serializer with default configuration. + */ ++ (instancetype)serializer; + +///----------------------------------------- +/// @name Configuring Response Serialization +///----------------------------------------- + +/** + The acceptable HTTP status codes for responses. When non-`nil`, responses with status codes not contained by the set will result in an error during validation. + + See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html + */ +@property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes; + +/** + The acceptable MIME types for responses. When non-`nil`, responses with a `Content-Type` with MIME types that do not intersect with the set will result in an error during validation. + */ +@property (nonatomic, copy, nullable) NSSet *acceptableContentTypes; + +/** + Validates the specified response and data. + + In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks. + + @param response The response to be validated. + @param data The data associated with the response. + @param error The error that occurred while attempting to validate the response. + + @return `YES` if the response is valid, otherwise `NO`. + */ +- (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response + data:(nullable NSData *)data + error:(NSError * _Nullable __autoreleasing *)error; + +@end + +#pragma mark - + + +/** + `AFJSONResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes JSON responses. + + By default, `AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types: + + - `application/json` + - `text/json` + - `text/javascript` + */ +@interface AFJSONResponseSerializer : AFHTTPResponseSerializer + +- (instancetype)init; + +/** + Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. + */ +@property (nonatomic, assign) NSJSONReadingOptions readingOptions; + +/** + Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`. + */ +@property (nonatomic, assign) BOOL removesKeysWithNullValues; + +/** + Creates and returns a JSON serializer with specified reading and writing options. + + @param readingOptions The specified JSON reading options. + */ ++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions; + +@end + +#pragma mark - + +/** + `AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects. + + By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: + + - `application/xml` + - `text/xml` + */ +@interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer + +@end + +#pragma mark - + +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED + +/** + `AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. + + By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: + + - `application/xml` + - `text/xml` + */ +@interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer + +- (instancetype)init; + +/** + Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. + */ +@property (nonatomic, assign) NSUInteger options; + +/** + Creates and returns an XML document serializer with the specified options. + + @param mask The XML document options. + */ ++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask; + +@end + +#endif + +#pragma mark - + +/** + `AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. + + By default, `AFPropertyListResponseSerializer` accepts the following MIME types: + + - `application/x-plist` + */ +@interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer + +- (instancetype)init; + +/** + The property list format. Possible values are described in "NSPropertyListFormat". + */ +@property (nonatomic, assign) NSPropertyListFormat format; + +/** + The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions." + */ +@property (nonatomic, assign) NSPropertyListReadOptions readOptions; + +/** + Creates and returns a property list serializer with a specified format, read options, and write options. + + @param format The property list format. + @param readOptions The property list reading options. + */ ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + readOptions:(NSPropertyListReadOptions)readOptions; + +@end + +#pragma mark - + +/** + `AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses. + + By default, `AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage: + + - `image/tiff` + - `image/jpeg` + - `image/gif` + - `image/png` + - `image/ico` + - `image/x-icon` + - `image/bmp` + - `image/x-bmp` + - `image/x-xbitmap` + - `image/x-win-bitmap` + */ +@interface AFImageResponseSerializer : AFHTTPResponseSerializer + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH +/** + The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance. + */ +@property (nonatomic, assign) CGFloat imageScale; + +/** + Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default. + */ +@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage; +#endif + +@end + +#pragma mark - + +/** + `AFCompoundSerializer` is a subclass of `AFHTTPResponseSerializer` that delegates the response serialization to the first `AFHTTPResponseSerializer` object that returns an object for `responseObjectForResponse:data:error:`, falling back on the default behavior of `AFHTTPResponseSerializer`. This is useful for supporting multiple potential types and structures of server responses with a single serializer. + */ +@interface AFCompoundResponseSerializer : AFHTTPResponseSerializer + +/** + The component response serializers. + */ +@property (readonly, nonatomic, copy) NSArray > *responseSerializers; + +/** + Creates and returns a compound serializer comprised of the specified response serializers. + + @warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`. + */ ++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray > *)responseSerializers; + +@end + +///---------------- +/// @name Constants +///---------------- + +/** + ## Error Domains + + The following error domain is predefined. + + - `NSString * const AFURLResponseSerializationErrorDomain` + + ### Constants + + `AFURLResponseSerializationErrorDomain` + AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. + */ +FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain; + +/** + ## User info dictionary keys + + These keys may exist in the user info dictionary, in addition to those defined for NSError. + + - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey` + - `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey` + + ### Constants + + `AFNetworkingOperationFailingURLResponseErrorKey` + The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. + + `AFNetworkingOperationFailingURLResponseDataErrorKey` + The corresponding value is an `NSData` containing the original data of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey; + +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey; + +NS_ASSUME_NONNULL_END diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFURLResponseSerialization.m b/its/plugin/projects/AFNetworking/AFNetworking/AFURLResponseSerialization.m new file mode 100755 index 00000000..1402e8d3 --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFURLResponseSerialization.m @@ -0,0 +1,803 @@ +// AFURLResponseSerialization.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "AFURLResponseSerialization.h" + +#import + +#if TARGET_OS_IOS +#import +#elif TARGET_OS_WATCH +#import +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) +#import +#endif + +NSString * const AFURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response"; +NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response"; +NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data"; + +static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) { + if (!error) { + return underlyingError; + } + + if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) { + return error; + } + + NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy]; + mutableUserInfo[NSUnderlyingErrorKey] = underlyingError; + + return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo]; +} + +static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) { + if ([error.domain isEqualToString:domain] && error.code == code) { + return YES; + } else if (error.userInfo[NSUnderlyingErrorKey]) { + return AFErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain); + } + + return NO; +} + +static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) { + if ([JSONObject isKindOfClass:[NSArray class]]) { + NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]]; + for (id value in (NSArray *)JSONObject) { + [mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)]; + } + + return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray]; + } else if ([JSONObject isKindOfClass:[NSDictionary class]]) { + NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject]; + for (id key in [(NSDictionary *)JSONObject allKeys]) { + id value = (NSDictionary *)JSONObject[key]; + if (!value || [value isEqual:[NSNull null]]) { + [mutableDictionary removeObjectForKey:key]; + } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) { + mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions); + } + } + + return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary]; + } + + return JSONObject; +} + +@implementation AFHTTPResponseSerializer + ++ (instancetype)serializer { + return [[self alloc] init]; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.stringEncoding = NSUTF8StringEncoding; + + self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; + self.acceptableContentTypes = nil; + + return self; +} + +#pragma mark - + +- (BOOL)validateResponse:(NSHTTPURLResponse *)response + data:(NSData *)data + error:(NSError * __autoreleasing *)error +{ + BOOL responseIsValid = YES; + NSError *validationError = nil; + + if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) { + if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]]) { + if ([data length] > 0 && [response URL]) { + NSMutableDictionary *mutableUserInfo = [@{ + NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]], + NSURLErrorFailingURLErrorKey:[response URL], + AFNetworkingOperationFailingURLResponseErrorKey: response, + } mutableCopy]; + if (data) { + mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data; + } + + validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError); + } + + responseIsValid = NO; + } + + if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) { + NSMutableDictionary *mutableUserInfo = [@{ + NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode], + NSURLErrorFailingURLErrorKey:[response URL], + AFNetworkingOperationFailingURLResponseErrorKey: response, + } mutableCopy]; + + if (data) { + mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data; + } + + validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError); + + responseIsValid = NO; + } + } + + if (error && !responseIsValid) { + *error = validationError; + } + + return responseIsValid; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + [self validateResponse:(NSHTTPURLResponse *)response data:data error:error]; + + return data; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [self init]; + if (!self) { + return nil; + } + + self.acceptableStatusCodes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableStatusCodes))]; + self.acceptableContentTypes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableContentTypes))]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [coder encodeObject:self.acceptableStatusCodes forKey:NSStringFromSelector(@selector(acceptableStatusCodes))]; + [coder encodeObject:self.acceptableContentTypes forKey:NSStringFromSelector(@selector(acceptableContentTypes))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; + serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone]; + serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone]; + + return serializer; +} + +@end + +#pragma mark - + +@implementation AFJSONResponseSerializer + ++ (instancetype)serializer { + return [self serializerWithReadingOptions:(NSJSONReadingOptions)0]; +} + ++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions { + AFJSONResponseSerializer *serializer = [[self alloc] init]; + serializer.readingOptions = readingOptions; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + id responseObject = nil; + NSError *serializationError = nil; + // Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization. + // See https://github.com/rails/rails/issues/1742 + BOOL isSpace = [data isEqualToData:[NSData dataWithBytes:" " length:1]]; + if (data.length > 0 && !isSpace) { + responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError]; + } else { + return nil; + } + + if (self.removesKeysWithNullValues && responseObject) { + responseObject = AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions); + } + + if (error) { + *error = AFErrorWithUnderlyingError(serializationError, *error); + } + + return responseObject; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.readingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readingOptions))] unsignedIntegerValue]; + self.removesKeysWithNullValues = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))] boolValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.readingOptions) forKey:NSStringFromSelector(@selector(readingOptions))]; + [coder encodeObject:@(self.removesKeysWithNullValues) forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFJSONResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; + serializer.readingOptions = self.readingOptions; + serializer.removesKeysWithNullValues = self.removesKeysWithNullValues; + + return serializer; +} + +@end + +#pragma mark - + +@implementation AFXMLParserResponseSerializer + ++ (instancetype)serializer { + AFXMLParserResponseSerializer *serializer = [[self alloc] init]; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSHTTPURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + return [[NSXMLParser alloc] initWithData:data]; +} + +@end + +#pragma mark - + +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED + +@implementation AFXMLDocumentResponseSerializer + ++ (instancetype)serializer { + return [self serializerWithXMLDocumentOptions:0]; +} + ++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask { + AFXMLDocumentResponseSerializer *serializer = [[self alloc] init]; + serializer.options = mask; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + NSError *serializationError = nil; + NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:self.options error:&serializationError]; + + if (error) { + *error = AFErrorWithUnderlyingError(serializationError, *error); + } + + return document; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.options = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(options))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.options) forKey:NSStringFromSelector(@selector(options))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFXMLDocumentResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; + serializer.options = self.options; + + return serializer; +} + +@end + +#endif + +#pragma mark - + +@implementation AFPropertyListResponseSerializer + ++ (instancetype)serializer { + return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0]; +} + ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + readOptions:(NSPropertyListReadOptions)readOptions +{ + AFPropertyListResponseSerializer *serializer = [[self alloc] init]; + serializer.format = format; + serializer.readOptions = readOptions; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/x-plist", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + id responseObject; + NSError *serializationError = nil; + + if (data) { + responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError]; + } + + if (error) { + *error = AFErrorWithUnderlyingError(serializationError, *error); + } + + return responseObject; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; + self.readOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readOptions))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))]; + [coder encodeObject:@(self.readOptions) forKey:NSStringFromSelector(@selector(readOptions))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFPropertyListResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; + serializer.format = self.format; + serializer.readOptions = self.readOptions; + + return serializer; +} + +@end + +#pragma mark - + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH +#import +#import + +@interface UIImage (AFNetworkingSafeImageLoading) ++ (UIImage *)af_safeImageWithData:(NSData *)data; +@end + +static NSLock* imageLock = nil; + +@implementation UIImage (AFNetworkingSafeImageLoading) + ++ (UIImage *)af_safeImageWithData:(NSData *)data { + UIImage* image = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + imageLock = [[NSLock alloc] init]; + }); + + [imageLock lock]; + image = [UIImage imageWithData:data]; + [imageLock unlock]; + return image; +} + +@end + +static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) { + UIImage *image = [UIImage af_safeImageWithData:data]; + if (image.images) { + return image; + } + + return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation]; +} + +static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) { + if (!data || [data length] == 0) { + return nil; + } + + CGImageRef imageRef = NULL; + CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data); + + if ([response.MIMEType isEqualToString:@"image/png"]) { + imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); + } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) { + imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); + + if (imageRef) { + CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageRef); + CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(imageColorSpace); + + // CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so fall back to AFImageWithDataAtScale + if (imageColorSpaceModel == kCGColorSpaceModelCMYK) { + CGImageRelease(imageRef); + imageRef = NULL; + } + } + } + + CGDataProviderRelease(dataProvider); + + UIImage *image = AFImageWithDataAtScale(data, scale); + if (!imageRef) { + if (image.images || !image) { + return image; + } + + imageRef = CGImageCreateCopy([image CGImage]); + if (!imageRef) { + return nil; + } + } + + size_t width = CGImageGetWidth(imageRef); + size_t height = CGImageGetHeight(imageRef); + size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef); + + if (width * height > 1024 * 1024 || bitsPerComponent > 8) { + CGImageRelease(imageRef); + + return image; + } + + // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate + size_t bytesPerRow = 0; + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace); + CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); + + if (colorSpaceModel == kCGColorSpaceModelRGB) { + uint32_t alpha = (bitmapInfo & kCGBitmapAlphaInfoMask); +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wassign-enum" + if (alpha == kCGImageAlphaNone) { + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + bitmapInfo |= kCGImageAlphaNoneSkipFirst; + } else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) { + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + bitmapInfo |= kCGImageAlphaPremultipliedFirst; + } +#pragma clang diagnostic pop + } + + CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo); + + CGColorSpaceRelease(colorSpace); + + if (!context) { + CGImageRelease(imageRef); + + return image; + } + + CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), imageRef); + CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context); + + CGContextRelease(context); + + UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation]; + + CGImageRelease(inflatedImageRef); + CGImageRelease(imageRef); + + return inflatedImage; +} +#endif + + +@implementation AFImageResponseSerializer + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil]; + +#if TARGET_OS_IOS || TARGET_OS_TV + self.imageScale = [[UIScreen mainScreen] scale]; + self.automaticallyInflatesResponseImage = YES; +#elif TARGET_OS_WATCH + self.imageScale = [[WKInterfaceDevice currentDevice] screenScale]; + self.automaticallyInflatesResponseImage = YES; +#endif + + return self; +} + +#pragma mark - AFURLResponseSerializer + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH + if (self.automaticallyInflatesResponseImage) { + return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale); + } else { + return AFImageWithDataAtScale(data, self.imageScale); + } +#else + // Ensure that the image is set to it's correct pixel width and height + NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data]; + NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])]; + [image addRepresentation:bitimage]; + + return image; +#endif + + return nil; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH + NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))]; +#if CGFLOAT_IS_DOUBLE + self.imageScale = [imageScale doubleValue]; +#else + self.imageScale = [imageScale floatValue]; +#endif + + self.automaticallyInflatesResponseImage = [decoder decodeBoolForKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; +#endif + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH + [coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))]; + [coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; +#endif +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFImageResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH + serializer.imageScale = self.imageScale; + serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage; +#endif + + return serializer; +} + +@end + +#pragma mark - + +@interface AFCompoundResponseSerializer () +@property (readwrite, nonatomic, copy) NSArray *responseSerializers; +@end + +@implementation AFCompoundResponseSerializer + ++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers { + AFCompoundResponseSerializer *serializer = [[self alloc] init]; + serializer.responseSerializers = responseSerializers; + + return serializer; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + for (id serializer in self.responseSerializers) { + if (![serializer isKindOfClass:[AFHTTPResponseSerializer class]]) { + continue; + } + + NSError *serializerError = nil; + id responseObject = [serializer responseObjectForResponse:response data:data error:&serializerError]; + if (responseObject) { + if (error) { + *error = AFErrorWithUnderlyingError(serializerError, *error); + } + + return responseObject; + } + } + + return [super responseObjectForResponse:response data:data error:error]; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.responseSerializers = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(responseSerializers))]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:self.responseSerializers forKey:NSStringFromSelector(@selector(responseSerializers))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFCompoundResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; + serializer.responseSerializers = self.responseSerializers; + + return serializer; +} + +@end diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFURLSessionManager.h b/its/plugin/projects/AFNetworking/AFNetworking/AFURLSessionManager.h new file mode 100644 index 00000000..691e80c8 --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFURLSessionManager.h @@ -0,0 +1,499 @@ +// AFURLSessionManager.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + + +#import + +#import "AFURLResponseSerialization.h" +#import "AFURLRequestSerialization.h" +#import "AFSecurityPolicy.h" +#if !TARGET_OS_WATCH +#import "AFNetworkReachabilityManager.h" +#endif + +/** + `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to ``, ``, ``, and ``. + + ## Subclassing Notes + + This is the base class for `AFHTTPSessionManager`, which adds functionality specific to making HTTP requests. If you are looking to extend `AFURLSessionManager` specifically for HTTP, consider subclassing `AFHTTPSessionManager` instead. + + ## NSURLSession & NSURLSessionTask Delegate Methods + + `AFURLSessionManager` implements the following delegate methods: + + ### `NSURLSessionDelegate` + + - `URLSession:didBecomeInvalidWithError:` + - `URLSession:didReceiveChallenge:completionHandler:` + - `URLSessionDidFinishEventsForBackgroundURLSession:` + + ### `NSURLSessionTaskDelegate` + + - `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:` + - `URLSession:task:didReceiveChallenge:completionHandler:` + - `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:` + - `URLSession:task:didCompleteWithError:` + + ### `NSURLSessionDataDelegate` + + - `URLSession:dataTask:didReceiveResponse:completionHandler:` + - `URLSession:dataTask:didBecomeDownloadTask:` + - `URLSession:dataTask:didReceiveData:` + - `URLSession:dataTask:willCacheResponse:completionHandler:` + + ### `NSURLSessionDownloadDelegate` + + - `URLSession:downloadTask:didFinishDownloadingToURL:` + - `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:` + - `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:` + + If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first. + + ## Network Reachability Monitoring + + Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `AFNetworkReachabilityManager` for more details. + + ## NSCoding Caveats + + - Encoded managers do not include any block properties. Be sure to set delegate callback blocks when using `-initWithCoder:` or `NSKeyedUnarchiver`. + + ## NSCopying Caveats + + - `-copy` and `-copyWithZone:` return a new manager with a new `NSURLSession` created from the configuration of the original. + - Operation copies do not include any delegate callback blocks, as they often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ session manager when copied. + + @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance. + */ + +NS_ASSUME_NONNULL_BEGIN + +@interface AFURLSessionManager : NSObject + +/** + The managed session. + */ +@property (readonly, nonatomic, strong) NSURLSession *session; + +/** + The operation queue on which delegate callbacks are run. + */ +@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue; + +/** + Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`. + + @warning `responseSerializer` must not be `nil`. + */ +@property (nonatomic, strong) id responseSerializer; + +///------------------------------- +/// @name Managing Security Policy +///------------------------------- + +/** + The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. + */ +@property (nonatomic, strong) AFSecurityPolicy *securityPolicy; + +#if !TARGET_OS_WATCH +///-------------------------------------- +/// @name Monitoring Network Reachability +///-------------------------------------- + +/** + The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default. + */ +@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager; +#endif + +///---------------------------- +/// @name Getting Session Tasks +///---------------------------- + +/** + The data, upload, and download tasks currently run by the managed session. + */ +@property (readonly, nonatomic, strong) NSArray *tasks; + +/** + The data tasks currently run by the managed session. + */ +@property (readonly, nonatomic, strong) NSArray *dataTasks; + +/** + The upload tasks currently run by the managed session. + */ +@property (readonly, nonatomic, strong) NSArray *uploadTasks; + +/** + The download tasks currently run by the managed session. + */ +@property (readonly, nonatomic, strong) NSArray *downloadTasks; + +///------------------------------- +/// @name Managing Callback Queues +///------------------------------- + +/** + The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used. + */ +@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue; + +/** + The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. + */ +@property (nonatomic, strong, nullable) dispatch_group_t completionGroup; + +///--------------------------------- +/// @name Working Around System Bugs +///--------------------------------- + +/** + Whether to attempt to retry creation of upload tasks for background sessions when initial call returns `nil`. `NO` by default. + + @bug As of iOS 7.0, there is a bug where upload tasks created for background tasks are sometimes `nil`. As a workaround, if this property is `YES`, AFNetworking will follow Apple's recommendation to try creating the task again. + + @see https://github.com/AFNetworking/AFNetworking/issues/1675 + */ +@property (nonatomic, assign) BOOL attemptsToRecreateUploadTasksForBackgroundSessions; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Creates and returns a manager for a session created with the specified configuration. This is the designated initializer. + + @param configuration The configuration used to create the managed session. + + @return A manager for a newly-created session. + */ +- (instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; + +/** + Invalidates the managed session, optionally canceling pending tasks. + + @param cancelPendingTasks Whether or not to cancel pending tasks. + */ +- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks; + +///------------------------- +/// @name Running Data Tasks +///------------------------- + +/** + Creates an `NSURLSessionDataTask` with the specified request. + + @param request The HTTP request for the request. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +/** + Creates an `NSURLSessionDataTask` with the specified request. + + @param request The HTTP request for the request. + @param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param downloadProgress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +///--------------------------- +/// @name Running Upload Tasks +///--------------------------- + +/** + Creates an `NSURLSessionUploadTask` with the specified request for a local file. + + @param request The HTTP request for the request. + @param fileURL A URL to the local file to be uploaded. + @param progress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + + @see `attemptsToRecreateUploadTasksForBackgroundSessions` + */ +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromFile:(NSURL *)fileURL + progress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +/** + Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body. + + @param request The HTTP request for the request. + @param bodyData A data object containing the HTTP body to be uploaded. + @param progress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromData:(nullable NSData *)bodyData + progress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +/** + Creates an `NSURLSessionUploadTask` with the specified streaming request. + + @param request The HTTP request for the request. + @param progress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request + progress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +///----------------------------- +/// @name Running Download Tasks +///----------------------------- + +/** + Creates an `NSURLSessionDownloadTask` with the specified request. + + @param request The HTTP request for the request. + @param progress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL. + @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any. + + @warning If using a background `NSURLSessionConfiguration` on iOS, these blocks will be lost when the app is terminated. Background sessions may prefer to use `-setDownloadTaskDidFinishDownloadingBlock:` to specify the URL for saving the downloaded file, rather than the destination block of this method. + */ +- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request + progress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock + destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler; + +/** + Creates an `NSURLSessionDownloadTask` with the specified resume data. + + @param resumeData The data used to resume downloading. + @param progress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL. + @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any. + */ +- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData + progress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock + destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler; + +///--------------------------------- +/// @name Getting Progress for Tasks +///--------------------------------- + +/** + Returns the upload progress of the specified task. + + @param task The session task. Must not be `nil`. + + @return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable. + */ +- (nullable NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task; + +/** + Returns the download progress of the specified task. + + @param task The session task. Must not be `nil`. + + @return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable. + */ +- (nullable NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task; + +///----------------------------------------- +/// @name Setting Session Delegate Callbacks +///----------------------------------------- + +/** + Sets a block to be executed when the managed session becomes invalid, as handled by the `NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`. + + @param block A block object to be executed when the managed session becomes invalid. The block has no return value, and takes two arguments: the session, and the error related to the cause of invalidation. + */ +- (void)setSessionDidBecomeInvalidBlock:(nullable void (^)(NSURLSession *session, NSError *error))block; + +/** + Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`. + + @param block A block object to be executed when a connection level authentication challenge has occurred. The block returns the disposition of the authentication challenge, and takes three arguments: the session, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge. + */ +- (void)setSessionDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block; + +///-------------------------------------- +/// @name Setting Task Delegate Callbacks +///-------------------------------------- + +/** + Sets a block to be executed when a task requires a new request body stream to send to the remote server, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:needNewBodyStream:`. + + @param block A block object to be executed when a task requires a new request body stream. + */ +- (void)setTaskNeedNewBodyStreamBlock:(nullable NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block; + +/** + Sets a block to be executed when an HTTP request is attempting to perform a redirection to a different URL, as handled by the `NSURLSessionTaskDelegate` method `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`. + + @param block A block object to be executed when an HTTP request is attempting to perform a redirection to a different URL. The block returns the request to be made for the redirection, and takes four arguments: the session, the task, the redirection response, and the request corresponding to the redirection response. + */ +- (void)setTaskWillPerformHTTPRedirectionBlock:(nullable NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block; + +/** + Sets a block to be executed when a session task has received a request specific authentication challenge, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didReceiveChallenge:completionHandler:`. + + @param block A block object to be executed when a session task has received a request specific authentication challenge. The block returns the disposition of the authentication challenge, and takes four arguments: the session, the task, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge. + */ +- (void)setTaskDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block; + +/** + Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. + + @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes five arguments: the session, the task, the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread. + */ +- (void)setTaskDidSendBodyDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block; + +/** + Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`. + + @param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any error that occurred in the process of executing the task. + */ +- (void)setTaskDidCompleteBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSError * _Nullable error))block; + +///------------------------------------------- +/// @name Setting Data Task Delegate Callbacks +///------------------------------------------- + +/** + Sets a block to be executed when a data task has received a response, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveResponse:completionHandler:`. + + @param block A block object to be executed when a data task has received a response. The block returns the disposition of the session response, and takes three arguments: the session, the data task, and the received response. + */ +- (void)setDataTaskDidReceiveResponseBlock:(nullable NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block; + +/** + Sets a block to be executed when a data task has become a download task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`. + + @param block A block object to be executed when a data task has become a download task. The block has no return value, and takes three arguments: the session, the data task, and the download task it has become. + */ +- (void)setDataTaskDidBecomeDownloadTaskBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block; + +/** + Sets a block to be executed when a data task receives data, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`. + + @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the session, the data task, and the data received. This block may be called multiple times, and will execute on the session manager operation queue. + */ +- (void)setDataTaskDidReceiveDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block; + +/** + Sets a block to be executed to determine the caching behavior of a data task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:willCacheResponse:completionHandler:`. + + @param block A block object to be executed to determine the caching behavior of a data task. The block returns the response to cache, and takes three arguments: the session, the data task, and the proposed cached URL response. + */ +- (void)setDataTaskWillCacheResponseBlock:(nullable NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block; + +/** + Sets a block to be executed once all messages enqueued for a session have been delivered, as handled by the `NSURLSessionDataDelegate` method `URLSessionDidFinishEventsForBackgroundURLSession:`. + + @param block A block object to be executed once all messages enqueued for a session have been delivered. The block has no return value and takes a single argument: the session. + */ +- (void)setDidFinishEventsForBackgroundURLSessionBlock:(nullable void (^)(NSURLSession *session))block; + +///----------------------------------------------- +/// @name Setting Download Task Delegate Callbacks +///----------------------------------------------- + +/** + Sets a block to be executed when a download task has completed a download, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didFinishDownloadingToURL:`. + + @param block A block object to be executed when a download task has completed. The block returns the URL the download should be moved to, and takes three arguments: the session, the download task, and the temporary location of the downloaded file. If the file manager encounters an error while attempting to move the temporary file to the destination, an `AFURLSessionDownloadTaskDidFailToMoveFileNotification` will be posted, with the download task as its object, and the user info of the error. + */ +- (void)setDownloadTaskDidFinishDownloadingBlock:(nullable NSURL * _Nullable (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block; + +/** + Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`. + + @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes five arguments: the session, the download task, the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the session manager operation queue. + */ +- (void)setDownloadTaskDidWriteDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block; + +/** + Sets a block to be executed when a download task has been resumed, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. + + @param block A block object to be executed when a download task has been resumed. The block has no return value and takes four arguments: the session, the download task, the file offset of the resumed download, and the total number of bytes expected to be downloaded. + */ +- (void)setDownloadTaskDidResumeBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block; + +@end + +///-------------------- +/// @name Notifications +///-------------------- + +/** + Posted when a task resumes. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidResumeNotification; + +/** + Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteNotification; + +/** + Posted when a task suspends its execution. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidSuspendNotification; + +/** + Posted when a session is invalidated. + */ +FOUNDATION_EXPORT NSString * const AFURLSessionDidInvalidateNotification; + +/** + Posted when a session download task encountered an error when moving the temporary download file to a specified destination. + */ +FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification; + +/** + The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if response data exists for the task. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseDataKey; + +/** + The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the response was serialized. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey; + +/** + The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the task has an associated response serializer. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey; + +/** + The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an the response data has been stored directly to disk. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteAssetPathKey; + +/** + Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an error exists. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteErrorKey; + +NS_ASSUME_NONNULL_END diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFURLSessionManager.m b/its/plugin/projects/AFNetworking/AFNetworking/AFURLSessionManager.m new file mode 100644 index 00000000..170581ac --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFURLSessionManager.m @@ -0,0 +1,1244 @@ +// AFURLSessionManager.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "AFURLSessionManager.h" +#import + +#ifndef NSFoundationVersionNumber_iOS_8_0 +#define NSFoundationVersionNumber_With_Fixed_5871104061079552_bug 1140.11 +#else +#define NSFoundationVersionNumber_With_Fixed_5871104061079552_bug NSFoundationVersionNumber_iOS_8_0 +#endif + +static dispatch_queue_t url_session_manager_creation_queue() { + static dispatch_queue_t af_url_session_manager_creation_queue; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + af_url_session_manager_creation_queue = dispatch_queue_create("com.alamofire.networking.session.manager.creation", DISPATCH_QUEUE_SERIAL); + }); + + return af_url_session_manager_creation_queue; +} + +static void url_session_manager_create_task_safely(dispatch_block_t block) { + if (NSFoundationVersionNumber < NSFoundationVersionNumber_With_Fixed_5871104061079552_bug) { + // Fix of bug + // Open Radar:http://openradar.appspot.com/radar?id=5871104061079552 (status: Fixed in iOS8) + // Issue about:https://github.com/AFNetworking/AFNetworking/issues/2093 + dispatch_sync(url_session_manager_creation_queue(), block); + } else { + block(); + } +} + +static dispatch_queue_t url_session_manager_processing_queue() { + static dispatch_queue_t af_url_session_manager_processing_queue; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + af_url_session_manager_processing_queue = dispatch_queue_create("com.alamofire.networking.session.manager.processing", DISPATCH_QUEUE_CONCURRENT); + }); + + return af_url_session_manager_processing_queue; +} + +static dispatch_group_t url_session_manager_completion_group() { + static dispatch_group_t af_url_session_manager_completion_group; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + af_url_session_manager_completion_group = dispatch_group_create(); + }); + + return af_url_session_manager_completion_group; +} + +NSString * const AFNetworkingTaskDidResumeNotification = @"com.alamofire.networking.task.resume"; +NSString * const AFNetworkingTaskDidCompleteNotification = @"com.alamofire.networking.task.complete"; +NSString * const AFNetworkingTaskDidSuspendNotification = @"com.alamofire.networking.task.suspend"; +NSString * const AFURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate"; +NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error"; + +NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse"; +NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer"; +NSString * const AFNetworkingTaskDidCompleteResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata"; +NSString * const AFNetworkingTaskDidCompleteErrorKey = @"com.alamofire.networking.task.complete.error"; +NSString * const AFNetworkingTaskDidCompleteAssetPathKey = @"com.alamofire.networking.task.complete.assetpath"; + +static NSString * const AFURLSessionManagerLockName = @"com.alamofire.networking.session.manager.lock"; + +static NSUInteger const AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask = 3; + +static void * AFTaskStateChangedContext = &AFTaskStateChangedContext; + +typedef void (^AFURLSessionDidBecomeInvalidBlock)(NSURLSession *session, NSError *error); +typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential); + +typedef NSURLRequest * (^AFURLSessionTaskWillPerformHTTPRedirectionBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request); +typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionTaskDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential); +typedef void (^AFURLSessionDidFinishEventsForBackgroundURLSessionBlock)(NSURLSession *session); + +typedef NSInputStream * (^AFURLSessionTaskNeedNewBodyStreamBlock)(NSURLSession *session, NSURLSessionTask *task); +typedef void (^AFURLSessionTaskDidSendBodyDataBlock)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend); +typedef void (^AFURLSessionTaskDidCompleteBlock)(NSURLSession *session, NSURLSessionTask *task, NSError *error); + +typedef NSURLSessionResponseDisposition (^AFURLSessionDataTaskDidReceiveResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response); +typedef void (^AFURLSessionDataTaskDidBecomeDownloadTaskBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask); +typedef void (^AFURLSessionDataTaskDidReceiveDataBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data); +typedef NSCachedURLResponse * (^AFURLSessionDataTaskWillCacheResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse); + +typedef NSURL * (^AFURLSessionDownloadTaskDidFinishDownloadingBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location); +typedef void (^AFURLSessionDownloadTaskDidWriteDataBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite); +typedef void (^AFURLSessionDownloadTaskDidResumeBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes); +typedef void (^AFURLSessionTaskProgressBlock)(NSProgress *); + +typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id responseObject, NSError *error); + + +#pragma mark - + +@interface AFURLSessionManagerTaskDelegate : NSObject +@property (nonatomic, weak) AFURLSessionManager *manager; +@property (nonatomic, strong) NSMutableData *mutableData; +@property (nonatomic, strong) NSProgress *uploadProgress; +@property (nonatomic, strong) NSProgress *downloadProgress; +@property (nonatomic, copy) NSURL *downloadFileURL; +@property (nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading; +@property (nonatomic, copy) AFURLSessionTaskProgressBlock uploadProgressBlock; +@property (nonatomic, copy) AFURLSessionTaskProgressBlock downloadProgressBlock; +@property (nonatomic, copy) AFURLSessionTaskCompletionHandler completionHandler; +@end + +@implementation AFURLSessionManagerTaskDelegate + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.mutableData = [NSMutableData data]; + self.uploadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil]; + self.uploadProgress.totalUnitCount = NSURLSessionTransferSizeUnknown; + + self.downloadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil]; + self.downloadProgress.totalUnitCount = NSURLSessionTransferSizeUnknown; + return self; +} + +#pragma mark - NSProgress Tracking + +- (void)setupProgressForTask:(NSURLSessionTask *)task { + __weak __typeof__(task) weakTask = task; + + self.uploadProgress.totalUnitCount = task.countOfBytesExpectedToSend; + self.downloadProgress.totalUnitCount = task.countOfBytesExpectedToReceive; + [self.uploadProgress setCancellable:YES]; + [self.uploadProgress setCancellationHandler:^{ + __typeof__(weakTask) strongTask = weakTask; + [strongTask cancel]; + }]; + [self.uploadProgress setPausable:YES]; + [self.uploadProgress setPausingHandler:^{ + __typeof__(weakTask) strongTask = weakTask; + [strongTask suspend]; + }]; + if ([self.uploadProgress respondsToSelector:@selector(setResumingHandler:)]) { + [self.uploadProgress setResumingHandler:^{ + __typeof__(weakTask) strongTask = weakTask; + [strongTask resume]; + }]; + } + + [self.downloadProgress setCancellable:YES]; + [self.downloadProgress setCancellationHandler:^{ + __typeof__(weakTask) strongTask = weakTask; + [strongTask cancel]; + }]; + [self.downloadProgress setPausable:YES]; + [self.downloadProgress setPausingHandler:^{ + __typeof__(weakTask) strongTask = weakTask; + [strongTask suspend]; + }]; + + if ([self.downloadProgress respondsToSelector:@selector(setResumingHandler:)]) { + [self.downloadProgress setResumingHandler:^{ + __typeof__(weakTask) strongTask = weakTask; + [strongTask resume]; + }]; + } + + [task addObserver:self + forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived)) + options:NSKeyValueObservingOptionNew + context:NULL]; + [task addObserver:self + forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToReceive)) + options:NSKeyValueObservingOptionNew + context:NULL]; + + [task addObserver:self + forKeyPath:NSStringFromSelector(@selector(countOfBytesSent)) + options:NSKeyValueObservingOptionNew + context:NULL]; + [task addObserver:self + forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToSend)) + options:NSKeyValueObservingOptionNew + context:NULL]; + + [self.downloadProgress addObserver:self + forKeyPath:NSStringFromSelector(@selector(fractionCompleted)) + options:NSKeyValueObservingOptionNew + context:NULL]; + [self.uploadProgress addObserver:self + forKeyPath:NSStringFromSelector(@selector(fractionCompleted)) + options:NSKeyValueObservingOptionNew + context:NULL]; +} + +- (void)cleanUpProgressForTask:(NSURLSessionTask *)task { + [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))]; + [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToReceive))]; + [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))]; + [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToSend))]; + [self.downloadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))]; + [self.uploadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))]; +} + +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + if ([object isKindOfClass:[NSURLSessionTask class]] || [object isKindOfClass:[NSURLSessionDownloadTask class]]) { + if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) { + self.downloadProgress.completedUnitCount = [change[@"new"] longLongValue]; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesExpectedToReceive))]) { + self.downloadProgress.totalUnitCount = [change[@"new"] longLongValue]; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) { + self.uploadProgress.completedUnitCount = [change[@"new"] longLongValue]; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesExpectedToSend))]) { + self.uploadProgress.totalUnitCount = [change[@"new"] longLongValue]; + } + } + else if ([object isEqual:self.downloadProgress]) { + if (self.downloadProgressBlock) { + self.downloadProgressBlock(object); + } + } + else if ([object isEqual:self.uploadProgress]) { + if (self.uploadProgressBlock) { + self.uploadProgressBlock(object); + } + } +} + +#pragma mark - NSURLSessionTaskDelegate + +- (void)URLSession:(__unused NSURLSession *)session + task:(NSURLSessionTask *)task +didCompleteWithError:(NSError *)error +{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + __strong AFURLSessionManager *manager = self.manager; + + __block id responseObject = nil; + + __block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer; + + //Performance Improvement from #2672 + NSData *data = nil; + if (self.mutableData) { + data = [self.mutableData copy]; + //We no longer need the reference, so nil it out to gain back some memory. + self.mutableData = nil; + } + + if (self.downloadFileURL) { + userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL; + } else if (data) { + userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data; + } + + if (error) { + userInfo[AFNetworkingTaskDidCompleteErrorKey] = error; + + dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{ + if (self.completionHandler) { + self.completionHandler(task.response, responseObject, error); + } + + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo]; + }); + }); + } else { + dispatch_async(url_session_manager_processing_queue(), ^{ + NSError *serializationError = nil; + responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:data error:&serializationError]; + + if (self.downloadFileURL) { + responseObject = self.downloadFileURL; + } + + if (responseObject) { + userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject; + } + + if (serializationError) { + userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError; + } + + dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{ + if (self.completionHandler) { + self.completionHandler(task.response, responseObject, serializationError); + } + + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo]; + }); + }); + }); + } +#pragma clang diagnostic pop +} + +#pragma mark - NSURLSessionDataTaskDelegate + +- (void)URLSession:(__unused NSURLSession *)session + dataTask:(__unused NSURLSessionDataTask *)dataTask + didReceiveData:(NSData *)data +{ + [self.mutableData appendData:data]; +} + +#pragma mark - NSURLSessionDownloadTaskDelegate + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask +didFinishDownloadingToURL:(NSURL *)location +{ + NSError *fileManagerError = nil; + self.downloadFileURL = nil; + + if (self.downloadTaskDidFinishDownloading) { + self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location); + if (self.downloadFileURL) { + [[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError]; + + if (fileManagerError) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo]; + } + } + } +} + +@end + +#pragma mark - + +/** + * A workaround for issues related to key-value observing the `state` of an `NSURLSessionTask`. + * + * See: + * - https://github.com/AFNetworking/AFNetworking/issues/1477 + * - https://github.com/AFNetworking/AFNetworking/issues/2638 + * - https://github.com/AFNetworking/AFNetworking/pull/2702 + */ + +static inline void af_swizzleSelector(Class theClass, SEL originalSelector, SEL swizzledSelector) { + Method originalMethod = class_getInstanceMethod(theClass, originalSelector); + Method swizzledMethod = class_getInstanceMethod(theClass, swizzledSelector); + method_exchangeImplementations(originalMethod, swizzledMethod); +} + +static inline BOOL af_addMethod(Class theClass, SEL selector, Method method) { + return class_addMethod(theClass, selector, method_getImplementation(method), method_getTypeEncoding(method)); +} + +static NSString * const AFNSURLSessionTaskDidResumeNotification = @"com.alamofire.networking.nsurlsessiontask.resume"; +static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofire.networking.nsurlsessiontask.suspend"; + +@interface _AFURLSessionTaskSwizzling : NSObject + +@end + +@implementation _AFURLSessionTaskSwizzling + ++ (void)load { + /** + WARNING: Trouble Ahead + https://github.com/AFNetworking/AFNetworking/pull/2702 + */ + + if (NSClassFromString(@"NSURLSessionTask")) { + /** + iOS 7 and iOS 8 differ in NSURLSessionTask implementation, which makes the next bit of code a bit tricky. + Many Unit Tests have been built to validate as much of this behavior has possible. + Here is what we know: + - NSURLSessionTasks are implemented with class clusters, meaning the class you request from the API isn't actually the type of class you will get back. + - Simply referencing `[NSURLSessionTask class]` will not work. You need to ask an `NSURLSession` to actually create an object, and grab the class from there. + - On iOS 7, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `__NSCFURLSessionTask`. + - On iOS 8, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `NSURLSessionTask`. + - On iOS 7, `__NSCFLocalSessionTask` and `__NSCFURLSessionTask` are the only two classes that have their own implementations of `resume` and `suspend`, and `__NSCFLocalSessionTask` DOES NOT CALL SUPER. This means both classes need to be swizzled. + - On iOS 8, `NSURLSessionTask` is the only class that implements `resume` and `suspend`. This means this is the only class that needs to be swizzled. + - Because `NSURLSessionTask` is not involved in the class hierarchy for every version of iOS, its easier to add the swizzled methods to a dummy class and manage them there. + + Some Assumptions: + - No implementations of `resume` or `suspend` call super. If this were to change in a future version of iOS, we'd need to handle it. + - No background task classes override `resume` or `suspend` + + The current solution: + 1) Grab an instance of `__NSCFLocalDataTask` by asking an instance of `NSURLSession` for a data task. + 2) Grab a pointer to the original implementation of `af_resume` + 3) Check to see if the current class has an implementation of resume. If so, continue to step 4. + 4) Grab the super class of the current class. + 5) Grab a pointer for the current class to the current implementation of `resume`. + 6) Grab a pointer for the super class to the current implementation of `resume`. + 7) If the current class implementation of `resume` is not equal to the super class implementation of `resume` AND the current implementation of `resume` is not equal to the original implementation of `af_resume`, THEN swizzle the methods + 8) Set the current class to the super class, and repeat steps 3-8 + */ + NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration]; + NSURLSession * session = [NSURLSession sessionWithConfiguration:configuration]; +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnonnull" + NSURLSessionDataTask *localDataTask = [session dataTaskWithURL:nil]; +#pragma clang diagnostic pop + IMP originalAFResumeIMP = method_getImplementation(class_getInstanceMethod([self class], @selector(af_resume))); + Class currentClass = [localDataTask class]; + + while (class_getInstanceMethod(currentClass, @selector(resume))) { + Class superClass = [currentClass superclass]; + IMP classResumeIMP = method_getImplementation(class_getInstanceMethod(currentClass, @selector(resume))); + IMP superclassResumeIMP = method_getImplementation(class_getInstanceMethod(superClass, @selector(resume))); + if (classResumeIMP != superclassResumeIMP && + originalAFResumeIMP != classResumeIMP) { + [self swizzleResumeAndSuspendMethodForClass:currentClass]; + } + currentClass = [currentClass superclass]; + } + + [localDataTask cancel]; + [session finishTasksAndInvalidate]; + } +} + ++ (void)swizzleResumeAndSuspendMethodForClass:(Class)theClass { + Method afResumeMethod = class_getInstanceMethod(self, @selector(af_resume)); + Method afSuspendMethod = class_getInstanceMethod(self, @selector(af_suspend)); + + if (af_addMethod(theClass, @selector(af_resume), afResumeMethod)) { + af_swizzleSelector(theClass, @selector(resume), @selector(af_resume)); + } + + if (af_addMethod(theClass, @selector(af_suspend), afSuspendMethod)) { + af_swizzleSelector(theClass, @selector(suspend), @selector(af_suspend)); + } +} + +- (NSURLSessionTaskState)state { + NSAssert(NO, @"State method should never be called in the actual dummy class"); + return NSURLSessionTaskStateCanceling; +} + +- (void)af_resume { + NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state"); + NSURLSessionTaskState state = [self state]; + [self af_resume]; + + if (state != NSURLSessionTaskStateRunning) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidResumeNotification object:self]; + } +} + +- (void)af_suspend { + NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state"); + NSURLSessionTaskState state = [self state]; + [self af_suspend]; + + if (state != NSURLSessionTaskStateSuspended) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidSuspendNotification object:self]; + } +} +@end + +#pragma mark - + +@interface AFURLSessionManager () +@property (readwrite, nonatomic, strong) NSURLSessionConfiguration *sessionConfiguration; +@property (readwrite, nonatomic, strong) NSOperationQueue *operationQueue; +@property (readwrite, nonatomic, strong) NSURLSession *session; +@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableTaskDelegatesKeyedByTaskIdentifier; +@property (readonly, nonatomic, copy) NSString *taskDescriptionForSessionTasks; +@property (readwrite, nonatomic, strong) NSLock *lock; +@property (readwrite, nonatomic, copy) AFURLSessionDidBecomeInvalidBlock sessionDidBecomeInvalid; +@property (readwrite, nonatomic, copy) AFURLSessionDidReceiveAuthenticationChallengeBlock sessionDidReceiveAuthenticationChallenge; +@property (readwrite, nonatomic, copy) AFURLSessionDidFinishEventsForBackgroundURLSessionBlock didFinishEventsForBackgroundURLSession; +@property (readwrite, nonatomic, copy) AFURLSessionTaskWillPerformHTTPRedirectionBlock taskWillPerformHTTPRedirection; +@property (readwrite, nonatomic, copy) AFURLSessionTaskDidReceiveAuthenticationChallengeBlock taskDidReceiveAuthenticationChallenge; +@property (readwrite, nonatomic, copy) AFURLSessionTaskNeedNewBodyStreamBlock taskNeedNewBodyStream; +@property (readwrite, nonatomic, copy) AFURLSessionTaskDidSendBodyDataBlock taskDidSendBodyData; +@property (readwrite, nonatomic, copy) AFURLSessionTaskDidCompleteBlock taskDidComplete; +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveResponseBlock dataTaskDidReceiveResponse; +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidBecomeDownloadTaskBlock dataTaskDidBecomeDownloadTask; +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveDataBlock dataTaskDidReceiveData; +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskWillCacheResponseBlock dataTaskWillCacheResponse; +@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading; +@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidWriteDataBlock downloadTaskDidWriteData; +@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidResumeBlock downloadTaskDidResume; +@end + +@implementation AFURLSessionManager + +- (instancetype)init { + return [self initWithSessionConfiguration:nil]; +} + +- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration { + self = [super init]; + if (!self) { + return nil; + } + + if (!configuration) { + configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; + } + + self.sessionConfiguration = configuration; + + self.operationQueue = [[NSOperationQueue alloc] init]; + self.operationQueue.maxConcurrentOperationCount = 1; + + self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue]; + + self.responseSerializer = [AFJSONResponseSerializer serializer]; + + self.securityPolicy = [AFSecurityPolicy defaultPolicy]; + +#if !TARGET_OS_WATCH + self.reachabilityManager = [AFNetworkReachabilityManager sharedManager]; +#endif + + self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init]; + + self.lock = [[NSLock alloc] init]; + self.lock.name = AFURLSessionManagerLockName; + + [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { + for (NSURLSessionDataTask *task in dataTasks) { + [self addDelegateForDataTask:task uploadProgress:nil downloadProgress:nil completionHandler:nil]; + } + + for (NSURLSessionUploadTask *uploadTask in uploadTasks) { + [self addDelegateForUploadTask:uploadTask progress:nil completionHandler:nil]; + } + + for (NSURLSessionDownloadTask *downloadTask in downloadTasks) { + [self addDelegateForDownloadTask:downloadTask progress:nil destination:nil completionHandler:nil]; + } + }]; + + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +#pragma mark - + +- (NSString *)taskDescriptionForSessionTasks { + return [NSString stringWithFormat:@"%p", self]; +} + +- (void)taskDidResume:(NSNotification *)notification { + NSURLSessionTask *task = notification.object; + if ([task respondsToSelector:@selector(taskDescription)]) { + if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) { + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidResumeNotification object:task]; + }); + } + } +} + +- (void)taskDidSuspend:(NSNotification *)notification { + NSURLSessionTask *task = notification.object; + if ([task respondsToSelector:@selector(taskDescription)]) { + if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) { + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidSuspendNotification object:task]; + }); + } + } +} + +#pragma mark - + +- (AFURLSessionManagerTaskDelegate *)delegateForTask:(NSURLSessionTask *)task { + NSParameterAssert(task); + + AFURLSessionManagerTaskDelegate *delegate = nil; + [self.lock lock]; + delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)]; + [self.lock unlock]; + + return delegate; +} + +- (void)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate + forTask:(NSURLSessionTask *)task +{ + NSParameterAssert(task); + NSParameterAssert(delegate); + + [self.lock lock]; + self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate; + [delegate setupProgressForTask:task]; + [self addNotificationObserverForTask:task]; + [self.lock unlock]; +} + +- (void)addDelegateForDataTask:(NSURLSessionDataTask *)dataTask + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init]; + delegate.manager = self; + delegate.completionHandler = completionHandler; + + dataTask.taskDescription = self.taskDescriptionForSessionTasks; + [self setDelegate:delegate forTask:dataTask]; + + delegate.uploadProgressBlock = uploadProgressBlock; + delegate.downloadProgressBlock = downloadProgressBlock; +} + +- (void)addDelegateForUploadTask:(NSURLSessionUploadTask *)uploadTask + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init]; + delegate.manager = self; + delegate.completionHandler = completionHandler; + + uploadTask.taskDescription = self.taskDescriptionForSessionTasks; + + [self setDelegate:delegate forTask:uploadTask]; + + delegate.uploadProgressBlock = uploadProgressBlock; +} + +- (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask + progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock + destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler +{ + AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init]; + delegate.manager = self; + delegate.completionHandler = completionHandler; + + if (destination) { + delegate.downloadTaskDidFinishDownloading = ^NSURL * (NSURLSession * __unused session, NSURLSessionDownloadTask *task, NSURL *location) { + return destination(location, task.response); + }; + } + + downloadTask.taskDescription = self.taskDescriptionForSessionTasks; + + [self setDelegate:delegate forTask:downloadTask]; + + delegate.downloadProgressBlock = downloadProgressBlock; +} + +- (void)removeDelegateForTask:(NSURLSessionTask *)task { + NSParameterAssert(task); + + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; + [self.lock lock]; + [delegate cleanUpProgressForTask:task]; + [self removeNotificationObserverForTask:task]; + [self.mutableTaskDelegatesKeyedByTaskIdentifier removeObjectForKey:@(task.taskIdentifier)]; + [self.lock unlock]; +} + +#pragma mark - + +- (NSArray *)tasksForKeyPath:(NSString *)keyPath { + __block NSArray *tasks = nil; + dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); + [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { + if ([keyPath isEqualToString:NSStringFromSelector(@selector(dataTasks))]) { + tasks = dataTasks; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(uploadTasks))]) { + tasks = uploadTasks; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(downloadTasks))]) { + tasks = downloadTasks; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(tasks))]) { + tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"]; + } + + dispatch_semaphore_signal(semaphore); + }]; + + dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); + + return tasks; +} + +- (NSArray *)tasks { + return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; +} + +- (NSArray *)dataTasks { + return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; +} + +- (NSArray *)uploadTasks { + return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; +} + +- (NSArray *)downloadTasks { + return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; +} + +#pragma mark - + +- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks { + dispatch_async(dispatch_get_main_queue(), ^{ + if (cancelPendingTasks) { + [self.session invalidateAndCancel]; + } else { + [self.session finishTasksAndInvalidate]; + } + }); +} + +#pragma mark - + +- (void)setResponseSerializer:(id )responseSerializer { + NSParameterAssert(responseSerializer); + + _responseSerializer = responseSerializer; +} + +#pragma mark - +- (void)addNotificationObserverForTask:(NSURLSessionTask *)task { + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidResume:) name:AFNSURLSessionTaskDidResumeNotification object:task]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidSuspend:) name:AFNSURLSessionTaskDidSuspendNotification object:task]; +} + +- (void)removeNotificationObserverForTask:(NSURLSessionTask *)task { + [[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidSuspendNotification object:task]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidResumeNotification object:task]; +} + +#pragma mark - + +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + return [self dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:completionHandler]; +} + +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler { + + __block NSURLSessionDataTask *dataTask = nil; + url_session_manager_create_task_safely(^{ + dataTask = [self.session dataTaskWithRequest:request]; + }); + + [self addDelegateForDataTask:dataTask uploadProgress:uploadProgressBlock downloadProgress:downloadProgressBlock completionHandler:completionHandler]; + + return dataTask; +} + +#pragma mark - + +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromFile:(NSURL *)fileURL + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + __block NSURLSessionUploadTask *uploadTask = nil; + url_session_manager_create_task_safely(^{ + uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL]; + }); + + if (!uploadTask && self.attemptsToRecreateUploadTasksForBackgroundSessions && self.session.configuration.identifier) { + for (NSUInteger attempts = 0; !uploadTask && attempts < AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask; attempts++) { + uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL]; + } + } + + [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler]; + + return uploadTask; +} + +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromData:(NSData *)bodyData + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + __block NSURLSessionUploadTask *uploadTask = nil; + url_session_manager_create_task_safely(^{ + uploadTask = [self.session uploadTaskWithRequest:request fromData:bodyData]; + }); + + [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler]; + + return uploadTask; +} + +- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + __block NSURLSessionUploadTask *uploadTask = nil; + url_session_manager_create_task_safely(^{ + uploadTask = [self.session uploadTaskWithStreamedRequest:request]; + }); + + [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler]; + + return uploadTask; +} + +#pragma mark - + +- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request + progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock + destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler +{ + __block NSURLSessionDownloadTask *downloadTask = nil; + url_session_manager_create_task_safely(^{ + downloadTask = [self.session downloadTaskWithRequest:request]; + }); + + [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler]; + + return downloadTask; +} + +- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData + progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock + destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler +{ + __block NSURLSessionDownloadTask *downloadTask = nil; + url_session_manager_create_task_safely(^{ + downloadTask = [self.session downloadTaskWithResumeData:resumeData]; + }); + + [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler]; + + return downloadTask; +} + +#pragma mark - +- (NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task { + return [[self delegateForTask:task] uploadProgress]; +} + +- (NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task { + return [[self delegateForTask:task] downloadProgress]; +} + +#pragma mark - + +- (void)setSessionDidBecomeInvalidBlock:(void (^)(NSURLSession *session, NSError *error))block { + self.sessionDidBecomeInvalid = block; +} + +- (void)setSessionDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block { + self.sessionDidReceiveAuthenticationChallenge = block; +} + +- (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession *session))block { + self.didFinishEventsForBackgroundURLSession = block; +} + +#pragma mark - + +- (void)setTaskNeedNewBodyStreamBlock:(NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block { + self.taskNeedNewBodyStream = block; +} + +- (void)setTaskWillPerformHTTPRedirectionBlock:(NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block { + self.taskWillPerformHTTPRedirection = block; +} + +- (void)setTaskDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block { + self.taskDidReceiveAuthenticationChallenge = block; +} + +- (void)setTaskDidSendBodyDataBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block { + self.taskDidSendBodyData = block; +} + +- (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block { + self.taskDidComplete = block; +} + +#pragma mark - + +- (void)setDataTaskDidReceiveResponseBlock:(NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block { + self.dataTaskDidReceiveResponse = block; +} + +- (void)setDataTaskDidBecomeDownloadTaskBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block { + self.dataTaskDidBecomeDownloadTask = block; +} + +- (void)setDataTaskDidReceiveDataBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block { + self.dataTaskDidReceiveData = block; +} + +- (void)setDataTaskWillCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block { + self.dataTaskWillCacheResponse = block; +} + +#pragma mark - + +- (void)setDownloadTaskDidFinishDownloadingBlock:(NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block { + self.downloadTaskDidFinishDownloading = block; +} + +- (void)setDownloadTaskDidWriteDataBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block { + self.downloadTaskDidWriteData = block; +} + +- (void)setDownloadTaskDidResumeBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block { + self.downloadTaskDidResume = block; +} + +#pragma mark - NSObject + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, self.session, self.operationQueue]; +} + +- (BOOL)respondsToSelector:(SEL)selector { + if (selector == @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)) { + return self.taskWillPerformHTTPRedirection != nil; + } else if (selector == @selector(URLSession:dataTask:didReceiveResponse:completionHandler:)) { + return self.dataTaskDidReceiveResponse != nil; + } else if (selector == @selector(URLSession:dataTask:willCacheResponse:completionHandler:)) { + return self.dataTaskWillCacheResponse != nil; + } else if (selector == @selector(URLSessionDidFinishEventsForBackgroundURLSession:)) { + return self.didFinishEventsForBackgroundURLSession != nil; + } + + return [[self class] instancesRespondToSelector:selector]; +} + +#pragma mark - NSURLSessionDelegate + +- (void)URLSession:(NSURLSession *)session +didBecomeInvalidWithError:(NSError *)error +{ + if (self.sessionDidBecomeInvalid) { + self.sessionDidBecomeInvalid(session, error); + } + + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDidInvalidateNotification object:session]; +} + +- (void)URLSession:(NSURLSession *)session +didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler +{ + NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; + __block NSURLCredential *credential = nil; + + if (self.sessionDidReceiveAuthenticationChallenge) { + disposition = self.sessionDidReceiveAuthenticationChallenge(session, challenge, &credential); + } else { + if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { + if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { + credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; + if (credential) { + disposition = NSURLSessionAuthChallengeUseCredential; + } else { + disposition = NSURLSessionAuthChallengePerformDefaultHandling; + } + } else { + disposition = NSURLSessionAuthChallengeRejectProtectionSpace; + } + } else { + disposition = NSURLSessionAuthChallengePerformDefaultHandling; + } + } + + if (completionHandler) { + completionHandler(disposition, credential); + } +} + +#pragma mark - NSURLSessionTaskDelegate + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +willPerformHTTPRedirection:(NSHTTPURLResponse *)response + newRequest:(NSURLRequest *)request + completionHandler:(void (^)(NSURLRequest *))completionHandler +{ + NSURLRequest *redirectRequest = request; + + if (self.taskWillPerformHTTPRedirection) { + redirectRequest = self.taskWillPerformHTTPRedirection(session, task, response, request); + } + + if (completionHandler) { + completionHandler(redirectRequest); + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler +{ + NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; + __block NSURLCredential *credential = nil; + + if (self.taskDidReceiveAuthenticationChallenge) { + disposition = self.taskDidReceiveAuthenticationChallenge(session, task, challenge, &credential); + } else { + if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { + if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { + disposition = NSURLSessionAuthChallengeUseCredential; + credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; + } else { + disposition = NSURLSessionAuthChallengeRejectProtectionSpace; + } + } else { + disposition = NSURLSessionAuthChallengePerformDefaultHandling; + } + } + + if (completionHandler) { + completionHandler(disposition, credential); + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler +{ + NSInputStream *inputStream = nil; + + if (self.taskNeedNewBodyStream) { + inputStream = self.taskNeedNewBodyStream(session, task); + } else if (task.originalRequest.HTTPBodyStream && [task.originalRequest.HTTPBodyStream conformsToProtocol:@protocol(NSCopying)]) { + inputStream = [task.originalRequest.HTTPBodyStream copy]; + } + + if (completionHandler) { + completionHandler(inputStream); + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + didSendBodyData:(int64_t)bytesSent + totalBytesSent:(int64_t)totalBytesSent +totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend +{ + + int64_t totalUnitCount = totalBytesExpectedToSend; + if(totalUnitCount == NSURLSessionTransferSizeUnknown) { + NSString *contentLength = [task.originalRequest valueForHTTPHeaderField:@"Content-Length"]; + if(contentLength) { + totalUnitCount = (int64_t) [contentLength longLongValue]; + } + } + + if (self.taskDidSendBodyData) { + self.taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalUnitCount); + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +didCompleteWithError:(NSError *)error +{ + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; + + // delegate may be nil when completing a task in the background + if (delegate) { + [delegate URLSession:session task:task didCompleteWithError:error]; + + [self removeDelegateForTask:task]; + } + + if (self.taskDidComplete) { + self.taskDidComplete(session, task, error); + } +} + +#pragma mark - NSURLSessionDataDelegate + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didReceiveResponse:(NSURLResponse *)response + completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler +{ + NSURLSessionResponseDisposition disposition = NSURLSessionResponseAllow; + + if (self.dataTaskDidReceiveResponse) { + disposition = self.dataTaskDidReceiveResponse(session, dataTask, response); + } + + if (completionHandler) { + completionHandler(disposition); + } +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask +{ + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask]; + if (delegate) { + [self removeDelegateForTask:dataTask]; + [self setDelegate:delegate forTask:downloadTask]; + } + + if (self.dataTaskDidBecomeDownloadTask) { + self.dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask); + } +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + didReceiveData:(NSData *)data +{ + + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask]; + [delegate URLSession:session dataTask:dataTask didReceiveData:data]; + + if (self.dataTaskDidReceiveData) { + self.dataTaskDidReceiveData(session, dataTask, data); + } +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + willCacheResponse:(NSCachedURLResponse *)proposedResponse + completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler +{ + NSCachedURLResponse *cachedResponse = proposedResponse; + + if (self.dataTaskWillCacheResponse) { + cachedResponse = self.dataTaskWillCacheResponse(session, dataTask, proposedResponse); + } + + if (completionHandler) { + completionHandler(cachedResponse); + } +} + +- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session { + if (self.didFinishEventsForBackgroundURLSession) { + dispatch_async(dispatch_get_main_queue(), ^{ + self.didFinishEventsForBackgroundURLSession(session); + }); + } +} + +#pragma mark - NSURLSessionDownloadDelegate + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask +didFinishDownloadingToURL:(NSURL *)location +{ + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; + if (self.downloadTaskDidFinishDownloading) { + NSURL *fileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location); + if (fileURL) { + delegate.downloadFileURL = fileURL; + NSError *error = nil; + [[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error]; + if (error) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo]; + } + + return; + } + } + + if (delegate) { + [delegate URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location]; + } +} + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask + didWriteData:(int64_t)bytesWritten + totalBytesWritten:(int64_t)totalBytesWritten +totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite +{ + if (self.downloadTaskDidWriteData) { + self.downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); + } +} + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask + didResumeAtOffset:(int64_t)fileOffset +expectedTotalBytes:(int64_t)expectedTotalBytes +{ + if (self.downloadTaskDidResume) { + self.downloadTaskDidResume(session, downloadTask, fileOffset, expectedTotalBytes); + } +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; + + self = [self initWithSessionConfiguration:configuration]; + if (!self) { + return nil; + } + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[[self class] allocWithZone:zone] initWithSessionConfiguration:self.session.configuration]; +} + +@end diff --git a/its/plugin/projects/AFNetworking/CHANGELOG.md b/its/plugin/projects/AFNetworking/CHANGELOG.md new file mode 100644 index 00000000..82dc3d02 --- /dev/null +++ b/its/plugin/projects/AFNetworking/CHANGELOG.md @@ -0,0 +1,1996 @@ +#Change Log +All notable changes to this project will be documented in this file. +`AFNetworking` adheres to [Semantic Versioning](http://semver.org/). + +--- + +## [3.0.4](https://github.com/AFNetworking/AFNetworking/releases/tag/3.0.4) (12/18/2015) +Released on Friday, December 18, 2015. All issues associated with this milestone can be found using this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A3.0.4+is%3Aclosed). + +#### Fixed +* Fixed issue where `AFNSURLSessionTaskDidResumeNotification` was removed twice + * Implemented by Kevin Harwood in [#3236](https://github.com/AFNetworking/AFNetworking/pull/3236). + + +## [3.0.3](https://github.com/AFNetworking/AFNetworking/releases/tag/3.0.3) (12/16/2015) +Released on Wednesday, December 16, 2015. All issues associated with this milestone can be found using this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A3.0.3+is%3Aclosed). + +#### Added +* Added tests for response serializers to increase test coverage + * Implemented by Kevin Harwood in [#3233](https://github.com/AFNetworking/AFNetworking/pull/3233). + +#### Fixed +* Fixed `AFImageResponseSerializer` serialization macros on watchOS and tvOS + * Implemented by Charles Joseph in [#3229](https://github.com/AFNetworking/AFNetworking/pull/3229). + + +## [3.0.2](https://github.com/AFNetworking/AFNetworking/releases/tag/3.0.2) (12/14/2015) +Released on Monday, December 14, 2015. All issues associated with this milestone can be found using this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A3.0.2+is%3Aclosed). + +#### Fixed +* Fixed a crash in `AFURLSessionManager` when resuming download tasks + * Implemented by Chongyu Zhu in [#3222](https://github.com/AFNetworking/AFNetworking/pull/3222). +* Fixed issue where background button image would not be updated + * Implemented by eofs in [#3220](https://github.com/AFNetworking/AFNetworking/pull/3220). + + +## [3.0.1](https://github.com/AFNetworking/AFNetworking/releases/tag/3.0.1) (12/11/2015) +Released on Friday, December 11, 2015. All issues associated with this milestone can be found using this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A3.0.1+is%3Aclosed). + +#### Added +* Added Xcode 7.2 support to Travis + * Implemented by Kevin Harwood in [#3216](https://github.com/AFNetworking/AFNetworking/pull/3216). + +#### Fixed +* Fixed race condition with ImageView/Button image downloading when starting/cancelling/starting the same request + * Implemented by Kevin Harwood in [#3215](https://github.com/AFNetworking/AFNetworking/pull/3215). + + +## [3.0.0](https://github.com/AFNetworking/AFNetworking/releases/tag/3.0.0) (12/10/2015) +Released on Thursday, December 10, 2015. All issues associated with this milestone can be found using this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A3.0.0+is%3Aclosed). + +For detailed information about migrating to AFNetworking 3.0.0, please reference the [migration guide](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-3.0-Migration-Guide). All 3.0.0 beta changes will be tracked with this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A3.0.0+is%3Aclosed). + +#### Added +* Added support for older versions of Xcode to Travis + * Implemented by Kevin Harwood in [#3209](https://github.com/AFNetworking/AFNetworking/pull/3209). +* Added support for [Codecov.io](https://codecov.io/github/AFNetworking/AFNetworking/AFNetworking?branch=master#sort=coverage&dir=desc) + * Implemented by Cédric Luthi and Kevin Harwood in [#3196](https://github.com/AFNetworking/AFNetworking/pull/3196). + * * **Please help us increase overall coverage by submitting a pull request!** +* Added support for IPv6 to Reachability + * Implemented by SAMUKEI and Kevin Harwood in [#3174](https://github.com/AFNetworking/AFNetworking/pull/3174). +* Added support for Objective-C light weight generics + * Implemented by Kevin Harwood in [#3166](https://github.com/AFNetworking/AFNetworking/pull/3166). +* Added nullability attributes to response object in success block + * Implemented by Nathan Racklyeft in [#3154](https://github.com/AFNetworking/AFNetworking/pull/3154). +* Migrated to Fastlane for CI and Deployment + * Implemented by Kevin Harwood in [#3148](https://github.com/AFNetworking/AFNetworking/pull/3148). +* Added support for tvOS + * Implemented by Kevin Harwood in [#3128](https://github.com/AFNetworking/AFNetworking/issues/3128). +* New image downloading architecture + * Implemented by Kevin Harwood in [#3122](https://github.com/AFNetworking/AFNetworking/issues/3122). +* Added Carthage Support + * Implemented by Kevin Harwood in [#3121](https://github.com/AFNetworking/AFNetworking/issues/3121). +* Added a method to create a unique reachability manager + * Implemented by Mo Bitar in [#3111](https://github.com/AFNetworking/AFNetworking/pull/3111). +* Added a initial delay to the network indicator per the Apple HIG + * Implemented by Kevin Harwood in [#3094](https://github.com/AFNetworking/AFNetworking/pull/3094). + +#### Updated +* Improved testing reliability for continuous integration + * Implemented by Kevin Harwood in [#3124](https://github.com/AFNetworking/AFNetworking/pull/3124). +* Example project now consumes AFNetworking as a library. + * Implemented by Kevin Harwood in [#3068](https://github.com/AFNetworking/AFNetworking/pull/3068). +* Migrated to using `instancetype` where applicable + * Implemented by Kyle Fuller in [#3064](https://github.com/AFNetworking/AFNetworking/pull/3064). +* Tweaks to project to support Framework Project + * Implemented by Christian Noon in [#3062](https://github.com/AFNetworking/AFNetworking/pull/3062). + +#### Changed +* Split the iOS and OS X AppDelegate classes in the Example Project + * Implemented by Cédric Luthi in [#3193](https://github.com/AFNetworking/AFNetworking/pull/3193). +* Changed SSL Pinning Error to be `NSURLErrorServerCertificateUntrusted` + * Implemented by Cédric Luthi and Kevin Harwood in [#3191](https://github.com/AFNetworking/AFNetworking/pull/3191). +* New Progress Reporting API using `NSProgress` + * Implemented by Kevin Harwood in [#3187](https://github.com/AFNetworking/AFNetworking/pull/3187). +* Changed `pinnedCertificates` type in `AFSecurityPolicy` from `NSArray` to `NSSet` + * Implemented by Cédric Luthi in [#3164](https://github.com/AFNetworking/AFNetworking/pull/3164). + +#### Fixed +* Improved task creation performance for iOS 8+ + * Implemented by nikitahils, Nikita G and Kevin Harwood in [#3208](https://github.com/AFNetworking/AFNetworking/pull/3208). +* Fixed certificate validation for servers providing incomplete chains + * Implemented by André Pacheco Neves in [#3159](https://github.com/AFNetworking/AFNetworking/pull/3159). +* Fixed bug in `AFMultipartBodyStream` that may cause the input stream to read more bytes than required. + * Implemented by bang in [#3153](https://github.com/AFNetworking/AFNetworking/pull/3153). +* Fixed race condition crash from Resume/Suspend task notifications + * Implemented by Kevin Harwood in [#3152](https://github.com/AFNetworking/AFNetworking/pull/3152). +* Fixed `AFImageDownloader` stalling after numerous failures + * Implemented by Rick Silva in [#3150](https://github.com/AFNetworking/AFNetworking/pull/3150). +* Fixed warnings generated in UIWebView category + * Implemented by Kevin Harwood in [#3126](https://github.com/AFNetworking/AFNetworking/pull/3126). + +#### Removed +* Removed AFBase64EncodedStringFromString static function + * Implemented by Cédric Luthi in [#3188](https://github.com/AFNetworking/AFNetworking/pull/3188). +* Removed code supporting conditional compilation for unsupported development configurations. + * Implemented by Cédric Luthi in [#3177](https://github.com/AFNetworking/AFNetworking/pull/3177). +* Removed deprecated methods, properties, and notifications from AFN 2.x + * Implemented by Kevin Harwood in [#3168](https://github.com/AFNetworking/AFNetworking/pull/3168). +* Removed support for `NSURLConnection` + * Implemented by Kevin Harwood in [#3120](https://github.com/AFNetworking/AFNetworking/issues/3120). +* Removed `UIAlertView` category support since it is now deprecated + * Implemented by Kevin Harwood in [#3034](https://github.com/AFNetworking/AFNetworking/pull/3034). + + +##[2.6.3](https://github.com/AFNetworking/AFNetworking/releases/tag/2.6.3) (11/11/2015) +Released on Wednesday, November 11, 2015. All issues associated with this milestone can be found using this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A2.6.3+is%3Aclosed). + +#### Fixed +* Fixed clang analyzer warning suppression that prevented building under some project configurations + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#3142](https://github.com/AFNetworking/AFNetworking/pull/3142). +* Restored Xcode 6 compatibility + * Fixed by [jcayzac](https://github.com/jcayzac) in [#3139](https://github.com/AFNetworking/AFNetworking/pull/3139). + + +##[2.6.2](https://github.com/AFNetworking/AFNetworking/releases/tag/2.6.2) (11/06/2015) +Released on Friday, November 06, 2015. All issues associated with this milestone can be found using this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A2.6.2+is%3Aclosed). + +### Important Upgrade Note for Swift +* [#3130](https://github.com/AFNetworking/AFNetworking/pull/3130) fixes a swift interop error that does have a breaking API change if you are using Swift. This was [identified](https://github.com/AFNetworking/AFNetworking/issues/3137) after 2.6.2 was released. It changes the method from `throws` to an error pointer, since that method does return an object and also handles an error pointer, which does not play nicely with the Swift/Objective-C error conversion. See [#2810](https://github.com/AFNetworking/AFNetworking/issues/2810) for additional notes. This affects `AFURLRequestionSerializer` and `AFURLResponseSerializer`. + +#### Added +* `AFHTTPSessionManager` now copies its `securityPolicy` + * Fixed by [mohamede1945](https://github.com/mohamede1945) in [#2887](https://github.com/AFNetworking/AFNetworking/pull/2887). + +#### Updated +* Updated travis to run on 7.1 + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#3132](https://github.com/AFNetworking/AFNetworking/pull/3132). +* Simplifications of if and return statements in `AFSecurityPolicy` + * Fixed by [TorreyBetts](https://github.com/TorreyBetts) in [#3063](https://github.com/AFNetworking/AFNetworking/pull/3063). + +#### Fixed +* Fixed swift interop issue that prevented returning a nil NSURL for a download task + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#3133](https://github.com/AFNetworking/AFNetworking/pull/3133). +* Suppressed false positive memory leak warning in Reachability Manager + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#3131](https://github.com/AFNetworking/AFNetworking/pull/3131). +* Fixed swift interop issue with throws and Request/Response serialization. + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#3130](https://github.com/AFNetworking/AFNetworking/pull/3130). +* Fixed race condition in reachability callback delivery + * Fixed by [MichaelHackett](https://github.com/MichaelHackett) in [#3117](https://github.com/AFNetworking/AFNetworking/pull/3117). +* Fixed URLs that were redirecting in the README + * Fixed by [frankenbot](https://github.com/frankenbot) in [#3109](https://github.com/AFNetworking/AFNetworking/pull/3109). +* Fixed Project Warnings + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#3102](https://github.com/AFNetworking/AFNetworking/pull/3102). +* Fixed README link to WWDC session + * Fixed by [wrtsprt](https://github.com/wrtsprt) in [#3099](https://github.com/AFNetworking/AFNetworking/pull/3099). +* Switched from `OS_OBJECT_HAVE_OBJC_SUPPORT` to `OS_OBJECT_USE_OBJC` for watchOS 2 support. + * Fixed by [kylef](https://github.com/kylef) in [#3065](https://github.com/AFNetworking/AFNetworking/pull/3065). +* Added missing __nullable attributes to failure blocks in `AFHTTPRequestOperationManager` and `AFHTTPSessionManager` + * Fixed by [hoppenichu](https://github.com/hoppenichu) in [#3057](https://github.com/AFNetworking/AFNetworking/pull/3057). +* Fixed memory leak in NSURLSession handling + * Fixed by [olegnaumenko](https://github.com/olegnaumenko) in [#2794](https://github.com/AFNetworking/AFNetworking/pull/2794). + + +## [2.6.1](https://github.com/AFNetworking/AFNetworking/releases/tag/2.6.1) (10-13-2015) +Released on Tuesday, October 13th, 2015. All issues associated with this milestone can be found using this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A2.6.1+is%3Aclosed). + +###Future Compatibility Note +Note that AFNetworking 3.0 will soon be released, and will drop support for all `NSURLConnection` based API's (`AFHTTPRequestOperationManager`, `AFHTTPRequestOperation`, and `AFURLConnectionOperation`. If you have not already migrated to `NSURLSession` based API's, please do so soon. For more information, please see the [3.0 migration guide](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-3.0-Migration-Guide). + +####Fixed +* Fixed a bug that prevented empty x-www-form-urlencoded bodies. + * Fixed by [Julien Cayzac](https://github.com/jcayzac) in [#2868](https://github.com/AFNetworking/AFNetworking/pull/2868). +* Fixed bug that prevented AFNetworking from being installed for watchOS via Cocoapods. + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2909](https://github.com/AFNetworking/AFNetworking/issues/2909). +* Added missing nullable attributes to `AFURLRequestSerialization` and `AFURLSessionManager`. + * Fixed by [andrewtoth](https://github.com/andrewtoth) in [#2911](https://github.com/AFNetworking/AFNetworking/pull/2911). +* Migrated to `OS_OBJECT_USE_OBJC`. + * Fixed by [canius](https://github.com/canius) in [#2930](https://github.com/AFNetworking/AFNetworking/pull/2930). +* Added missing nullable tags to UIKit extensions. + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#3000](https://github.com/AFNetworking/AFNetworking/pull/3000). +* Fixed potential infinite recursion loop if multiple versions of AFNetworking are loaded in a target. + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2743](https://github.com/AFNetworking/AFNetworking/issues/2743). +* Updated Travis CI test script + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#3032](https://github.com/AFNetworking/AFNetworking/issues/3032). +* Migrated to `FOUNDATION_EXPORT` from `extern`. + * Fixed by [Andrey Mikhaylov](https://github.com/pronebird) in [#3041](https://github.com/AFNetworking/AFNetworking/pull/3041). +* Fixed issue where `AFURLConnectionOperation` could get stuck in an infinite loop. + * Fixed by [Mattt Thompson](https://github.com/mattt) in [#2496](https://github.com/AFNetworking/AFNetworking/pull/2496). +* Fixed regression where URL request serialization would crash on iOS 8 for long URLs. + * Fixed by [softenhard](https://github.com/softenhard) in [#3028](https://github.com/AFNetworking/AFNetworking/pull/3028). + +## [2.6.0](https://github.com/AFNetworking/AFNetworking/releases/tag/2.6.0) (08-19-2015) +Released on Wednesday, August 19th, 2015. All issues associated with this milestone can be found using this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A2.6.0+is%3Aclosed). + +###Important Upgrade Notes +Please note the following API/project changes have been made: + +* iOS 6 and OS X 10.8 support has been dropped from the project to facilitate support for watchOS 2. The final release supporting iOS 6 and OS X 10.8 is 2.5.4. +* **Full Certificate Chain Validation has been removed** from `AFSecurityPolicy`. As discussed in [#2744](https://github.com/AFNetworking/AFNetworking/issues/2744), there was no documented security advantage to pinning against an entire certificate chain. If you were using full certificate chain, please determine and select the most ideal certificate in your chain to pin against. + * Implemented by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2856](https://github.com/AFNetworking/AFNetworking/pull/2856). +* **The request url will now be returned by the `UIImageView` category if the image is returned from cache.** In previous releases, both the request and the response were nil. Going forward, only the response will be nil. + * Implemented by [Chris Gibbs](https://github.com/chrisgibbs) in [#2771](https://github.com/AFNetworking/AFNetworking/pull/2771). +* **Support for App Extension Targets is now baked in using `NS_EXTENSION_UNAVAILABLE_IOS`.** You no longer need to define `AF_APP_EXTENSIONS` in order to include code in a extension target. + * Implemented by [bnickel](https://github.com/bnickel) in [#2737](https://github.com/AFNetworking/AFNetworking/pull/2737). +* This release now supports watchOS 2.0, which relys on target conditionals that are only present in Xcode 7 and iOS 9/watchOS 2.0/OS X 10.10. If you install the library using CocoaPods, AFNetworking will define these target conditionals for on older platforms, allowing your code to compile. If you do not use Cocoapods, you will need to add the following code your to PCH file. + +``` +#ifndef TARGET_OS_IOS + #define TARGET_OS_IOS TARGET_OS_IPHONE +#endif +#ifndef TARGET_OS_WATCH + #define TARGET_OS_WATCH 0 +#endif +``` +* This release migrates query parameter serialization to model AlamoFire and adhere to RFC standards. Note that `/` and `?` are no longer encoded by default. + * Implemented by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2908](https://github.com/AFNetworking/AFNetworking/pull/2908). + + + +**Note** that support for `NSURLConnection` based API's will be removed in a future update. If you have not already done so, it is recommended that you transition to the `NSURLSession` APIs in the very near future. + +####Added +* Added watchOS 2.0 support. `AFNetworking` can now be added to watchOS targets using CocoaPods. + * Added by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2837](https://github.com/AFNetworking/AFNetworking/issues/2837). +* Added nullability annotations to all of the header files to improve Swift interoperability. + * Added by [Frank LSF](https://github.com/franklsf95) and [Kevin Harwood](https://github.com/Kevin Harwood) in [#2814](https://github.com/AFNetworking/AFNetworking/pull/2814). +* Converted source to Modern Objective-C Syntax. + * Implemented by [Matt Shedlick](https://github.com/mattshedlick) and [Kevin Harwood](https://github.com/Kevin Harwood) in [#2688](https://github.com/AFNetworking/AFNetworking/pull/2688). +* Improved memory performance when download large objects. + * Fixed by [Gabe Zabrino](https://github.com/gfzabarino) and [Kevin Harwood](https://github.com/Kevin Harwood) in [#2672](https://github.com/AFNetworking/AFNetworking/pull/2672). + +####Fixed +* Fixed a crash related for objects that observe notifications but don't properly unregister. + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) and [bnickle](https://github.com/bnickel) in [#2741](https://github.com/AFNetworking/AFNetworking/pull/2741). +* Fixed a race condition crash that occured with `AFImageResponseSerialization`. + * Fixed by [Paulo Ferreria](https://github.com/paulosotu) and [Kevin Harwood](https://github.com/Kevin Harwood) in [#2815](https://github.com/AFNetworking/AFNetworking/pull/2815). +* Fixed an issue where tests failed to run on CI due to unavailable simulators. + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2834](https://github.com/AFNetworking/AFNetworking/pull/2834). +* Fixed "method override not found" warnings in Xcode 7 Betas + * Fixed by [Ben Guo](https://github.com/benzguo) in [#2822](https://github.com/AFNetworking/AFNetworking/pull/2822) +* Removed Duplicate Import and UIKit Header file. + * Fixed by [diehardest](https://github.com/diehardest) in [#2813](https://github.com/AFNetworking/AFNetworking/pull/2813) +* Removed the ability to include duplicate certificates in the pinned certificate chain. + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2756](https://github.com/AFNetworking/AFNetworking/pull/2756). +* Fixed potential memory leak in `AFNetworkReachabilityManager`. + * Fixed by [Julien Cayzac](https://github.com/jcayzac) in [#2867](https://github.com/AFNetworking/AFNetworking/pull/2867). + +####Documentation Improvements +* Clarified best practices for Reachability per Apple recommendations. + * Fixed by [Steven Fisher](https://github.com/tewha) in [#2704](https://github.com/AFNetworking/AFNetworking/pull/2704). +* Added `startMonitoring` call to the Reachability section of the README + * Added by [Jawwad Ahmad](https://github.com/jawwad) in [#2831](https://github.com/AFNetworking/AFNetworking/pull/2831). +* Fixed documentation error around how `baseURL` is used for reachability monitoring. + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2761](https://github.com/AFNetworking/AFNetworking/pull/2761). +* Numerous spelling corrections in the documentation. + * Fixed by [Antoine Cœur](https://github.com/Coeur) in [#2732](https://github.com/AFNetworking/AFNetworking/pull/2732) and [#2898](https://github.com/AFNetworking/AFNetworking/pull/2898). + +## [2.5.4](https://github.com/AFNetworking/AFNetworking/releases/tag/2.5.4) (2015-05-14) +Released on 2015-05-14. All issues associated with this milestone can be found using this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A2.5.4+is%3Aclosed). + +####Updated +* Updated the CI test script to run iOS tests on all versions of iOS that are installed on the build machine. + * Updated by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2716](https://github.com/AFNetworking/AFNetworking/pull/2716). + +####Fixed + +* Fixed an issue where `AFNSURLSessionTaskDidResumeNotification` and `AFNSURLSessionTaskDidSuspendNotification` were not being properly called due to implementation differences in `NSURLSessionTask` in iOS 7 and iOS 8, which also affects the `AFNetworkActivityIndicatorManager`. + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2702](https://github.com/AFNetworking/AFNetworking/pull/2702). +* Fixed an issue where the OS X test linker would throw a warning during tests. + * Fixed by [Christian Noon](https://github.com/cnoon) in [#2719](https://github.com/AFNetworking/AFNetworking/pull/2719). +* Fixed an issue where tests would randomly fail due to mocked objects not being cleaned up. + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2717](https://github.com/AFNetworking/AFNetworking/pull/2717). + + +## [2.5.3](https://github.com/AFNetworking/AFNetworking/releases/tag/2.5.3) (2015-04-20) + +* Add security policy tests for default policy + +* Add network reachability tests + +* Change `validatesDomainName` property to default to `YES` under all * security policies + +* Fix `NSURLSession` subspec compatibility with iOS 6 / OS X 10.8 + +* Fix leak of data task used in `NSURLSession` swizzling + +* Fix leak for observers from `addObserver:...:withBlock:` + +* Fix issue with network reachability observation on domain name + +## [2.5.2](https://github.com/AFNetworking/AFNetworking/releases/tag/2.5.2) (2015-03-26) +**NOTE** This release contains a security vulnerabilty. **All users should upgrade to a 2.5.3 or greater**. Please reference this [statement](https://gist.github.com/AlamofireSoftwareFoundation/f784f18f949b95ab733a) if you have any further questions about this release. + +* Add guards for unsupported features in iOS 8 App Extensions + +* Add missing delegate callbacks to `UIWebView` category + +* Add test and implementation of strict default certificate validation + +* Add #define for `NS_DESIGNATED_INITIALIZER` for unsupported versions of Xcode + +* Fix `AFNetworkActivityIndicatorManager` for iOS 7 + +* Fix `AFURLRequestSerialization` property observation + +* Fix `testUploadTasksProgressBecomesPartOfCurrentProgress` + +* Fix warnings from Xcode 6.3 Beta + +* Fix `AFImageWithDataAtScale` handling of animated images + +* Remove `AFNetworkReachabilityAssociation` enumeration + +* Update to conditional use assign semantics for GCD properties based on `OS_OBJECT_HAVE_OBJC_SUPPORT` for better Swift support + +## [2.5.1](https://github.com/AFNetworking/AFNetworking/releases/tag/2.5.1) (2015-02-09) +**NOTE** This release contains a security vulnerabilty. **All users should upgrade to a 2.5.3 or greater**. Please reference this [statement](https://gist.github.com/AlamofireSoftwareFoundation/f784f18f949b95ab733a) if you have any further questions about this release. + + * Add `NS_DESIGNATED_INITIALIZER` macros. (Samir Guerdah) + + * Fix and clarify documentation for `stringEncoding` property. (Mattt +Thompson) + + * Fix for NSProgress bug where two child NSProgress instances are added to a +parent NSProgress. (Edward Povazan) + + * Fix incorrect file names in headers. (Steven Fisher) + + * Fix KVO issue when running testing target caused by lack of +`automaticallyNotifiesObserversForKey:` implementation. (Mattt Thompson) + + * Fix use of variable arguments for UIAlertView category. (Kenta Tokumoto) + + * Fix `genstrings` warning for `NSLocalizedString` usage in +`UIAlertView+AFNetworking`. (Adar Porat) + + * Fix `NSURLSessionManager` task observation for network activity indicator +manager. (Phil Tang) + + * Fix `UIButton` category method caching of background image (Fernanda G. +Geraissate) + + * Fix `UIButton` category method failure handling. (Maxim Zabelin) + + * Update multipart upload method requirements to ensure `request.HTTPBody` +is non-nil. (Mattt Thompson) + + * Update to use builtin `__Require` macros from AssertMacros.h. (Cédric +Luthi) + + * Update `parameters` parameter to accept `id` for custom serialization +block. (@mooosu) + +## [2.5.0](https://github.com/AFNetworking/AFNetworking/releases/tag/2.5.0) (2014-11-17) + + * Add documentation for expected background session manager usage (Aaron +Brager) + + * Add missing documentation for `AFJSONRequestSerializer` and +`AFPropertyListSerializer` (Mattt Thompson) + + * Add tests for requesting HTTPS endpoints (Mattt Thompson) + + * Add `init` method declarations of `AFURLResponseSerialization` classes for +Swift compatibility (Allen Rohner) + + * Change default User-Agent to use the version number instead of the build +number (Tim Watson) + + * Change `validatesDomainName` to readonly property (Mattt Thompson, Brian +King) + + * Fix checks when observing `AFHTTPRequestSerializerObservedKeyPaths` (Jacek +Suliga) + + * Fix crash caused by attempting to set nil `NSURLResponse -URL` as key for +`userInfo` dictionary (Elvis Nuñez) + + * Fix crash for multipart streaming requests in XPC services (Mattt Thompson) + + * Fix minor aspects of response serializer documentation (Mattt Thompson) + + * Fix potential race condition for `AFURLConnectionOperation -description` + + * Fix widespread crash related to key-value observing of `NSURLSessionTask +-state` (Phil Tang) + + * Fix `UIButton` category associated object keys (Kristian Bauer, Mattt +Thompson) + + * Remove `charset` parameter from Content-Type HTTP header field values for +`AFJSONRequestSerializer` and `AFPropertyListSerializer` (Mattt Thompson) + + * Update CocoaDocs color scheme (@Orta) + + * Update Podfile to explicitly define sources (Kyle Fuller) + + * Update to relay `downloadFileURL` to the delegate if the manager picks a +`fileURL` (Brian King) + + * Update `AFSSLPinningModeNone` to not validate domain name (Brian King) + + * Update `UIButton` category to cache images in `sharedImageCache` (John +Bushnell) + + * Update `UIRefreshControl` category to set control state to current state +of request (Elvis Nuñez) + +## [2.4.1](https://github.com/AFNetworking/AFNetworking/releases/tag/2.4.1) (2014-09-04) + + * Fix compiler warning generated on 32-bit architectures (John C. Daub) + + * Fix potential crash caused by failed validation with nil responseData + (Mattt Thompson) + + * Fix to suppress compiler warnings for out-of-range enumerated type + value assignment (Mattt Thompson) + +## [2.4.0](https://github.com/AFNetworking/AFNetworking/releases/tag/2.4.0) (2014-09-03) + + * Add CocoaDocs color scheme (Orta) + + * Add image cache to `UIButton` category (Kristian Bauer, Mattt Thompson) + + * Add test for success block on 204 response (Mattt Thompson) + + * Add tests for encodable and re-encodable query string parameters (Mattt +Thompson) + + * Add `AFHTTPRequestSerializer -valueForHTTPHeaderField:` (Kyle Fuller) + + * Add `AFNetworkingOperationFailingURLResponseDataErrorKey` key to user info +of serialization error (Yannick Heinrich) + + * Add `imageResponseSerializer` property to `UIButton` category (Kristian +Bauer, Mattt Thompson) + + * Add `removesKeysWithNullValues` setting to serialization and copying (Jon +Shier) + + * Change request and response serialization tests to be factored out into +separate files (Mattt Thompson) + + * Change signature of success parameters in `UIButton` category methods to +match those in `UIImageView` (Mattt Thompson) + + * Change to remove charset parameter from +`application/x-www-form-urlencoded` content type (Mattt Thompson) + + * Change `AFImageCache` to conform to `NSObject` protocol ( Marcelo Fabri) + + * Change `AFMaximumNumberOfToRecreateBackgroundSessionUploadTask` to +`AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask` (Mattt +Thompson) + + * Fix documentation error for NSSecureCoding (Robert Ryan) + + * Fix documentation for `URLSessionDidFinishEventsForBackgroundURLSession` +delegate method (Mattt Thompson) + + * Fix expired ADN certificate in example project (Carson McDonald) + + * Fix for interoperability within Swift project (Stephan Krusche) + + * Fix for potential deadlock due to KVO subscriptions within a lock +(Alexander Skvortsov) + + * Fix iOS 7 bug where session tasks can have duplicate identifiers if +created from different threads (Mattt Thompson) + + * Fix iOS 8 bug by adding explicit synthesis for `delegate` of +`AFMultipartBodyStream` (Mattt Thompson) + + * Fix issue caused by passing `nil` as body of multipart form part (Mattt +Thompson) + + * Fix issue caused by passing `nil` as destination in download task method +(Mattt Thompson) + + * Fix issue with `AFHTTPRequestSerializer` returning a request and silently +handling an error from a `queryStringSerialization` block (Kyle Fuller, Mattt +Thompson) + + * Fix potential issues by ensuring `invalidateSessionCancelingTasks` only +executes on main thread (Mattt Thompson) + + * Fix potential memory leak caused by deferred opening of output stream +(James Tomson) + + * Fix properties on session managers such that default values will not trump +values set in the session configuration (Mattt Thompson) + + * Fix README to include explicit call to start reachability manager (Mattt +Thompson) + + * Fix request serialization error handling in `AFHTTPSessionManager` +convenience methods (Kyle Fuller, Lars Anderson, Mattt Thompson) + + * Fix stray localization macro (Devin McKaskle) + + * Fix to ensure connection operation `-copyWithZone:` calls super +implementation (Chris Streeter) + + * Fix `UIButton` category to only cancel request for specified state +(@xuzhe, Mattt Thompson) + +## [2.3.1](https://github.com/AFNetworking/AFNetworking/releases/tag/2.3.1) (2014-06-13) + + * Fix issue with unsynthesized `streamStatus` & `streamError` properties +on `AFMultipartBodyStream` (Mattt Thompson) + +## [2.3.0](https://github.com/AFNetworking/AFNetworking/releases/tag/2.3.0) (2014-06-11) + + * Add check for `AF_APP_EXTENSIONS` macro to conditionally compile +background method that makes API call unavailable to App Extensions in iOS 8 +/ OS X 10.10 + + * Add further explanation for network reachability in documentation (Steven +Fisher) + + * Add notification for initial change from +`AFNetworkReachabilityStatusUnknown` to any other state (Jason Pepas, +Sebastian S.A., Mattt Thompson) + + * Add tests for AFNetworkActivityIndicatorManager (Dave Weston, Mattt +Thompson) + + * Add tests for AFURLSessionManager task progress (Ullrich Schäfer) + + * Add `attemptsToRecreateUploadTasksForBackgroundSessions` property, which +attempts Apple's recommendation of retrying a failed upload task if initial +creation did not succeed (Mattt Thompson) + + * Add `completionQueue` and `completionGroup` properties to +`AFHTTPRequestOperationManager` (Robert Ryan) + + * Change deprecating `AFErrorDomain` in favor of +`AFRequestSerializerErrorDomain` & `AFResponseSerializerErrorDomain` (Mattt +Thompson) + + * Change serialization tests to be split over two different files (Mattt +Thompson) + + * Change to make NSURLSession subspec not depend on NSURLConnection subspec +(Mattt Thompson) + + * Change to make Serialization subspec not depend on NSURLConnection subspec +(Nolan Waite, Mattt Thompson) + + * Change `completionHandler` of +`application:handleEventsForBackgroundURLSession:completion:` to be run on +main thread (Padraig Kennedy) + + * Change `UIImageView` category to accept any object conforming to +`AFURLResponseSerialization`, rather than just `AFImageResponseSerializer` +(Romans Karpelcevs) + + * Fix calculation and behavior of `NSProgress` (Padraig Kennedy, Ullrich +Schäfer) + + * Fix deprecation warning for `backgroundSessionConfiguration:` in iOS 8 / +OS X 10.10 (Mattt Thompson) + + * Fix implementation of `copyWithZone:` in serializer subclasses (Chris +Streeter) + + * Fix issue in Xcode 6 caused by implicit synthesis of overridden `NSStream` +properties (Clay Bridges, Johan Attali) + + * Fix KVO handling for `NSURLSessionTask` on iOS 8 / OS X 10.10 (Mattt +Thompson) + + * Fix KVO leak for `NSURLSessionTask` (@Zyphrax) + + * Fix potential crash caused by attempting to use non-existent error of +failing requests due to URLs exceeding a certain length (Boris Bügling) + + * Fix to check existence of `uploadProgress` block inside a referencing +`dispatch_async` to avoid potential race condition (Kyungkoo Kang) + + * Fix `UIImageView` category race conditions (Sunny) + + * Remove unnecessary default operation response serializer setters (Mattt +Thompson) + +## [2.2.4](https://github.com/AFNetworking/AFNetworking/releases/tag/2.2.4) (2014-05-13) + + * Add NSSecureCoding support to all AFNetworking classes (Kyle Fuller, Mattt +Thompson) + + * Change behavior of request operation `NSOutputStream` property to only nil +out if `responseData` is non-nil, meaning that no custom object was set +(Mattt Thompson) + + * Fix data tasks to not attempt to track progress, and rare related crash +(Padraig Kennedy) + + * Fix issue with `-downloadTaskDidFinishDownloading:` not being called +(Andrej Mihajlov) + + * Fix KVO leak on invalidated session tasks (Mattt Thompson) + + * Fix missing import of `UIRefreshControl+AFNetworking" (@BB9z) + + * Fix potential compilation errors on Mac OS X, caused by import order of +``, which signaled an incorrect deprecation warning (Mattt +Thompson) + + * Fix race condition in UIImageView+AFNetworking when making several image +requests in quick succession (Alexander Crettenand) + + * Update documentation for `-downloadTaskWithRequest:` to warn about blocks +being disassociated on app termination and backgrounding (Robert Ryan) + +## [2.2.3](https://github.com/AFNetworking/AFNetworking/releases/tag/2.2.3) (2014-04-18) + + * Fix `AFErrorOrUnderlyingErrorHasCodeInDomain` function declaration for +AFXMLDocumentResponseSerializer (Mattt Thompson) + + * Fix error domain check in `AFErrorOrUnderlyingErrorHasCodeInDomain` +(Mattt Thompson) + + * Fix `UIImageView` category to only `nil` out request operation properties +belonging to completed request (Mattt Thompson) + + * Fix `removesKeysWithNullValues` to respect +`NSJSONReadingMutableContainers` option (Mattt Thompson) + + * Change `removesKeysWithNullValues` property to recursively remove null +values from dictionaries nested in arrays (@jldagon) + + * Change to not override `Content-Type` header field values set by +`HTTPRequestHeaders` property (Aaron Brager, Mattt Thompson) + +## [2.2.2](https://github.com/AFNetworking/AFNetworking/releases/tag/2.2.2) (2014-04-15) + + * Add `removesKeysWithNullValues` property to `AFJSONResponsSerializer` to +automatically remove `NSNull` values in dictionaries serialized from JSON +(Mattt Thompson) + + * Add unit test for checking content type (Diego Torres) + + * Add `boundary` property to `AFHTTPBodyPart -copyWithZone:` + + * Change to accept `id` parameter type in HTTP manager convenience methods +(Mattt Thompson) + + * Change to deprecate `setAuthorizationHeaderFieldWithToken:`, in favor of +users specifying an `Authorization` header field value themselves (Mattt +Thompson) + + * Change to use `long long` type to prevent a difference in stream size +caps on 32-bit and 64-bit architectures (Yung-Luen Lan, Cédric Luthi) + + * Fix calculation of Content-Length in `taskDidSendBodyData` (Christos +Vasilakis) + + * Fix for comparison of image view request operations (Mattt Thompson) + + * Fix for SSL certificate validation to check status codes at runtime (Dave +Anderson) + + * Fix to add missing call to delegate in +`URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:` + + * Fix to call `taskDidComplete` if delegate is missing (Jeff Ward) + + * Fix to implement `respondsToSelector:` for `NSURLSession` delegate +methods to conditionally respond to conditionally respond to optional +selectors if and only if a custom block has been set (Mattt Thompson) + + * Fix to prevent illegal state values from being assigned for +`AFURLConnectionOperation` (Kyle Fuller) + + * Fix to re-establish `AFNetworkingURLSessionTaskDelegate` objects after +restoring from a background configuration (Jeff Ward) + + * Fix to reduce memory footprint by `nil`-ing out request operation +`outputStream` after closing, as well as image view request operation after +setting image (Teun van Run, Mattt Thompson) + + * Remove unnecessary call in class constructor (Bernhard Loibl) + + * Remove unnecessary check for `respondsToSelector:` for `UIScreen scale` +in User-Agent string (Samuel Goodwin) + + * Update App.net certificate and API base URL (Cédric Luthi) + + * Update examples in README (@petard, @orta, Mattt Thompson) + + * Update Travis CI icon to use SVG format (Maximilian Tagher) + +## [2.2.1](https://github.com/AFNetworking/AFNetworking/releases/tag/2.2.1) (2014-03-14) + + * Fix `-Wsign-conversion` warning in AFURLConnectionOperation (Jesse Collis) + + * Fix `-Wshorten-64-to-32` warning (Jesse Collis) + + * Remove unnecessary #imports in `UIImageView` & `UIWebView` categories +(Jesse Collis) + + * Fix call to `CFStringTransform()` by checking return value before setting +as `User-Agent` (Kevin Cassidy Jr) + + * Update `AFJSONResponseSerializer` adding `@autorelease` to relieve memory +pressure (Mattt Thompson, Michal Pietras) + + * Update `AFJSONRequestSerializer` to accept `id` (Daren Desjardins) + + * Fix small documentation bug (@jkoepcke) + + * Fix behavior of SSL pinning. In case of `validatesDomainName == YES`, it +now explicitly uses `SecPolicyCreateSSL`, which also validates the domain +name. Otherwise, `SecPolicyCreateBasicX509` is used. +`AFSSLPinningModeCertificate` now uses `SecTrustSetAnchorCertificates`, which +allows explicit specification of all trusted certificates. For +`AFSSLPinningModePublicKey`, the number of trusted public keys determines if +the server should be trusted. (Oliver Letterer, Eric Allam) + +## [2.2.0](https://github.com/AFNetworking/AFNetworking/releases/tag/2.2.0) (2014-02-25) + + * Add default initializer to make `AFHTTPRequestOperationManager` +consistent with `AFHTTPSessionManager` (Marcelo Fabri) + + * Add documentation about `UIWebView` category and implementing +`UIWebViewDelegate` (Mattt Thompson) + + * Add missing `NSCoding` and `NSCopying` implementations for +`AFJSONRequestSerializer` (Mattt Thompson) + + * Add note about use of `-startMonitoring` in +`AFNetworkReachabilityManager` (Mattt Thompson) + + * Add setter for needsNewBodyStream block (Carmen Cerino) + + * Add support for specifying a response serializer on a per-instance of +`AFURLSessionManagerTaskDelegate` (Blake Watters) + + * Add `AFHTTPRequestSerializer +-requestWithMultipartFormRequest:writingStreamContentsToFile:completionHandler +:` as a workaround for a bug in NSURLSession that removes the Content-Length +header from streamed requests (Mattt Thompson) + + * Add `NSURLRequest` factory properties on `AFHTTPRequestSerializer` (Mattt +Thompson) + + * Add `UIRefreshControl+AFNetworking` (Mattt Thompson) + + * Change example project to enable certificate pinning (JP Simard) + + * Change to allow self-signed certificates (Frederic Jacobs) + + * Change to make `reachabilityManager` property readwrite (Mattt Thompson) + + * Change to sort `NSSet` members during query string parameter +serialization (Mattt Thompson) + + * Change to use case sensitive compare when sorting keys in query string +serialization (Mattt Thompson) + + * Change to use xcpretty instead of xctool for automated testing (Kyle +Fuller, Marin Usalj, Carson McDonald) + + * Change to use `@selector` values as keys for associated objects (Mattt +Thompson) + + * Change `setImageWithURL:placeholder:`, et al. to only set placeholder +image if not `nil` (Alejandro Martinez) + + * Fix auto property synthesis warnings (Oliver Letterer) + + * Fix domain name validation for SSL certificates (Oliver Letterer) + + * Fix issue with session task delegate KVO observation (Kyle Fuller) + + * Fix placement of `baseURL` method declaration (Oliver Letterer) + + * Fix podspec linting error (Ari Braginsky) + + * Fix potential concurrency issues by adding lock around setting +`isFinished` state in `AFURLConnectionOperation` (Mattt Thompson) + + * Fix potential vulnerability caused by hard-coded multipart form data +boundary (Mathias Bynens, Tom Van Goethem, Mattt Thompson) + + * Fix protocol name in #pragma mark declaration (@sevntine) + + * Fix regression causing inflated images to have incorrect orientation +(Mattt Thompson) + + * Fix to `AFURLSessionManager` `NSCoding` implementation, to accommodate +`NSURLSessionConfiguration` no longer conforming to `NSCoding`. + + * Fix Travis CI integration (Kyle Fuller, Marin Usalj, Carson McDonald) + + * Fix various static analyzer warnings (Philippe Casgrain, Jim Young, +Steven Fisher, Mattt Thompson) + + * Fix with download progress calculation of completion units (Kyle Fuller) + + * Fix Xcode 5.1 compiler warnings (Nick Banks) + + * Fix `AFHTTPRequestOperationManager` to default +`shouldUseCredentialStorage` to `YES`, as documented (Mattt Thompson) + + * Remove Unused format property in `AFJSONRequestSerializer` (Mattt +Thompson) + + * Remove unused `acceptablePathExtensions` class method in +`AFJSONRequestSerializer` (Mattt Thompson) + + * Update #ifdef declarations in UIKit categories to be simpler (Mattt +Thompson) + + * Update podspec to includ social_media_url (Kyle Fuller) + + * Update types for 64 bit architecture (Bruno Tortato Furtado, Mattt +Thompson) + +## [2.1.0](https://github.com/AFNetworking/AFNetworking/releases/tag/2.1.0) (2014-01-16) + + * Add CONTRIBUTING (Kyle Fuller) + + * Add domain name verification for SSL certificates (Oliver Letterer) + + * Add leaf certificate checking (Alex Leverington, Carson McDonald, Mattt +Thompson) + + * Add test case for stream failure handling (Kyle Fuller) + + * Add underlying error properties to response serializers to forward errors +to subsequent validation steps (Mattt Thompson) + + * Add `AFImageCache` protocol, to allow for custom image caches to be +specified for `UIImageView` (Mattt Thompson) + + * Add `error` out parameter for request serializer, deprecating existing +request constructor methods (Adam Becevello) + + * Change request serializer protocol to take id type for parameters (Mattt +Thompson) + + * Change to add validation of download task responses (Mattt Thompson) + + * Change to force upload progress, by using original request Content-Length +(Mateusz Malczak) + + * Change to use `NSDictionary` object literals for `NSError` `userInfo` +construction (Mattt Thompson) + + * Fix #pragma declaration to be NSURLConnectionDataDelegate, rather than +NSURLConnectionDelegate (David Paschich) + + * Fix a bug when appending a file part to multipart request from a URL +(Kyle Fuller) + + * Fix analyzer warning about weak receiver being set to nil, capture strong +reference (Stewart Gleadow) + + * Fix appending file part to multipart request to use suggested file name, +rather than temporary one (Kyle Fuller) + + * Fix availability macros for network activity indicator (Mattt Thompson) + + * Fix crash in iOS 6.1 caused by KVO on `isCancelled` property of +`AFURLConnectionOperation` (Sam Page) + + * Fix dead store issues in `AFSecurityPolicy` (Andrew Hershberger) + + * Fix incorrect documentation for `-HTTPRequestOperationWithRequest:...` +(Kyle Fuller) + + * Fix issue in reachability callbacks, where reachability managers created +for a particular domain would initially report no reachability (Mattt +Thompson) + + * Fix logic for handling data task turning into download task (Kyle Fuller) + + * Fix property list response serializer to handle 204 response (Kyle Fuller) + + * Fix README multipart example (Johan Forssell) + + * Fix to add check for non-nil delegate in +`URLSession:didCompleteWithError:` (Kaom Te) + + * Fix to dramatically improve creation of images in +`AFInflatedImageFromResponseWithDataAtScale`, including handling of CMYK, 16 +/ 32 bpc images, and colorspace alpha settings (Robert Ryan) + + * Fix Travis CI integration and unit testing (Kyle Fuller, Carson McDonald) + + * Fix typo in comments (@palringo) + + * Fix UIWebView category to use supplied success callback (Mattt Thompson) + + * Fix various static analyzer warnings (Kyle Fuller, Jesse Collis, Mattt +Thompson) + + * Fix `+batchOfRequestOperations:...` completion block to execute in +`dispatch_async` (Mattt Thompson) + + * Remove synchronous `SCNetworkReachabilityGetFlags` call when initializing +managers, which had the potential to block in certain network conditions +(Yury Korolev, Mattt Thompson) + + * Remove unnecessary check for completionHandler in HTTP manager (Mattt +Thompson) + + * Remove unused conditional clauses (Luka Bratos) + + * Update documentation for `AFCompoundResponseSerializer` (Mattt Thompson) + + * Update httpbin certificates (Carson McDonald) + + * Update notification constant names to be consistent with `NSURLSession` +terminology (Mattt Thompson) + +## [2.0.3](https://github.com/AFNetworking/AFNetworking/releases/tag/2.0.3) (2013-11-18) + + * Fix a bug where `AFURLConnectionOperation -pause` did not correctly reset +the state of `AFURLConnectionOperation`, causing the Network Thread to enter +an infinite loop (Erik Chen) + + * Fix a bug where `AFURLConnectionOperation -cancel` does not set the +appropriate error on the `NSOperation` (Erik Chen) + + * Fix to post `AFNetworkingTaskDidFinishNotification` only on main queue +(Jakub Hladik) + + * Fix issue where the query string serialization block was not used (Kevin +Harwood) + + * Fix project file and repository directory items (Andrew Newdigate) + + * Fix `NSURLSession` subspec (Mattt Thompson) + + * Fix to session task delegate KVO by moving observer removal to +`-didCompleteWithError:` (Mattt Thompson) + + * Add AFNetworking 1.x behavior for image construction in inflation to +ensure correct orientation (Mattt Thompson) + + * Add `NSParameterAssert` for internal task constructors in order to catch +invalid constructions early (Mattt Thompson) + + * Update replacing `NSParameterAssert` with early `nil` return if session +was unable to create a task (Mattt Thompson) + + * Update `AFHTTPRequestOperationManager` and `AFHTTPSessionManager` to use +relative `self class` to create class constructor instances (Bogdan +Poplauschi) + + * Update to break out of loop if output stream does not have space to write +bytes (Mattt Thompson) + + * Update documentation and README with various fixes (Max Goedjen, Mattt +Thompson) + + * Remove unnecessary willChangeValueForKey and didChangeValueForKey method +calls (Mindaugas Vaičiūnas) + + * Remove deletion of all task delegates in +`URLSessionDidFinishEventsForBackgroundURLSession:` (Jeremy Mailen) + + * Remove empty, unused `else` branch (Luka Bratos) + +## [2.0.2](https://github.com/AFNetworking/AFNetworking/releases/tag/2.0.2) (2013-10-29) + + * Add `UIWebView + -loadRequest:MIMEType:textEncodingName:progress:success:failure:` (Mattt + Thompson) + + * Fix iOS 6 compatibility in `AFHTTPSessionManager` & + `UIProgressView+AFNetworking` (Olivier Halligon, Mattt Thompson) + + * Fix issue writing partial data to output stream (Kyle Fuller) + + * Fix behavior for `nil` response in request operations (Marcelo Fabri) + + * Fix implementation of + batchOfRequestOperations:progressBlock:completionBlock: for nil when passed + empty operations parameter (Mattt Thompson) + + * Update `AFHTTPSessionManager` to allow `-init` and `initWithConfig:` to + work (Ben Scheirman) + + * Update `AFRequestOperation` to default to `AFHTTPResponseSerializer` (Jiri + Techet) + + * Update `AFHTTPResponseSerializer` to remove check for nonzero responseData + length (Mattt Thompson) + + * Update `NSCoding` methods to use NSStringFromSelector(@selector()) pattern + instead of `NSString` literals (Mattt Thompson) + + * Update multipart form stream to set Content-Length after setting request + stream (Mattt Thompson) + + * Update documentation with outdated references to `AFHTTPSerializer` (Bruno + Koga) + + * Update documentation and README with various fixes (Jon Chambers, Mattt + Thompson) + + * Update files to remove executable privilege (Kyle Fuller) + +## 2.0.1 (2013-10-10) + + * Fix iOS 6 compatibility (Matt Baker, Mattt Thompson) + + * Fix example applications (Sam Soffes, Kyle Fuller) + + * Fix usage of `NSSearchPathForDirectoriesInDomains` in README (Leo Lou) + + * Fix names of exposed private methods `downloadProgress` and +`uploadProgress` (Hermes Pique) + + * Fix initial upload/download task progress updates (Vlas Voloshin) + + * Fix podspec to include `AFNetworking.h` `#import` (@haikusw) + + * Fix request serializers to not override existing header field values with +defaults (Mattt Thompson) + + * Fix unused format string placeholder (Thorsten Lockert) + + * Fix `AFHTTPRequestOperation -initWithCoder:` to call `super` (Josh Avant) + + * Fix `UIProgressView` selector name (Allen Tu) + + * Fix `UIButton` response serializer (Sam Grossberg) + + * Fix `setPinnedCertificates:` and pinned public keys (Kyle Fuller) + + * Fix timing of batched operation completion block (Denys Telezhkin) + + * Fix `GCC_WARN_ABOUT_MISSING_NEWLINE` compiler warning (Chuck Shnider) + + * Fix a format string missing argument issue in tests (Kyle Fuller) + + * Fix location of certificate chain bundle location (Kyle Fuller) + + * Fix memory leaks in AFSecurityPolicyTests (Kyle Fuller) + + * Fix potential concurrency issues in `AFURLSessionManager` by adding locks +around access to mutiple delegates dictionary (Mattt Thompson) + + * Fix unused variable compiler warnings by wrapping `OSStatus` and +`NSCAssert` with NS_BLOCK_ASSERTIONS macro (Mattt Thompson) + + * Fix compound serializer error handling (Mattt Thompson) + + * Fix string encoding for responseString (Juan Enrique) + + * Fix `UIImageView -setBackgroundImageWithRequest:` (Taichiro Yoshida) + + * Fix regressions nested multipart parameters (Mattt Thompson) + + * Add `responseObject` property to `AFHTTPRequestOperation` (Mattt Thompson) + + * Add support for automatic network reachability monitoring for request +operation and session managers (Mattt Thompson) + + * Update documentation and README with various corrections and fixes +(@haikusw, Chris Hellmuth, Dave Caunt, Mattt Thompson) + + * Update default User-Agent such that only ASCII character set is used +(Maximillian Dornseif) + + * Update SSL pinning mode to have default pinned certificates by default +(Kevin Harwood) + + * Update `AFSecurityPolicy` to use default authentication handling unless a +credential exists for the server trust (Mattt Thompson) + + * Update Prefix.pch (Steven Fisher) + + * Update minimum iOS test target to iOS 6 + + * Remove unused protection space block type (Kyle Fuller) + + * Remove unnecessary Podfile.lock (Kyle Fuller) + +## [2.0.0](https://github.com/AFNetworking/AFNetworking/releases/tag/2.0.0) (2013-09-27) + +* Initial 2.0.0 Release + +==================== +#AFNetworking 1.0 Change Log +-- + +## [1.3.4](https://github.com/AFNetworking/AFNetworking/releases/tag/1.3.4) (2014-04-15) + + * Fix `AFHTTPMultipartBodyStream` to randomly generate form boundary, to +prevent attack based on a known value (Mathias Bynens, Tom Van Goethem, Mattt +Thompson) + + * Fix potential non-terminating loop in `connection:didReceiveData:` (Mattt +Thompson) + + * Fix SSL certificate validation to provide a human readable Warning when +SSL Pinning fails (Maximillian Dornseif) + + * Fix SSL certificate validation to assert that no impossible pinning +configuration exists (Maximillian Dornseif) + + * Fix to check `CFStringTransform()` call for success before using result +(Kevin Cassidy Jr) + + * Fix to prevent unused assertion results with macros (Indragie Karunaratne) + + * Fix to call call `SecTrustEvaluate` before calling +`SecTrustGetCertificateCount` in SSL certificate validation (Josh Chung) + + * Fix to add explicit cast to `NSUInteger` in format string (Alexander +Kempgen) + + * Remove unused variable `kAFStreamToStreamBufferSize` (Alexander Kempgen) + +## [1.3.3](https://github.com/AFNetworking/AFNetworking/releases/tag/1.3.3) (2013-09-25) + + * Add stream error handling to `AFMultipartBodyStream` (Nicolas Bachschmidt, +Mattt Thompson) + + * Add stream error handling to `AFURLConnectionOperation +-connection:didReceiveData:` (Ian Duggan, Mattt Thompson) + + * Fix parameter query string encoding of square brackets according to RFC +3986 (Kra Larivain) + + * Fix AFHTTPBodyPart determination of end of input stream data (Brian Croom) + + * Fix unit test timeouts (Carson McDonald) + + * Fix truncated `User-Agent` header field when app contained non-ASCII +characters (Diego Torres) + + * Fix outdated link in documentation (Jonas Schmid) + + * Fix `AFHTTPRequestOperation` `HTTPError` property to be thread-safe +(Oliver Letterer, Mattt Thompson) + + * Fix API compatibility with iOS 5 (Blake Watters, Mattt Thompson) + + * Fix potential race condition in `AFURLConnectionOperation +-cancelConnection` (@mm-jkolb, Mattt Thompson) + + * Remove implementation of `connection:needNewBodyStream:` delegate method +in `AFURLConnectionOperation`, which fixes stream errors on authentication +challenges (Mattt Thompson) + + * Fix calculation of network reachability from flags (Tracy Pesin, Mattt +Thompson) + + * Update AFHTTPClient documentation to clarify scope of `parameterEncoding` +property (Thomas Catterall) + + * Update `UIImageView` category to allow for nested calls to +`setImageWithURLRequest:` (Philippe Converset) + + * Change `UIImageView` category to accept invalid SSL certificates when +`_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is defined (Flávio Caetano) + + * Change to replace #pragma clang with cast (Cédric Luthi) + +## [1.3.2](https://github.com/AFNetworking/AFNetworking/releases/tag/1.3.2) (2013-08-08) + + * Add return status checks when building list of pinned public keys (Sylvain +Guillope) + + * Add return status checks when handling connection authentication challenges +(Sylvain Guillope) + + * Add tests around `AFHTTPClient initWithBaseURL:` (Kyle Fuller) + + * Change to remove all `_AFNETWORKING_PIN_SSL_CERTIFICATES_` conditional +compilation (Dustin Barker) + + * Change to allow fallback to generic image loading when PNG/JPEG data +provider methods fail (Darryl H. Thomas) + + * Change to only set placeholder image if not `nil` (Mattt Thompson) + + * Change to use `response.MIMEType` rather than (potentially nonexistent) +Content-Type headers to determine image data provider (Mattt Thompson) + + * Fix image request test endpoint (Carson McDonald) + + * Fix compiler warning caused by `size_t` value defaulted to `NULL` (Darryl H. +Thomas) + + * Fix mutable headers property in `AFHTTPClient -copyWithZone:` (Oliver +Letterer) + + * Fix documentation and asset references in README (Romain Pouclet, Peter +Goldsmith) + + * Fix bug in examples always using `AFSSLPinningModeNone` (Dustin Barker) + + * Fix execution of tests under Travis (Blake Watters) + + * Fix static analyzer warnings about CFRelease calls to NULL pointer (Mattt +Thompson) + + * Change to return early in `AFGetMediaTypeAndSubtypeWithString` if string is +`nil` (Mattt Thompson) + + * Change to opimize network thread creation (Mattt Thompson) + +## [1.3.1](https://github.com/AFNetworking/AFNetworking/releases/tag/1.3.1) (2013-06-18) + + * Add `automaticallyInflatesResponseImage` property to +`AFImageRequestOperation`, which when enabled, offers significant performance +improvements for drawing images loaded through `UIImageView+AFNetworking` by +inflating compressed image data in the background (Mattt Thompson, Peter +Steinberger) + + * Add `NSParameterAssert` check for `nil` `urlRequest` parameter in +`AFURLConnectionOperation` initializer (Kyle Fuller) + + * Fix reachability to detect the case where a connection is required but can +be automatically established (Joshua Vickery) + + * Fix to Test target Podfile (Kyle Fuller) + +## [1.3.0](https://github.com/AFNetworking/AFNetworking/releases/tag/1.3.0) (2013-06-01) + + * Change in `AFURLConnectionOperation` `NSURLConnection` authentication +delegate methods and associated block setters. If +`_AFNETWORKING_PIN_SSL_CERTIFICATES_` is defined, +`-setWillSendRequestForAuthenticationChallengeBlock:` will be available, and +`-connection:willSendRequestForAuthenticationChallenge:` will be implemented. +Otherwise, `-setAuthenticationAgainstProtectionSpaceBlock:` & +`-setAuthenticationChallengeBlock:` will be available, and +`-connection:canAuthenticateAgainstProtectionSpace:` & +`-connection:didReceiveAuthenticationChallenge:` will be implemented instead +(Oliver Letterer) + + * Change in AFNetworking podspec to include Security framework (Kevin Harwood, +Oliver Letterer, Sam Soffes) + + * Change in AFHTTPClient to @throw exception when non-designated intializer is +used (Kyle Fuller) + + * Change in behavior of connection:didReceiveAuthenticationChallenge: to not +use URL-encoded credentials, which should already have been applied (@xjdrew) + + * Change to set AFJSONRequestOperation error when unable to decode response +string (Chris Pickslay, Geoff Nix) + + * Change AFURLConnectionOperation to lazily initialize outputStream property +(@fumoboy007) + + * Change instances of (CFStringRef)NSRunLoopCommonModes to +kCFRunLoopCommonModes + + * Change #warning to #pragma message for dynamic framework linking warnings +(@michael_r_may) + + * Add unit testing and continuous integration system (Blake Watters, Oliver +Letterer, Kevin Harwood, Cédric Luthi, Adam Fraser, Carson McDonald, Mattt +Thompson) + + * Fix multipart input stream implementation (Blake Watters, OliverLetterer, +Aleksey Kononov, @mattyohe, @mythodeia, @JD-) + + * Fix implementation of authentication delegate methods (Oliver Letterer, +Kevin Harwood) + + * Fix implementation of AFSSLPinningModePublicKey on Mac OS X (Oliver Letterer) + + * Fix error caused by loading file:// requests with AFHTTPRequestOperation +subclasses (Dave Anderson, Oliver Letterer) + + * Fix threading-related crash in AFNetworkActivityIndicatorManager (Dave Keck) + + * Fix to suppress GNU expression and enum assignment warnings from Clang +(Henrik Hartz) + + * Fix leak caused by CFStringConvertEncodingToIANACharSetName in AFHTTPClient +-requestWithMethod:path:parameters: (Daniel Demiss) + + * Fix missing __bridge casts in AFHTTPClient (@apouche, Mattt Thompson) + + * Fix Objective-C++ compatibility (Audun Holm Ellertsen) + + * Fix to not escape tildes (@joein3d) + + * Fix warnings caused by unsynthesized properties (Jeff Hunter) + + * Fix to network reachability calls to provide correct status on +initialization (@djmadcat, Mattt Thompson) + + * Fix to suppress warnings about implicit signedness conversion (Matt Rubin) + + * Fix AFJSONRequestOperation -responseJSON failing cases (Andrew Vyazovoy, +Mattt Thompson) + + * Fix use of object subscripting to avoid incompatibility with iOS < 6 and OS +X < 10.8 (Paul Melnikow) + + * Various fixes to reverted multipart stream provider implementation (Yaron +Inger, Alex Burgel) + +## [1.2.1](https://github.com/AFNetworking/AFNetworking/releases/tag/1.2.1) (2013-04-18) + + * Add `allowsInvalidSSLCertificate` property to `AFURLConnectionOperation` and +`AFHTTPClient`, replacing `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` macro +(Kevin Harwood) + + * Add SSL pinning mode to example project (Kevin Harwood) + + * Add name to AFNetworking network thread (Peter Steinberger) + + * Change pinned certificates to trust all derived certificates (Oliver +Letterer) + + * Fix documentation about SSL pinning (Kevin Harwood, Mattt Thompson) + + * Fix certain enumerated loops to use fast enumeration, resulting in better +performance (Oliver Letterer) + + * Fix macro to work correctly under Mac OS X 10.7 and iOS 4 SDK (Paul Melnikow) + + * Fix documentation, removing unsupported `@discussion` tags (Michele Titolo) + + * Fix `SecTrustCreateWithCertificates` expecting an array as first argument +(Oliver Letterer) + + * Fix to use `errSecSuccess` instead of `noErr` for Security frameworks +OSStatus (Oliver Letterer) + + * Fix `AFImageRequestOperation` to use `[self alloc]` instead of explicit +class, which allows for subclassing (James Clarke) + + * Fix for `numberOfFinishedOperations` calculations (Rune Madsen) + + * Fix calculation of data length in `-connection:didReceiveData:` +(Jean-Francois Morin) + + * Fix to encode JSON only with UTF-8, following recommendation of +`NSJSONSerialiation` (Sebastian Utz) + +## [1.2.0](https://github.com/AFNetworking/AFNetworking/releases/tag/1.2.0) (2013-03-24) + + * Add `SSLPinningMode` property to `AFHTTPClient` (Oliver Letterer, Kevin +Harwood, Adam Becevello, Dustin Barker, Mattt Thompson) + + * Add single quote ("'"), comma (","), and asterix ("*") to escaped URL +encoding characters (Eric Florenzano, Marc Nijdam, Garrett Murray) + + * Add `credential` property to `AFURLConnectionOperation` (Mattt Thompson) + + * Add `-setDefaultCredential:` to `AFHTTPClient` + + * Add `shouldUseCredentialStorage` property to `AFURLConnectionOperation` +(Mattt Thompson) + + * Add support for repeated key value pairs in `AFHTTPClient` URL query string +(Nick Dawson) + + * Add `AFMultipartFormData - +appendPartWithFileURL:name:fileName:mimeType:error` (Daniel Rodríguez Troitiño) + + * Add `AFMultipartFormData - +appendPartWithInputStream:name:fileName:mimeType:` (@joein3d) + + * Change SSL pinning to be runtime property on `AFURLConnectionOperation` +rather than defined by macro (Oliver Letterer) + + * Change `AFMultipartBodyStream` to `AFMultipartBodyStreamProvider`, vending +one side of a bound CFStream pair rather than subclassing `NSInputStream` (Mike +Ash) + + * Change default `Accept-Language` header in `AFHTTPClient` (@therigu, Mattt +Thompson) + + * Change `AFHTTPClient` operation cancellation to be based on request URL path +rather than absolute URL string (Mattt Thompson) + + * Change request operation subclass processing queues to use +`DISPATCH_QUEUE_CONCURRENT` (Mattt Thompson) + + * Change `UIImageView+AFNetworking` to resolve asymmetry in cached image case +between success block provided and not provided (@Eveets, Mattt Thompson) + + * Change `UIImageView+AFNetworking` to compare `NSURLRequest` instead of +`NSURL` to determine if previous request was equivalent (Cédric Luthi) + + * Change `UIImageView+AFNetworking` to only set image if non-`nil` (Sean +Kovacs) + + * Change indentation settings to four spaces at the project level (Cédric +Luthi) + + * Change `AFNetworkActivityIndicatorManager` to only update if requests have a +non-`nil` URL (Cédric Luthi) + + * Change `UIImageView+AFNetworking` to not do `setHTTPShouldHandleCookies` +(Konstantinos Vaggelakos) + + * Fix request stream exhaustion error on authentication challenges (Alex +Burgel) + + * Fix implementation to use `NSURL` methods instead of `CFURL` functions where +applicable (Cédric Luthi) + + * Fix race condition in `UIImageView+AFNetworking` (Peyman) + + * Fix `responseJSON`, `responseString`, and `responseStringEncoding` to be +threadsafe (Jon Parise, Mattt Thompson) + + * Fix `AFContentTypeForPathExtension` to ensure non-`NULL` content return +value (Zach Waugh) + + * Fix documentation for `appendPartWithFileURL:name:error:` + (Daniel Rodríguez Troitiño) + + * Fix request operation subclass processing queues to initialize with +`dispatch_once` (Sasmito Adibowo) + + * Fix posting of `AFNetworkingOperationDidStartNotification` and +`AFNetworkingOperationDidFinishNotification` to avoid crashes when logging in +response to notifications (Blake Watters) + + * Fix ordering of registered operation consultation in `AFHTTPClient` (Joel +Parsons) + + * Fix warning: multiple methods named 'postNotificationName:object:' found +[-Wstrict-selector-match] (Oliver Jones) + + * Fix warning: multiple methods named 'objectForKey:' found +[-Wstrict-selector-match] (Oliver Jones) + + * Fix warning: weak receiver may be unpredictably set to nil +[-Wreceiver-is-weak] (Oliver Jones) + + * Fix missing #pragma clang diagnostic pop (Steven Fisher) + +## [1.1.0](https://github.com/AFNetworking/AFNetworking/releases/tag/1.1.0) (2012-12-27) + + * Add optional SSL certificate pinning with `#define +_AFNETWORKING_PIN_SSL_CERTIFICATES_` (Dustin Barker) + + * Add `responseStringEncoding` property to `AFURLConnectionOperation` (Mattt +Thompson) + + * Add `userInfo` property to `AFURLConnectionOperation` (Mattt Thompson, +Steven Fisher) + + * Change behavior to cause a failure when an operation is cancelled (Daniel +Tull) + + * Change return type of class constructors to `instancetype` (@guykogus) + + * Change notifications to always being posted on an asynchronously-dispatched +block run on the main queue (Evadne Wu, Mattt Thompson) + + * Change from NSLocalizedString to NSLocalizedStringFromTable with +AFNetworking.strings table for localized strings (Cédric Luthi) + + * Change `-appendPartWithHeaders:body:` to add assertion handler for existence +of body data parameter (Jonathan Beilin) + + * Change `AFHTTPRequestOperation -responseString` to follow guidelines from +RFC 2616 regarding the use of string encoding when none is specified in the +response (Jorge Bernal) + + * Change AFHTTPClient parameter serialization dictionary keys with +`caseInsensitiveCompare:` to ensure + deterministic ordering of query string parameters, which may otherwise + cause ambiguous representations of nested parameters (James Coleman, + Mattt Thompson) + + * Fix -Wstrict-selector-match warnings raised by Xcode 4.6DP3 (Jesse Collis, +Cédric Luthi) + + * Fix NSJSONSerialization crash with Unicode character escapes in JSON +response (Mathijs Kadijk) + + * Fix issue with early return in -startMonitoringNetworkReachability if +network reachability object could not be created (i.e. invalid hostnames) +(Basil Shkara) + + * Fix retain cycles in AFImageRequestOperation.m and AFHTTPClient.m caused by +strong references within blocks (Nick Forge) + + * Fix issue caused by Rails behavior of returning a single space in head :ok +responses, which is interpreted as invalid (Sebastian Ludwig) + + * Fix issue in streaming multipart upload, where final encapsulation boundary +would not be appended if it was larger than the available buffer, causing a +potential timeout (Tomohisa Takaoka, David Kasper) + + * Fix memory leak of network reachability callback block (Mattt Thompson) + + * Fix `-initWithCoder:` for `AFURLConnectionOperation` and `AFHTTPClient` to +cast scalar types (Mattt Thompson) + + * Fix bug in `-enqueueBatchOfHTTPRequestOperations:...` to by using +`addOperations:waitUntilFinished:` instead of adding each operation +individually. (Mattt Thompson) + + * Change `#warning` messages of checks for `CoreServices` and +`MobileCoreServices` to message according to the build target platform (Mattt +Thompson) + + * Change `AFQueryStringFromParametersWithEncoding` to create keys string +representations using the description method as specified in documentation +(Cédric Luthi) + + * Fix __unused keywords for better Xcode indexing (Christian Rasmussen) + + * Fix warning: unused parameter 'x' [-Werror,-Wunused-parameter] (Oliver Jones) + + * Fix warning: property is assumed atomic by default +[-Werror,-Wimplicit-atomic-properties] (Oliver Jones) + + * Fix warning: weak receiver may be unpredictably null in ARC mode +[-Werror,-Wreceiver-is-weak] (Oliver Jones) + + * Fix warning: multiple methods named 'selector' found +[-Werror,-Wstrict-selector-match] (Oliver Jones) + + * Fix warning: 'macro' is not defined, evaluates to 0 (Oliver Jones) + + * Fix warning: atomic by default property 'X' has a user (Oliver Jones)defined +getter (property should be marked 'atomic' if this is intended) [-Werror, +-Wcustom-atomic-properties] (Oliver Jones) + + * Fix warning: 'response' was marked unused but was used +[-Werror,-Wused-but-marked-unused] (Oliver Jones) + + * Fix warning: enumeration value 'AFFinalBoundaryPhase' not explicitly handled +in switch [-Werror,-Wswitch-enum] (Oliver Jones) + +## [1.0.1](https://github.com/AFNetworking/AFNetworking/releases/tag/1.0.1) / 2012-11-01 + + * Fix error in multipart upload streaming, where byte range at boundaries +was not correctly calculated (Stan Chang Khin Boon) + + * If a success block is specified to `UIImageView -setImageWithURLRequest: +placeholderImage:success:failure`:, it is now the responsibility of the +block to set the image of the image view (Mattt Thompson) + + * Add `JSONReadingOptions` property to `AFJSONRequestOperation` (Jeremy + Foo, Mattt Thompson) + + * Using __weak self / __strong self pattern to break retain cycles in + background task and network reachability blocks (Jerry Beers, Dan Weeks) + + * Fix parameter encoding to leave period (`.`) unescaped (Diego Torres) + + * Fixing last file component in multipart form part creation (Sylver + Bruneau) + + * Remove executable permission on AFHTTPClient source files (Andrew + Sardone) + + * Fix warning (error with -Werror) on implicit 64 to 32 conversion (Dan + Weeks) + + * Add GitHub's .gitignore file (Nate Stedman) + + * Updates to README (@ckmcc) + +## [1.0](https://github.com/AFNetworking/AFNetworking/releases/tag/1.0) / 2012-10-15 + + * AFNetworking now requires iOS 5 / Mac OSX 10.7 or higher (Mattt Thompson) + + * AFNetworking now uses Automatic Reference Counting (ARC) (Mattt Thompson) + + * AFNetworking raises compiler warnings for missing features when +SystemConfiguration or CoreServices / MobileCoreServices frameworks are not +included in the project and imported in the precompiled headers (Mattt +Thompson) + + * AFNetworking now raises compiler error when not compiled with ARC (Steven +Fisher) + + * Add `NSCoding` and `NSCopying` protocol conformance to +`AFURLConnectionOperation` and `AFHTTPClient` (Mattt Thompson) + + * Add substantial improvements HTTP multipart streaming support, having +files streamed directly from disk and read sequentially from a custom input +stream (Max Lansing, Stan Chang Khin Boon, Mattt Thompson) + + * Add `AFMultipartFormData -throttleBandwidthWithPacketSize:delay:` as +workaround to issues when uploading over 3G (Mattt Thompson) + + * Add request and response to `userInfo` of errors returned from failing +`AFHTTPRequestOperation` (Mattt Thompson) + + * Add `userInfo` dictionary with current status in reachability changes +(Mattt Thompson) + + * Add `Accept` header for image requests in `UIImageView` category (Bratley +Lower) + + * Add explicit declaration of `NSURLConnection` delegate methods so that +they can be overridden in subclasses (Mattt Thompson, Evan Grim) + + * Add parameter validation to match conditions specified in documentation +(Jason Brennan, Mattt Thompson) + + * Add import to `UIKit` to avoid build errors from `UIDevice` references in +`User-Agent` default header (Blake Watters) + + * Remove `AFJSONUtilities` in favor of `NSJSONSerialization` (Mattt Thompson) + + * Remove `extern` declaration of `AFURLEncodedStringFromStringWithEncoding` +function (`CFURLCreateStringByAddingPercentEscapes` should be used instead) +(Mattt Thompson) + + * Remove `setHTTPShouldHandleCookies:NO` from `AFHTTPClient` (@phamsonha, +Mattt Thompson) + + * Remove `dispatch_retain` / `dispatch_release` with ARC in iOS 6 (Benoit +Bourdon) + + * Fix threading issue with `AFNetworkActivityIndicatorManager` (Eric Patey) + + * Fix issue where `AFNetworkActivityIndicatorManager` count could become +negative (@ap4y) + + * Fix properties to explicitly set options to suppress warnings (Wen-Hao +Lue, Mattt Thompson) + + * Fix compiler warning caused by mismatched types in upload / download +progress blocks (Gareth du Plooy, tomas.a) + + * Fix weak / strong variable relationships in `completionBlock` (Peter +Steinberger) + + * Fix string formatting syntax warnings caused by type mismatch (David +Keegan, Steven Fisher, George Cox) + + * Fix minor potential security vulnerability by explicitly using string +format in NSError localizedDescription value in userInfo (Steven Fisher) + + * Fix `AFURLConnectionOperation -pause` by adding state checks to prevent +likely memory issues when resuming (Mattt Thompson) + + * Fix warning caused by miscast of type when +`CLANG_WARN_IMPLICIT_SIGN_CONVERSION` is set (Steven Fisher) + + * Fix incomplete implementation warning in example code (Steven Fisher) + + * Fix warning caused by using `==` comparator on floats (Steven Fisher) + + * Fix iOS 4 bug where file URLs return `NSURLResponse` rather than +`NSHTTPURLResponse` objects (Leo Lobato) + + * Fix calculation of finished operations in batch operation progress +callback (Mattt Thompson) + + * Fix documentation typos (Steven Fisher, Matthias Wessendorf, +jorge@miv.uk.com) + + * Fix `hasAcceptableStatusCode` to return true after a network failure (Tony +Million) + + * Fix warning about missing prototype for private static method (Stephan +Diederich) + + * Fix issue where `nil` content type resulted in unacceptable content type +(Mattt Thompson) + + * Fix bug related to setup and scheduling of output stream (Stephen Tramer) + + * Fix AFContentTypesFromHTTPHeader to correctly handle comma-delimited +content types (Peyman, Mattt Thompson, @jsm174) + + * Fix crash caused by `_networkReachability` not being set to `NULL` after +releasing (Blake Watters) + + * Fix Podspec to correctly import required headers and use ARC (Eloy Durán, +Blake Watters) + + * Fix query string parameter escaping to leave square brackets unescaped +(Mattt Thompson) + + * Fix query string parameter encoding of `NSNull` values (Daniel Rinser) + + * Fix error caused by referencing `__IPHONE_OS_VERSION_MIN_REQUIRED` without +importing `Availability.h` (Blake Watters) + + * Update example to use App.net API, as Twitter shut off its unauthorized +access to the public timeline (Mattt Thompson) + + * Update `AFURLConnectionOperation` to replace `NSAutoReleasePool` with +`@autoreleasepool` (Mattt Thompson) + + * Update `AFHTTPClient` operation queue to specify +`NSOperationQueueDefaultMaxConcurrentOperationCount` rather than +previously-defined constant (Mattt Thompson) + + * Update `AFHTTPClient -initWithBaseURL` to automatically append trailing +slash, so as to fix common issue where default path is not respected without +trailing slash (Steven Fisher) + + * Update default `AFHTTPClient` `User-Agent` header strings (Mattt Thompson, +Steven Fisher) + + * Update icons for iOS example application (Mattt Thompson) + + * Update `numberOfCompletedOperations` variable in progress block to be +renamed to `numberOfFinishedOperations` (Mattt Thompson) + + +## 0.10.0 / 2012-06-26 + + * Add Twitter Mac Example application (Mattt Thompson) + + * Add note in README about how to set `-fno-objc-arc` flag for multiple files + at once (Pål Brattberg) + + * Add note in README about 64-bit architecture requirement (@rmuginov, Mattt + Thompson) + + * Add note in `AFNetworkActivityIndicatorManager` about not having to manually + manage animation state (Mattt Thompson) + + * Add missing block parameter name for `imageProcessingBlock` (Francois + Lambert) + + * Add NextiveJson to list of supported JSON libraries (Mattt Thompson) + + * Restore iOS 4.0 compatibility with `addAcceptableStatusCodes:` and + `addAcceptableContentTypes:` (Zachary Waldowski) + + * Update `AFHTTPClient` to use HTTP pipelining for `GET` and `HEAD` requests by + default (Mattt Thompson) + + * Remove @private ivar declaration in headers (Peter Steinberger, Mattt + Thompson) + + * Fix potential premature deallocation of _skippedCharacterSet (Tom Wanielista, + Mattt Thompson) + + * Fix potential issue in `setOutputStream` by closing any existing + `outputStream` (Mattt Thompson) + + * Fix filename in AFHTTPClient header (Steven Fisher) + + * Fix documentation for UIImageView+AFNetworking (Mattt Thompson) + + * Fix HTTP multipart form format, which caused issues with Tornado web server + (Matt Chen) + + * Fix `AFHTTPClient` to not append empty data into multipart form data (Jon + Parise) + + * Fix URL encoding normalization to not conditionally escape percent-encoded + strings (João Prado Maia, Kendall Helmstetter Gelner, @cysp, Mattt Thompson) + + * Fix `AFHTTPClient` documentation reference of + `HTTPRequestOperationWithRequest:success:failure` (Shane Vitarana) + + * Add `AFURLRequestOperation -setRedirectResponseBlock:` (Kevin Harwood) + + * Fix `AFURLConnectionOperation` compilation error by conditionally importing + UIKit framework (Steven Fisher) + + * Fix issue where image processing block is not called correctly with success + block in `AFImageRequestOperation` (Sergey Gavrilyuk) + + * Fix leaked dispatch group in batch operations (@andyegorov, Mattt Thompson) + + * Fix support for non-LLVM compilers in `AFNetworkActivityIndicatorManager` + (Abraham Vegh, Bill Williams, Mattt Thompson) + + * Fix AFHTTPClient to not add unnecessary data when constructing multipart form + request with nil parameters (Taeho Kim) + +## 1.0RC1 / 2012-04-25 + + * Add `AFHTTPRequestOperation +addAcceptableStatusCodes / ++addAcceptableContentTypes` to dynamically add acceptable status codes and +content types on the class level (Mattt Thompson) + + * Add support for compound and complex `Accept` headers that include multiple +content types and / or specify a particular character encoding (Mattt Thompson) + + * Add `AFURLConnectionOperation +-setShouldExecuteAsBackgroundTaskWithExpirationHandler:` to have operations +finish once an app becomes inactive (Mattt Thompson) + + * Add support for pausing / resuming request operations (Peter Steinberger, +Mattt Thompson) + + * Improve network reachability functionality in `AFHTTPClient`, including a +distinction between WWan and WiFi reachability (Kevin Harwood, Mattt Thompson) + + +## 0.9.2 / 2012-04-25 + + * Add thread safety to `AFNetworkActivityIndicator` (Peter Steinberger, Mattt +Thompson) + + * Document requirement of available JSON libraries for decoding responses in +`AFJSONRequestOperation` and parameter encoding in `AFHTTPClient` (Mattt +Thompson) + + * Fix `AFHTTPClient` parameter encoding (Mattt Thompson) + + * Fix `AFJSONEncode` and `AFJSONDecode` to use `SBJsonWriter` and +`SBJsonParser` instead of `NSObject+SBJson` (Oliver Eikemeier) + + * Fix bug where `AFJSONDecode` does not return errors (Alex Michaud) + + * Fix compiler warning for undeclared +`AFQueryStringComponentFromKeyAndValueWithEncoding` function (Mattt Thompson) + + * Fix cache policy for URL requests (Peter Steinberger) + + * Fix race condition bug in `UIImageView+AFNetworking` caused by incorrectly +nil-ing request operations (John Wu) + + * Fix reload button in Twitter example (Peter Steinberger) + + * Improve batched operation by deferring execution of batch completion block +until all component request completion blocks have finished (Patrick Hernandez, +Kevin Harwood, Mattt Thompson) + + * Improve performance of image request decoding by dispatching to background + queue (Mattt Thompson) + + * Revert `AFImageCache` to cache image objects rather than `NSPurgeableData` +(Tony Million, Peter Steinberger, Mattt Thompson) + + * Remove unnecessary KVO `willChangeValueForKey:` / `didChangeValueForKey:` +calls (Peter Steinberger) + + * Remove unnecessary @private ivar declarations in headers (Peter Steinberger, +Mattt Thompson) + + * Remove @try-@catch block wrapping network thread entry point (Charles T. Ahn) + + +## 0.9.1 / 2012-03-19 + + * Create Twitter example application (Mattt Thompson) + + * Add support for nested array and dictionary parameters for query string and +form-encoded requests (Mathieu Hausherr, Josh Chung, Mattt Thompson) + + * Add `AFURLConnectionOperation -setCacheResponseBlock:`, which allows the +behavior of the `NSURLConnectionDelegate` method +`-connection:willCacheResponse:` to be overridden without subclassing (Mattt +Thompson) + + * Add `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` macros for +NSURLConnection authentication delegate methods (Mattt Thompson) + + * Add properties for custom success / failure callback queues (Peter +Steinberger) + + * Add notifications for network reachability changes to `AFHTTPClient` (Mattt +Thompson) + + * Add `AFHTTPClient -patchPath:` convenience method (Mattt Thompson) + + * Add support for NextiveJson (Adrian Kosmaczewski) + + * Improve network reachability checks (C. Bess) + + * Improve NSIndexSet formatting in error strings (Jon Parise) + + * Document crashing behavior in iOS 4 loading a file:// URL (Mattt Thompson) + + * Fix crash caused by `AFHTTPClient -cancelAllHTTPOperationsWithMethod:` not +checking operation to be instance of `AFHTTPRequestOperation` (Mattt Thompson) + + * Fix crash caused by passing `nil` URL in requests (Sam Soffes) + + * Fix errors caused by connection property not being nil'd out after an +operation finishes (Kevin Harwood, @zdzisiekpu) + + * Fix crash caused by passing `NULL` error pointer when setting `NSInvocation` +in `AFJSONEncode` and `AFJSONDecode` (Tyler Stromberg) + + * Fix batch operation completion block returning on background thread (Patrick +Hernandez) + + * Fix documentation for UIImageView+AFNetworking (Dominic Dagradi) + + * Fix race condition caused by `AFURLConnectionOperation` being cancelled on +main thread, rather than network thread (Erik Olsson) + + * Fix `AFURLEncodedStringFromStringWithEncoding` to correctly handle cases +where % is used as a literal rather than as part of a percent escape code +(Mattt Thompson) + + * Fix missing comma in `+defaultAcceptableContentTypes` for +`AFImageRequestOperation` (Michael Schneider) + + +## 0.9.0 / 2012-01-23 + + * Add thread-safe behavior to `AFURLConnectionOperation` (Mattt Thompson) + + * Add batching of operations for `AFHTTPClient` (Mattt Thompson) + + * Add authentication challenge callback block to override default + implementation of `connection:didReceiveAuthenticationChallenge:` in + `AFURLConnectionOperation` (Mattt Thompson) + + * Add `_AFNETWORKING_PREFER_NSJSONSERIALIZATION_`, which, when defined, + short-circuits the standard preference ordering used in `AFJSONEncode` and + `AFJSONDecode` to use `NSJSONSerialization` when available, falling back on + third-party-libraries. (Mattt Thompson, Shane Vitarana) + + * Add custom `description` for `AFURLConnectionOperation` and `AFHTTPClient` + (Mattt Thompson) + + * Add `text/javascript` to default acceptable content types for + `AFJSONRequestOperation` (Jake Boxer) + + * Add `imageScale` property to change resolution of images constructed from + cached data (Štěpán Petrů) + + * Add note about third party JSON libraries in README (David Keegan) + + * `AFQueryStringFromParametersWithEncoding` formats `NSArray` values in the + form `key[]=value1&key[]=value2` instead of `key=(value1,value2)` (Dan Thorpe) + + * `AFImageRequestOperation -responseImage` on OS X uses `NSBitmapImageRep` to + determine the correct pixel dimensions of the image (David Keegan) + + * `AFURLConnectionOperation` `connection` has memory management policy `assign` + to avoid retain cycles caused by `NSURLConnection` retaining its delegate + (Mattt Thompson) + + * `AFURLConnectionOperation` calls super implementation for `-isReady`, + following the guidelines for `NSOperation` subclasses (Mattt Thompson) + + * `UIImageView -setImageWithURL:` and related methods call success callback + after setting image (Cameron Boehmer) + + * Cancel request if an authentication challenge has no suitable credentials in + `AFURLConnectionOperation -connection:didReceiveAuthenticationChallenge:` + (Jorge Bernal) + + * Remove exception from + `multipartFormRequestWithMethod:path:parameters:constructing BodyWithBlock:` + raised when certain HTTP methods are used. (Mattt Thompson) + + * Remove `AFImageCache` from public API, moving it into private implementation + of `UIImageView+AFNetworking` (Mattt Thompson) + + * Mac example application makes better use of AppKit technologies and + conventions (Mattt Thompson) + + * Fix issue with multipart form boundaries in `AFHTTPClient + -multipartFormRequestWithMethod:path:parameters:constructing BodyWithBlock:` + (Ray Morgan, Mattt Thompson, Sam Soffes) + + * Fix "File Upload with Progress Callback" code snippet in README (Larry +Legend) + + * Fix to SBJSON invocations in `AFJSONEncode` and `AFJSONDecode` (Matthias + Tretter, James Frye) + + * Fix documentation for `AFHTTPClient requestWithMethod:path:parameters:` + (Michael Parker) + + * Fix `Content-Disposition` headers used for multipart form construction + (Michael Parker) + + * Add network reachability status change callback property to `AFHTTPClient`. + (Mattt Thompson, Kevin Harwood) + + * Fix exception handling in `AFJSONEncode` and `AFJSONDecode` (David Keegan) + + * Fix `NSData` initialization with string in `AFBase64EncodedStringFromString` + (Adam Ernst, Mattt Thompson) + + * Fix error check in `appendPartWithFileURL:name:error:` (Warren Moore, + Baldoph, Mattt Thompson) + + * Fix compiler warnings for certain configurations (Charlie Williams) + + * Fix bug caused by passing zero-length `responseData` to response object + initializers (Mattt Thompson, Serge Paquet) diff --git a/its/plugin/projects/AFNetworking/CONTRIBUTING.md b/its/plugin/projects/AFNetworking/CONTRIBUTING.md new file mode 100644 index 00000000..9bb98ead --- /dev/null +++ b/its/plugin/projects/AFNetworking/CONTRIBUTING.md @@ -0,0 +1,96 @@ +# Contributing Guidelines + +This document contains information and guidelines about contributing to this project. +Please read it before you start participating. + +**Topics** + +* [Asking Questions](#asking-questions) +* [Reporting Security Issues](#reporting-security-issues) +* [Reporting Issues](#reporting-other-issues) +* [Submitting Pull Requests](#submitting-pull-requests) +* [Developers Certificate of Origin](#developers-certificate-of-origin) +* [Code of Conduct](#code-of-conduct) + +## Asking Questions + +We don't use GitHub as a support forum. +For any usage questions that are not specific to the project itself, +please ask on [Stack Overflow](https://stackoverflow.com) instead. +By doing so, you'll be more likely to quickly solve your problem, +and you'll allow anyone else with the same question to find the answer. +This also allows maintainers to focus on improving the project for others. + +## Reporting Security Issues + +The Alamofire Software Foundation takes security seriously. +If you discover a security issue, please bring it to our attention right away! + +Please **DO NOT** file a public issue, +instead send your report privately to . +This will help ensure that any vulnerabilities that _are_ found +can be [disclosed responsibly](http://en.wikipedia.org/wiki/Responsible_disclosure) +to any affected parties. + +## Reporting Other Issues + +A great way to contribute to the project +is to send a detailed issue when you encounter an problem. +We always appreciate a well-written, thorough bug report. + +Check that the project issues database +doesn't already include that problem or suggestion before submitting an issue. +If you find a match, add a quick "+1" or "I have this problem too." +Doing this helps prioritize the most common problems and requests. + +When reporting issues, please include the following: + +* The version of Xcode you're using +* The version of iOS or OS X you're targeting +* The full output of any stack trace or compiler error +* A code snippet that reproduces the described behavior, if applicable +* Any other details that would be useful in understanding the problem + +This information will help us review and fix your issue faster. + +## Submitting Pull Requests + +Pull requests are welcome, and greatly encouraged. When submitting a pull request, please create proper test cases demonstrating the issue to be fixed or the new feature. + +## Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +- (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +- (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +- (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +- (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. + +## Code of Conduct + +The Code of Conduct governs how we behave in public or in private +whenever the project will be judged by our actions. +We expect it to be honored by everyone who contributes to this project. + +See [CONDUCT.md](https://github.com/Alamofire/Foundation/blob/master/CONDUCT.md) for details. + +--- + +*Some of the ideas and wording for the statements above were based on work by the [Docker](https://github.com/docker/docker/blob/master/CONTRIBUTING.md) and [Linux](http://elinux.org/Developer_Certificate_Of_Origin) communities. We commend them for their efforts to facilitate collaboration in their projects.* diff --git a/its/plugin/projects/AFNetworking/Framework/AFNetworking.h b/its/plugin/projects/AFNetworking/Framework/AFNetworking.h new file mode 100644 index 00000000..61a17eb8 --- /dev/null +++ b/its/plugin/projects/AFNetworking/Framework/AFNetworking.h @@ -0,0 +1,66 @@ +// AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import + +//! Project version number for AFNetworking. +FOUNDATION_EXPORT double AFNetworkingVersionNumber; + +//! Project version string for AFNetworking. +FOUNDATION_EXPORT const unsigned char AFNetworkingVersionString[]; + +// In this header, you should import all the public headers of your framework using statements like #import + +#import +#import + +#ifndef _AFNETWORKING_ +#define _AFNETWORKING_ + +#import +#import +#import + +#if !TARGET_OS_WATCH +#import +#endif + +#import +#import + +#if TARGET_OS_IOS || TARGET_OS_TV +#import +#import +#import +#import +#import +#import +#import +#endif + +#if TARGET_OS_IOS +#import +#import +#import +#endif + + +#endif /* _AFNETWORKING_ */ diff --git a/its/plugin/projects/AFNetworking/Framework/Info.plist b/its/plugin/projects/AFNetworking/Framework/Info.plist new file mode 100644 index 00000000..2a327732 --- /dev/null +++ b/its/plugin/projects/AFNetworking/Framework/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + FMWK + CFBundleShortVersionString + 3.0.0 + CFBundleSignature + ???? + CFBundleVersion + 3.0.4 + NSPrincipalClass + + + diff --git a/its/plugin/projects/AFNetworking/Framework/module.modulemap b/its/plugin/projects/AFNetworking/Framework/module.modulemap new file mode 100644 index 00000000..a9200e1d --- /dev/null +++ b/its/plugin/projects/AFNetworking/Framework/module.modulemap @@ -0,0 +1,5 @@ +framework module AFNetworking { + umbrella header "AFNetworking.h" + export * + module * { export * } +} \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/LICENSE b/its/plugin/projects/AFNetworking/LICENSE new file mode 100644 index 00000000..3fbc2c9a --- /dev/null +++ b/its/plugin/projects/AFNetworking/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) + +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. diff --git a/its/plugin/projects/AFNetworking/README.md b/its/plugin/projects/AFNetworking/README.md new file mode 100644 index 00000000..53cb2024 --- /dev/null +++ b/its/plugin/projects/AFNetworking/README.md @@ -0,0 +1,320 @@ +

+ AFNetworking +

+ +[![Build Status](https://travis-ci.org/AFNetworking/AFNetworking.svg)](https://travis-ci.org/AFNetworking/AFNetworking) +[![codecov.io](https://codecov.io/github/AFNetworking/AFNetworking/coverage.svg?branch=master)](https://codecov.io/github/AFNetworking/AFNetworking?branch=master) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/AFNetworking.svg)](https://img.shields.io/cocoapods/v/AFNetworking.svg) +[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Platform](https://img.shields.io/cocoapods/p/AFNetworking.svg?style=flat)](http://cocoadocs.org/docsets/AFNetworking) +[![Twitter](https://img.shields.io/badge/twitter-@AFNetworking-blue.svg?style=flat)](http://twitter.com/AFNetworking) + +AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of the [Foundation URL Loading System](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html), extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use. + +Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac. + +Choose AFNetworking for your next project, or migrate over your existing projects—you'll be happy you did! + +## How To Get Started + +- [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/archive/master.zip) and try out the included Mac and iPhone example apps +- Read the ["Getting Started" guide](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking), [FAQ](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ), or [other articles on the Wiki](https://github.com/AFNetworking/AFNetworking/wiki) +- Check out the [documentation](http://cocoadocs.org/docsets/AFNetworking/) for a comprehensive look at all of the APIs available in AFNetworking +- Read the [AFNetworking 3.0 Migration Guide](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-3.0-Migration-Guide) for an overview of the architectural changes from 2.0. + +## Communication + +- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). (Tag 'afnetworking') +- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). +- If you **found a bug**, _and can provide steps to reliably reproduce it_, open an issue. +- If you **have a feature request**, open an issue. +- If you **want to contribute**, submit a pull request. + +## Installation +AFNetworking supports multiple methods for installing the library in a project. + +## Installation with CocoaPods + +[CocoaPods](http://cocoapods.org) is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries like AFNetworking in your projects. See the ["Getting Started" guide for more information](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking). You can install it with the following command: + +```bash +$ gem install cocoapods +``` + +> CocoaPods 0.39.0+ is required to build AFNetworking 3.0.0+. + +#### Podfile + +To integrate AFNetworking into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '8.0' + +pod 'AFNetworking', '~> 3.0' +``` + +Then, run the following command: + +```bash +$ pod install +``` + +### Installation with Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. + +You can install Carthage with [Homebrew](http://brew.sh/) using the following command: + +```bash +$ brew update +$ brew install carthage +``` + +To integrate AFNetworking into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "AFNetworking/AFNetworking" ~> 3.0 +``` + +Run `carthage` to build the framework and drag the built `AFNetworking.framework` into your Xcode project. + +## Requirements + +| AFNetworking Version | Minimum iOS Target | Minimum OS X Target | Minimum watchOS Target | Minimum tvOS Target | Notes | +|:--------------------:|:---------------------------:|:----------------------------:|:----------------------------:|:----------------------------:|:-------------------------------------------------------------------------:| +| 3.x | iOS 7 | OS X 10.9 | watchOS 2.0 | tvOS 9.0 | Xcode 7+ is required. `NSURLConnectionOperation` support has been removed. | +| 2.6 -> 2.6.3 | iOS 7 | OS X 10.9 | watchOS 2.0 | n/a | Xcode 7+ is required. | +| 2.0 -> 2.5.4 | iOS 6 | OS X 10.8 | n/a | n/a | Xcode 5+ is required. `NSURLSession` subspec requires iOS 7 or OS X 10.9. | +| 1.x | iOS 5 | Mac OS X 10.7 | n/a | n/a | +| 0.10.x | iOS 4 | Mac OS X 10.6 | n/a | n/a | + +(OS X projects must support [64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)). + +> Programming in Swift? Try [Alamofire](https://github.com/Alamofire/Alamofire) for a more conventional set of APIs. + +## Architecture + +### NSURLSession + +- `AFURLSessionManager` +- `AFHTTPSessionManager` + +### Serialization + +* `` + - `AFHTTPRequestSerializer` + - `AFJSONRequestSerializer` + - `AFPropertyListRequestSerializer` +* `` + - `AFHTTPResponseSerializer` + - `AFJSONResponseSerializer` + - `AFXMLParserResponseSerializer` + - `AFXMLDocumentResponseSerializer` _(Mac OS X)_ + - `AFPropertyListResponseSerializer` + - `AFImageResponseSerializer` + - `AFCompoundResponseSerializer` + +### Additional Functionality + +- `AFSecurityPolicy` +- `AFNetworkReachabilityManager` + +## Usage + +### AFURLSessionManager + +`AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to ``, ``, ``, and ``. + +#### Creating a Download Task + +```objective-c +NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; +AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; + +NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"]; +NSURLRequest *request = [NSURLRequest requestWithURL:URL]; + +NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { + NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; + return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; +} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { + NSLog(@"File downloaded to: %@", filePath); +}]; +[downloadTask resume]; +``` + +#### Creating an Upload Task + +```objective-c +NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; +AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; + +NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"]; +NSURLRequest *request = [NSURLRequest requestWithURL:URL]; + +NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"]; +NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + if (error) { + NSLog(@"Error: %@", error); + } else { + NSLog(@"Success: %@ %@", response, responseObject); + } +}]; +[uploadTask resume]; +``` + +#### Creating an Upload Task for a Multi-Part Request, with Progress + +```objective-c +NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) { + [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil]; + } error:nil]; + +AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + +NSURLSessionUploadTask *uploadTask; +uploadTask = [manager + uploadTaskWithStreamedRequest:request + progress:^(NSProgress * _Nonnull uploadProgress) { + // This is not called back on the main queue. + // You are responsible for dispatching to the main queue for UI updates + dispatch_async(dispatch_get_main_queue(), ^{ + //Update the progress view + [progressView setProgress:uploadProgress.fractionCompleted]; + }); + } + completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + if (error) { + NSLog(@"Error: %@", error); + } else { + NSLog(@"%@ %@", response, responseObject); + } + }]; + +[uploadTask resume]; +``` + +#### Creating a Data Task + +```objective-c +NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; +AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; + +NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"]; +NSURLRequest *request = [NSURLRequest requestWithURL:URL]; + +NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + if (error) { + NSLog(@"Error: %@", error); + } else { + NSLog(@"%@ %@", response, responseObject); + } +}]; +[dataTask resume]; +``` + +--- + +### Request Serialization + +Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body. + +```objective-c +NSString *URLString = @"http://example.com"; +NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]}; +``` + +#### Query String Parameter Encoding + +```objective-c +[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil]; +``` + + GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3 + +#### URL Form Parameter Encoding + +```objective-c +[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil]; +``` + + POST http://example.com/ + Content-Type: application/x-www-form-urlencoded + + foo=bar&baz[]=1&baz[]=2&baz[]=3 + +#### JSON Parameter Encoding + +```objective-c +[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil]; +``` + + POST http://example.com/ + Content-Type: application/json + + {"foo": "bar", "baz": [1,2,3]} + +--- + +### Network Reachability Manager + +`AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. + +* Do not use Reachability to determine if the original request should be sent. + * You should try to send it. +* You can use Reachability to determine when a request should be automatically retried. + * Although it may still fail, a Reachability notification that the connectivity is available is a good time to retry something. +* Network reachability is a useful tool for determining why a request might have failed. + * After a network request has failed, telling the user they're offline is better than giving them a more technical but accurate error, such as "request timed out." + +See also [WWDC 2012 session 706, "Networking Best Practices."](https://developer.apple.com/videos/play/wwdc2012-706/). + +#### Shared Network Reachability + +```objective-c +[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { + NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status)); +}]; + +[[AFNetworkReachabilityManager sharedManager] startMonitoring]; +``` + +--- + +### Security Policy + +`AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. + +Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled. + +#### Allowing Invalid SSL Certificates + +```objective-c +AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; +manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production +``` + +--- + +## Unit Tests + +AFNetworking includes a suite of unit tests within the Tests subdirectory. These tests can be run simply be executed the test action on the platform framework you would like to test. + +## Credits + +AFNetworking is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). + +AFNetworking was originally created by [Scott Raymond](https://github.com/sco/) and [Mattt Thompson](https://github.com/mattt/) in the development of [Gowalla for iPhone](http://en.wikipedia.org/wiki/Gowalla). + +AFNetworking's logo was designed by [Alan Defibaugh](http://www.alandefibaugh.com/). + +And most of all, thanks to AFNetworking's [growing list of contributors](https://github.com/AFNetworking/AFNetworking/contributors). + +### Security Disclosure + +If you believe you have identified a security vulnerability with AFNetworking, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## License + +AFNetworking is released under the MIT license. See LICENSE for details. diff --git a/its/plugin/projects/AFNetworking/Tests/Info.plist b/its/plugin/projects/AFNetworking/Tests/Info.plist new file mode 100644 index 00000000..32379bec --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Info.plist @@ -0,0 +1,22 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + com.alamofire.afnetworking.${PRODUCT_NAME:rfc1034identifier} + CFBundleInfoDictionaryVersion + 6.0 + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + + diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_0.cer b/its/plugin/projects/AFNetworking/Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_0.cer new file mode 100644 index 00000000..5cbf610f Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_0.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_1.cer b/its/plugin/projects/AFNetworking/Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_1.cer new file mode 100644 index 00000000..683d5ff3 Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_1.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_2.cer b/its/plugin/projects/AFNetworking/Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_2.cer new file mode 100644 index 00000000..dae01965 Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_2.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/Equifax_Secure_Certificate_Authority_Root.cer b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/Equifax_Secure_Certificate_Authority_Root.cer new file mode 100644 index 00000000..c44db274 Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/Equifax_Secure_Certificate_Authority_Root.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GeoTrust_Global_CA-cross.cer b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GeoTrust_Global_CA-cross.cer new file mode 100644 index 00000000..82e50046 Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GeoTrust_Global_CA-cross.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GeoTrust_Global_CA_Root.cer b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GeoTrust_Global_CA_Root.cer new file mode 100644 index 00000000..4ae42e81 Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GeoTrust_Global_CA_Root.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath1/googlecom_0.cer b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath1/googlecom_0.cer new file mode 100644 index 00000000..ab4002a2 Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath1/googlecom_0.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath1/googlecom_1.cer b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath1/googlecom_1.cer new file mode 100644 index 00000000..521e4393 Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath1/googlecom_1.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath2/googlecom_0.cer b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath2/googlecom_0.cer new file mode 100644 index 00000000..ab4002a2 Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath2/googlecom_0.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath2/googlecom_1.cer b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath2/googlecom_1.cer new file mode 100644 index 00000000..521e4393 Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath2/googlecom_1.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath2/googlecom_2.cer b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath2/googlecom_2.cer new file mode 100644 index 00000000..82e50046 Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath2/googlecom_2.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleInternetAuthorityG2.cer b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleInternetAuthorityG2.cer new file mode 100644 index 00000000..521e4393 Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleInternetAuthorityG2.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/google.com.cer b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/google.com.cer new file mode 100644 index 00000000..ab4002a2 Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/google.com.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/AddTrust_External_CA_Root.cer b/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/AddTrust_External_CA_Root.cer new file mode 100644 index 00000000..8a99c54a Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/AddTrust_External_CA_Root.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/COMODO_RSA_Certification_Authority.cer b/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/COMODO_RSA_Certification_Authority.cer new file mode 100644 index 00000000..ad75f0fc Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/COMODO_RSA_Certification_Authority.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/COMODO_RSA_Domain_Validation_Secure_Server_CA.cer b/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/COMODO_RSA_Domain_Validation_Secure_Server_CA.cer new file mode 100644 index 00000000..7d7e8f27 Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/COMODO_RSA_Domain_Validation_Secure_Server_CA.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_0.cer b/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_0.cer new file mode 100644 index 00000000..e2a2a3a1 Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_0.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_1.cer b/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_1.cer new file mode 100644 index 00000000..7d7e8f27 Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_1.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_2.cer b/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_2.cer new file mode 100644 index 00000000..ad75f0fc Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_2.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_3.cer b/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_3.cer new file mode 100644 index 00000000..8a99c54a Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_3.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/httpbinorg_01192017.cer b/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/httpbinorg_01192017.cer new file mode 100644 index 00000000..e2a2a3a1 Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/httpbinorg_01192017.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/SelfSigned/AltName.cer b/its/plugin/projects/AFNetworking/Tests/Resources/SelfSigned/AltName.cer new file mode 100644 index 00000000..3ba9d337 Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/SelfSigned/AltName.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/SelfSigned/NoDomains.cer b/its/plugin/projects/AFNetworking/Tests/Resources/SelfSigned/NoDomains.cer new file mode 100644 index 00000000..6b6cce65 Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/SelfSigned/NoDomains.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/SelfSigned/foobar.com.cer b/its/plugin/projects/AFNetworking/Tests/Resources/SelfSigned/foobar.com.cer new file mode 100644 index 00000000..a9ca08ea Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/SelfSigned/foobar.com.cer differ diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/logo.png b/its/plugin/projects/AFNetworking/Tests/Resources/logo.png new file mode 100644 index 00000000..4fc5a3c9 Binary files /dev/null and b/its/plugin/projects/AFNetworking/Tests/Resources/logo.png differ diff --git a/its/plugin/projects/AFNetworking/Tests/Tests-Prefix.pch b/its/plugin/projects/AFNetworking/Tests/Tests-Prefix.pch new file mode 100644 index 00000000..eb2007ec --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests-Prefix.pch @@ -0,0 +1,9 @@ +// +// Prefix header +// +// The contents of this file are implicitly included at the beginning of every source file. +// + +#ifdef __OBJC__ + #import +#endif diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFAutoPurgingImageCacheTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFAutoPurgingImageCacheTests.m new file mode 100644 index 00000000..add2301f --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFAutoPurgingImageCacheTests.m @@ -0,0 +1,233 @@ +// AFAutoPurgingImageCacheTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import +#import "AFAutoPurgingImageCache.h" + +@interface AFAutoPurgingImageCacheTests : XCTestCase +@property (nonatomic, strong) AFAutoPurgingImageCache *cache; +@property (nonatomic, strong) UIImage *testImage; +@end + +@implementation AFAutoPurgingImageCacheTests + +- (void)setUp { + [super setUp]; + self.cache = [[AFAutoPurgingImageCache alloc] initWithMemoryCapacity:100 * 1024 * 1024 + preferredMemoryCapacity:60 * 1024 * 1024]; + + NSString *path = [[NSBundle bundleForClass:[self class]] pathForResource:@"logo" ofType:@"png"]; + self.testImage = [UIImage imageWithContentsOfFile:path]; + + +} + +- (void)tearDown { + [self.cache removeAllImages]; + self.cache = nil; + self.testImage = nil; + [super tearDown]; +} + +#pragma mark - Cache Return Images + +- (void)testImageIsReturnedFromCacheForIdentifier { + NSString *identifier = @"logo"; + [self.cache addImage:self.testImage withIdentifier:identifier]; + + UIImage *cachedImage = [self.cache imageWithIdentifier:identifier]; + XCTAssertEqual(self.testImage, cachedImage, @"Cached image should equal original image"); +} + +- (void)testImageIsReturnedFromCacheForURLRequest { + NSURL *url = [NSURL URLWithString:@"http://test.com/image"]; + NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; + [self.cache addImage:self.testImage forRequest:request withAdditionalIdentifier:nil]; + + UIImage *cachedImage = [self.cache imageforRequest:request withAdditionalIdentifier:nil]; + XCTAssertEqual(self.testImage, cachedImage, @"Cached image should equal original image"); +} + +- (void)testImageIsReturnedFromCacheForURLRequestWithAdditionalIdentifier { + NSURL *url = [NSURL URLWithString:@"http://test.com/image"]; + NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; + NSString *additionalIdentifier = @"filter"; + [self.cache addImage:self.testImage forRequest:request withAdditionalIdentifier:additionalIdentifier]; + + UIImage *cachedImage = [self.cache imageforRequest:request withAdditionalIdentifier:additionalIdentifier]; + XCTAssertEqual(self.testImage, cachedImage, @"Cached image should equal original image"); +} + +- (void)testImageIsNotReturnedWhenAdditionalIdentifierIsNotSet { + NSURL *url = [NSURL URLWithString:@"http://test.com/image"]; + NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; + NSString *additionalIdentifier = @"filter"; + [self.cache addImage:self.testImage forRequest:request withAdditionalIdentifier:additionalIdentifier]; + + UIImage *cachedImage = [self.cache imageforRequest:request withAdditionalIdentifier:nil]; + XCTAssertNil(cachedImage, @"cached image should be nil"); +} + +- (void)testImageIsNotReturnedWhenURLDoesntMatch { + NSURL *url = [NSURL URLWithString:@"http://test.com/image"]; + NSURLRequest *originalRequest = [[NSURLRequest alloc] initWithURL:url]; + [self.cache addImage:self.testImage forRequest:originalRequest withAdditionalIdentifier:nil]; + + NSURL *newURL = [NSURL URLWithString:@"http://test.com/differentImage"]; + NSURLRequest *newRequest = [[NSURLRequest alloc] initWithURL:newURL]; + UIImage *cachedImage = [self.cache imageforRequest:newRequest withAdditionalIdentifier:nil]; + XCTAssertNil(cachedImage, @"cached image should be nil"); +} + +- (void)testDuplicateImageAddedToCacheIsReturned { + NSURL *url = [NSURL URLWithString:@"http://test.com/image"]; + NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; + [self.cache addImage:self.testImage forRequest:request withAdditionalIdentifier:nil]; + + NSString *path = [[NSBundle bundleForClass:[self class]] pathForResource:@"logo" ofType:@"png"]; + UIImage *newImage = [UIImage imageWithContentsOfFile:path]; + + [self.cache addImage:newImage forRequest:request withAdditionalIdentifier:nil]; + + UIImage *cachedImage = [self.cache imageforRequest:request withAdditionalIdentifier:nil]; + XCTAssertEqual(cachedImage, newImage); + XCTAssertNotEqual(cachedImage, self.testImage); +} + +#pragma mark - Remove Image Tests + +- (void)testImageIsRemovedWithIdentifier { + NSString *identifier = @"logo"; + [self.cache addImage:self.testImage withIdentifier:identifier]; + XCTAssertTrue([self.cache removeImageWithIdentifier:identifier], @"image should be reported as removed"); + XCTAssertFalse([self.cache removeImageWithIdentifier:identifier], @"image should be reported as removed the second time"); + UIImage *cachedImage = [self.cache imageWithIdentifier:identifier]; + XCTAssertNil(cachedImage, @"cached image should be nil"); +} + +- (void)testImageIsRemovedWithURLRequest { + NSURL *url = [NSURL URLWithString:@"http://test.com/image"]; + NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; + [self.cache addImage:self.testImage forRequest:request withAdditionalIdentifier:nil]; + XCTAssertTrue([self.cache removeImageforRequest:request withAdditionalIdentifier:nil], @"image should be reported as removed"); + XCTAssertFalse([self.cache removeImageforRequest:request withAdditionalIdentifier:nil], @"image should be reported as removed the second time"); + UIImage *cachedImage = [self.cache imageforRequest:request withAdditionalIdentifier:nil]; + XCTAssertNil(cachedImage, @"cached image should be nil"); +} + +- (void)testImageIsRemovedWithURLRequestWithAdditionalIdentifier { + NSURL *url = [NSURL URLWithString:@"http://test.com/image"]; + NSString *identifier = @"filter"; + NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; + [self.cache addImage:self.testImage forRequest:request withAdditionalIdentifier:identifier]; + XCTAssertTrue([self.cache removeImageforRequest:request withAdditionalIdentifier:identifier], @"image should be reported as removed"); + XCTAssertFalse([self.cache removeImageforRequest:request withAdditionalIdentifier:identifier], @"image should be reported as removed the second time"); + UIImage *cachedImage = [self.cache imageforRequest:request withAdditionalIdentifier:identifier]; + XCTAssertNil(cachedImage, @"cached image should be nil"); +} + +- (void)testImageIsNotRemovedWithURLRequestAndNilIdentifier { + NSURL *url = [NSURL URLWithString:@"http://test.com/image"]; + NSString *identifier = @"filter"; + NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; + [self.cache addImage:self.testImage forRequest:request withAdditionalIdentifier:identifier]; + XCTAssertFalse([self.cache removeImageforRequest:request withAdditionalIdentifier:nil], @"image should not be reported as removed"); + UIImage *cachedImage = [self.cache imageforRequest:request withAdditionalIdentifier:identifier]; + XCTAssertNotNil(cachedImage, @"cached image should be nil"); +} + +- (void)testImageIsNotRemovedWithURLRequestAndIncorrectIdentifier { + NSURL *url = [NSURL URLWithString:@"http://test.com/image"]; + NSString *identifier = @"filter"; + NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; + [self.cache addImage:self.testImage forRequest:request withAdditionalIdentifier:identifier]; + NSString *differentIdentifier = @"nofilter"; + XCTAssertFalse([self.cache removeImageforRequest:request withAdditionalIdentifier:differentIdentifier], @"image should not be reported as removed"); + UIImage *cachedImage = [self.cache imageforRequest:request withAdditionalIdentifier:identifier]; + XCTAssertNotNil(cachedImage, @"cached image should be nil"); +} + +#pragma mark - Memory Usage +- (void)testThatMemoryUsageIncreasesWhenAddingImage { + NSString *identifier = @"logo"; + XCTAssertTrue(self.cache.memoryUsage == 0); + [self.cache addImage:self.testImage withIdentifier:identifier]; + XCTAssertTrue(self.cache.memoryUsage == 13600); +} + +- (void)testThatMemoryUsageDecreasesWhenRemovingImage { + NSString *identifier = @"logo"; + [self.cache addImage:self.testImage withIdentifier:identifier]; + UInt64 currentUsage = self.cache.memoryUsage; + [self.cache removeImageWithIdentifier:identifier]; + XCTAssertTrue(currentUsage > self.cache.memoryUsage); +} + +#pragma mark - Purging +- (void)testThatImagesArePurgedWhenCapcityIsReached { + UInt64 imageSize = 13600; + NSInteger numberOfImages = 10; + NSInteger numberOfImagesAfterPurge = 6; + self.cache = [[AFAutoPurgingImageCache alloc] initWithMemoryCapacity:numberOfImages * imageSize preferredMemoryCapacity:numberOfImagesAfterPurge * imageSize]; + NSInteger index = 1; + while (YES) { + NSString * identifier = [NSString stringWithFormat:@"image-%ld",(long)index]; + [self.cache addImage:self.testImage withIdentifier:identifier]; + if (index <= numberOfImages) { + XCTAssertTrue(self.cache.memoryUsage == index * imageSize); + } else { + XCTAssertTrue(self.cache.memoryUsage == numberOfImagesAfterPurge * imageSize); + break; + } + index++; + } +} + +- (void)testThatPrioritizedImagesWithOldestLastAccessDatesAreRemovedDuringPurge { + UInt64 imageSize = 13600; + NSInteger numberOfImages = 10; + NSInteger numberOfImagesAfterPurge = 6; + self.cache = [[AFAutoPurgingImageCache alloc] initWithMemoryCapacity:numberOfImages * imageSize preferredMemoryCapacity:numberOfImagesAfterPurge * imageSize]; + for (NSInteger index = 0; index < numberOfImages; index ++) { + NSString * identifier = [NSString stringWithFormat:@"image-%ld",(long)index]; + [self.cache addImage:self.testImage withIdentifier:identifier]; + } + + NSString * firstIdentifier = [NSString stringWithFormat:@"image-%ld",(long)0]; + UIImage *firstImage = [self.cache imageWithIdentifier:firstIdentifier]; + XCTAssertNotNil(firstImage, @"first image should not be nil"); + UInt64 prePurgeMemoryUsage = self.cache.memoryUsage; + [self.cache addImage:self.testImage withIdentifier:[NSString stringWithFormat:@"image-%ld",(long)10]]; + UInt64 postPurgeMemoryUsage = self.cache.memoryUsage; + XCTAssertTrue(postPurgeMemoryUsage < prePurgeMemoryUsage); + + for (NSInteger index = 0; index <= numberOfImages ; index++) { + NSString * identifier = [NSString stringWithFormat:@"image-%ld",(long)index]; + UIImage *cachedImage = [self.cache imageWithIdentifier:identifier]; + if (index == 0 || index >= 6) { + XCTAssertNotNil(cachedImage, @"Image for %@ should be cached", identifier); + } else { + XCTAssertNil(cachedImage, @"Image for %@ should not be cached", identifier); + } + } +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFCompoundResponseSerializerTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFCompoundResponseSerializerTests.m new file mode 100644 index 00000000..247ce8b6 --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFCompoundResponseSerializerTests.m @@ -0,0 +1,89 @@ +// AFURLSessionManagerTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import +#import "AFTestCase.h" +#import "AFURLResponseSerialization.h" + +@interface AFCompoundResponseSerializerTests : AFTestCase + +@end + +@implementation AFCompoundResponseSerializerTests + +- (void)setUp { + [super setUp]; + // Put setup code here. This method is called before the invocation of each test method in the class. +} + +- (void)tearDown { + // Put teardown code here. This method is called after the invocation of each test method in the class. + [super tearDown]; +} + +#pragma mark - Compound Serializers + +- (void)testCompoundSerializerProperlySerializesResponse { + + AFImageResponseSerializer *imageSerializer = [AFImageResponseSerializer serializer]; + AFJSONResponseSerializer *jsonSerializer = [AFJSONResponseSerializer serializer]; + AFCompoundResponseSerializer *compoundSerializer = [AFCompoundResponseSerializer compoundSerializerWithResponseSerializers:@[imageSerializer, jsonSerializer]]; + + NSData *data = [NSJSONSerialization dataWithJSONObject:@{@"key":@"value"} options:0 error:nil]; + NSURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"http://test.com"] + statusCode:200 + HTTPVersion:@"1.1" + headerFields:@{@"Content-Type":@"application/json"}]; + + NSError *error = nil; + id responseObject = [compoundSerializer responseObjectForResponse:response data:data error:&error]; + + XCTAssertTrue([responseObject isKindOfClass:[NSDictionary class]]); + XCTAssertNil(error); +} + +- (void)testCompoundSerializerCanBeCopied { + AFImageResponseSerializer *imageSerializer = [AFImageResponseSerializer serializer]; + AFJSONResponseSerializer *jsonSerializer = [AFJSONResponseSerializer serializer]; + AFCompoundResponseSerializer *compoundSerializer = [AFCompoundResponseSerializer compoundSerializerWithResponseSerializers:@[imageSerializer, jsonSerializer]]; + + AFCompoundResponseSerializer *copiedSerializer = [compoundSerializer copy]; + XCTAssertNotEqual(compoundSerializer, copiedSerializer); + XCTAssertTrue(compoundSerializer.responseSerializers.count == copiedSerializer.responseSerializers.count); + XCTAssertTrue([NSStringFromClass([[copiedSerializer.responseSerializers objectAtIndex:0] class]) isEqualToString:NSStringFromClass([AFImageResponseSerializer class])]); + XCTAssertTrue([NSStringFromClass([[copiedSerializer.responseSerializers objectAtIndex:1] class]) isEqualToString:NSStringFromClass([AFJSONResponseSerializer class])]); +} + +- (void)testCompoundSerializerCanBeArchivedAndUnarchived { + AFImageResponseSerializer *imageSerializer = [AFImageResponseSerializer serializer]; + AFJSONResponseSerializer *jsonSerializer = [AFJSONResponseSerializer serializer]; + AFCompoundResponseSerializer *compoundSerializer = [AFCompoundResponseSerializer compoundSerializerWithResponseSerializers:@[imageSerializer, jsonSerializer]]; + NSData *data = [NSKeyedArchiver archivedDataWithRootObject:compoundSerializer]; + XCTAssertNotNil(data); + AFCompoundResponseSerializer *unarchivedSerializer = [NSKeyedUnarchiver unarchiveObjectWithData:data]; + XCTAssertNotNil(unarchivedSerializer); + XCTAssertNotEqual(unarchivedSerializer, compoundSerializer); + XCTAssertTrue(compoundSerializer.responseSerializers.count == compoundSerializer.responseSerializers.count); + XCTAssertTrue([NSStringFromClass([[unarchivedSerializer.responseSerializers objectAtIndex:0] class]) isEqualToString:NSStringFromClass([AFImageResponseSerializer class])]); + XCTAssertTrue([NSStringFromClass([[unarchivedSerializer.responseSerializers objectAtIndex:1] class]) isEqualToString:NSStringFromClass([AFJSONResponseSerializer class])]); +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFHTTPRequestSerializationTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFHTTPRequestSerializationTests.m new file mode 100644 index 00000000..24ac1062 --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFHTTPRequestSerializationTests.m @@ -0,0 +1,214 @@ +// AFHTTPRequestSerializationTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "AFTestCase.h" + +#import "AFURLRequestSerialization.h" + +@interface AFMultipartBodyStream : NSInputStream +@property (readwrite, nonatomic, strong) NSMutableArray *HTTPBodyParts; +@end + +@protocol AFMultipartFormDataTest +@property (readwrite, nonatomic, strong) AFMultipartBodyStream *bodyStream; + +- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest + stringEncoding:(NSStringEncoding)encoding; +@end + +@interface AFHTTPBodyPart : NSObject +@property (nonatomic, assign) NSStringEncoding stringEncoding; +@property (nonatomic, strong) NSDictionary *headers; +@property (nonatomic, copy) NSString *boundary; +@property (nonatomic, strong) id body; +@property (nonatomic, assign) NSUInteger bodyContentLength; +@property (nonatomic, strong) NSInputStream *inputStream; +@property (nonatomic, assign) BOOL hasInitialBoundary; +@property (nonatomic, assign) BOOL hasFinalBoundary; +@property (readonly, nonatomic, assign, getter = hasBytesAvailable) BOOL bytesAvailable; +@property (readonly, nonatomic, assign) NSUInteger contentLength; + +- (NSInteger)read:(uint8_t *)buffer + maxLength:(NSUInteger)length; +@end + +#pragma mark - + +@interface AFHTTPRequestSerializationTests : AFTestCase +@property (nonatomic, strong) AFHTTPRequestSerializer *requestSerializer; +@end + +@implementation AFHTTPRequestSerializationTests + +- (void)setUp { + [super setUp]; + self.requestSerializer = [AFHTTPRequestSerializer serializer]; +} + +#pragma mark - + +- (void)testThatAFHTTPRequestSerializationSerializesPOSTRequestsProperly { + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com"]]; + request.HTTPMethod = @"POST"; + + NSURLRequest *serializedRequest = [self.requestSerializer requestBySerializingRequest:request withParameters:@{@"key":@"value"} error:nil]; + NSString *contentType = serializedRequest.allHTTPHeaderFields[@"Content-Type"]; + + XCTAssertNotNil(contentType); + XCTAssertEqualObjects(contentType, @"application/x-www-form-urlencoded"); + + XCTAssertNotNil(serializedRequest.HTTPBody); + XCTAssertEqualObjects(serializedRequest.HTTPBody, [@"key=value" dataUsingEncoding:NSUTF8StringEncoding]); +} + +- (void)testThatAFHTTPRequestSerializationSerializesPOSTRequestsProperlyWhenNoParameterIsProvided { + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com"]]; + request.HTTPMethod = @"POST"; + + NSURLRequest *serializedRequest = [self.requestSerializer requestBySerializingRequest:request withParameters:nil error:nil]; + NSString *contentType = serializedRequest.allHTTPHeaderFields[@"Content-Type"]; + + XCTAssertNotNil(contentType); + XCTAssertEqualObjects(contentType, @"application/x-www-form-urlencoded"); + + XCTAssertNotNil(serializedRequest.HTTPBody); + XCTAssertEqualObjects(serializedRequest.HTTPBody, [NSData data]); +} + +- (void)testThatAFHTTPRequestSerialiationSerializesQueryParametersCorrectly { + NSURLRequest *originalRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com"]]; + NSURLRequest *serializedRequest = [self.requestSerializer requestBySerializingRequest:originalRequest withParameters:@{@"key":@"value"} error:nil]; + + XCTAssertTrue([[[serializedRequest URL] query] isEqualToString:@"key=value"], @"Query parameters have not been serialized correctly (%@)", [[serializedRequest URL] query]); +} + +- (void)testThatAFHTTPRequestSerialiationSerializesURLEncodableQueryParametersCorrectly { + NSURLRequest *originalRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com"]]; + NSURLRequest *serializedRequest = [self.requestSerializer requestBySerializingRequest:originalRequest withParameters:@{@"key":@" :#[]@!$&'()*+,;=/?"} error:nil]; + + XCTAssertTrue([[[serializedRequest URL] query] isEqualToString:@"key=%20%3A%23%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D/?"], @"Query parameters have not been serialized correctly (%@)", [[serializedRequest URL] query]); +} + +- (void)testThatAFHTTPRequestSerialiationSerializesURLEncodedQueryParametersCorrectly { + NSURLRequest *originalRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com"]]; + NSURLRequest *serializedRequest = [self.requestSerializer requestBySerializingRequest:originalRequest withParameters:@{@"key":@"%20%21%22%23%24%25%26%27%28%29%2A%2B%2C%2F"} error:nil]; + + XCTAssertTrue([[[serializedRequest URL] query] isEqualToString:@"key=%2520%2521%2522%2523%2524%2525%2526%2527%2528%2529%252A%252B%252C%252F"], @"Query parameters have not been serialized correctly (%@)", [[serializedRequest URL] query]); +} + +- (void)testThatAFHTTPRequestSerialiationSerializesQueryParametersCorrectlyFromQuerySerializationBlock { + [self.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) { + __block NSMutableString *query = [NSMutableString stringWithString:@""]; + [parameters enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + [query appendFormat:@"%@**%@",key,obj]; + }]; + + return query; + }]; + + NSURLRequest *originalRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com"]]; + NSURLRequest *serializedRequest = [self.requestSerializer requestBySerializingRequest:originalRequest withParameters:@{@"key":@"value"} error:nil]; + + XCTAssertTrue([[[serializedRequest URL] query] isEqualToString:@"key**value"], @"Custom Query parameters have not been serialized correctly (%@) by the query string block.", [[serializedRequest URL] query]); +} + +- (void)testThatAFHTTPRequestSerialiationSerializesMIMETypeCorrectly { + NSMutableURLRequest *originalRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com"]]; + Class streamClass = NSClassFromString(@"AFStreamingMultipartFormData"); + id formData = [[streamClass alloc] initWithURLRequest:originalRequest stringEncoding:NSUTF8StringEncoding]; + + NSURL *fileURL = [NSURL fileURLWithPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"ADNNetServerTrustChain/adn_0" ofType:@"cer"]]; + + [formData appendPartWithFileURL:fileURL name:@"test" error:NULL]; + + AFHTTPBodyPart *part = [formData.bodyStream.HTTPBodyParts firstObject]; + + XCTAssertTrue([part.headers[@"Content-Type"] isEqualToString:@"application/x-x509-ca-cert"], @"MIME Type has not been obtained correctly (%@)", part.headers[@"Content-Type"]); +} + +#pragma mark - + +- (void)testThatValueForHTTPHeaderFieldReturnsSetValue { + [self.requestSerializer setValue:@"Actual Value" forHTTPHeaderField:@"Set-Header"]; + NSString *value = [self.requestSerializer valueForHTTPHeaderField:@"Set-Header"]; + XCTAssertTrue([value isEqualToString:@"Actual Value"]); +} + +- (void)testThatValueForHTTPHeaderFieldReturnsNilForUnsetHeader { + NSString *value = [self.requestSerializer valueForHTTPHeaderField:@"Unset-Header"]; + XCTAssertNil(value); +} + +- (void)testQueryStringSerializationCanFailWithError { + AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer]; + + NSError *serializerError = [NSError errorWithDomain:@"TestDomain" code:0 userInfo:nil]; + + [serializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) { + *error = serializerError; + return nil; + }]; + + NSError *error; + NSURLRequest *request = [serializer requestWithMethod:@"GET" URLString:@"url" parameters:@{} error:&error]; + XCTAssertNil(request); + XCTAssertEqual(error, serializerError); +} + +- (void)testThatHTTPHeaderValueCanBeRemoved { + AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer]; + NSString *headerField = @"TestHeader"; + NSString *headerValue = @"test"; + [serializer setValue:headerValue forHTTPHeaderField:headerField]; + XCTAssertTrue([serializer.HTTPRequestHeaders[headerField] isEqualToString:headerValue]); + [serializer setValue:nil forHTTPHeaderField:headerField]; + XCTAssertFalse([serializer.HTTPRequestHeaders.allKeys containsObject:headerField]); +} + +#pragma mark - Helper Methods + +- (void)testQueryStringFromParameters { + XCTAssertTrue([AFQueryStringFromParameters(@{@"key":@"value",@"key1":@"value&"}) isEqualToString:@"key=value&key1=value%26"]); +} + +- (void)testPercentEscapingString { + XCTAssertTrue([AFPercentEscapedStringFromString(@":#[]@!$&'()*+,;=?/") isEqualToString:@"%3A%23%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D?/"]); +} + +#pragma mark - #3028 tests +//https://github.com/AFNetworking/AFNetworking/pull/3028 + +- (void)testThatEmojiIsProperlyEncoded { + //Start with an odd number of characters so we can cross the 50 character boundry + NSMutableString *parameter = [NSMutableString stringWithString:@"!"]; + while (parameter.length < 50) { + [parameter appendString:@"👴🏿👷🏻👮🏽"]; + } + + AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer]; + NSURLRequest *request = [serializer requestWithMethod:@"GET" + URLString:@"http://test.com" + parameters:@{@"test":parameter} + error:nil]; + XCTAssertTrue([request.URL.query isEqualToString:@"test=%21%F0%9F%91%B4%F0%9F%8F%BF%F0%9F%91%B7%F0%9F%8F%BB%F0%9F%91%AE%F0%9F%8F%BD%F0%9F%91%B4%F0%9F%8F%BF%F0%9F%91%B7%F0%9F%8F%BB%F0%9F%91%AE%F0%9F%8F%BD%F0%9F%91%B4%F0%9F%8F%BF%F0%9F%91%B7%F0%9F%8F%BB%F0%9F%91%AE%F0%9F%8F%BD%F0%9F%91%B4%F0%9F%8F%BF%F0%9F%91%B7%F0%9F%8F%BB%F0%9F%91%AE%F0%9F%8F%BD%F0%9F%91%B4%F0%9F%8F%BF%F0%9F%91%B7%F0%9F%8F%BB%F0%9F%91%AE%F0%9F%8F%BD"]); +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFHTTPResponseSerializationTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFHTTPResponseSerializationTests.m new file mode 100644 index 00000000..8e0f2cac --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFHTTPResponseSerializationTests.m @@ -0,0 +1,89 @@ +// AFHTTPResponseSerializationTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "AFTestCase.h" + +#import "AFURLResponseSerialization.h" + +@interface AFHTTPResponseSerializationTests : AFTestCase +@property (nonatomic, strong) AFHTTPResponseSerializer *responseSerializer; +@end + +@implementation AFHTTPResponseSerializationTests + +- (void)setUp { + [super setUp]; + self.responseSerializer = [AFHTTPResponseSerializer serializer]; +} + +#pragma mark - + +- (void)testThatAFHTTPResponseSerializationHandlesAll2XXCodes { + NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; + [indexSet enumerateIndexesUsingBlock:^(NSUInteger statusCode, BOOL *stop) { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:statusCode HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"text/html"}]; + + XCTAssert([self.responseSerializer.acceptableStatusCodes containsIndex:statusCode], @"Status code %@ should be acceptable", @(statusCode)); + + NSError *error = nil; + [self.responseSerializer validateResponse:response data:[@"text" dataUsingEncoding:NSUTF8StringEncoding] error:&error]; + + XCTAssertNil(error, @"Error handling status code %@", @(statusCode)); + }]; +} + +- (void)testThatAFHTTPResponseSerializationFailsAll4XX5XXStatusCodes { + NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(400, 200)]; + [indexSet enumerateIndexesUsingBlock:^(NSUInteger statusCode, BOOL *stop) { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:statusCode HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"text/html"}]; + + XCTAssert(![self.responseSerializer.acceptableStatusCodes containsIndex:statusCode], @"Status code %@ should not be acceptable", @(statusCode)); + + NSError *error = nil; + [self.responseSerializer validateResponse:response data:[@"text" dataUsingEncoding:NSUTF8StringEncoding] error:&error]; + + XCTAssertNotNil(error, @"Did not fail handling status code %@",@(statusCode)); + }]; +} + +- (void)testResponseIsValidated { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"http://test.com"] + statusCode:200 + HTTPVersion:@"1.1" + headerFields:@{@"Content-Type":@"text/html"}]; + NSData *data = [@"text" dataUsingEncoding:NSUTF8StringEncoding]; + NSError *error = nil; + XCTAssertTrue([self.responseSerializer validateResponse:response data:data error:&error]); +} + +- (void)testCanBeCopied { + AFHTTPResponseSerializer *copiedSerializer = [self.responseSerializer copy]; + XCTAssertNotNil(copiedSerializer); + XCTAssertNotEqual(copiedSerializer, self.responseSerializer); + XCTAssertTrue(copiedSerializer.acceptableContentTypes.count == self.responseSerializer.acceptableContentTypes.count); + XCTAssertTrue(copiedSerializer.acceptableStatusCodes.count == self.responseSerializer.acceptableStatusCodes.count); +} + +- (void)testSupportsSecureCoding { + XCTAssertTrue([AFHTTPResponseSerializer supportsSecureCoding]); +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFHTTPSessionManagerTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFHTTPSessionManagerTests.m new file mode 100644 index 00000000..7615c822 --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFHTTPSessionManagerTests.m @@ -0,0 +1,538 @@ +// AFHTTPSessionManagerTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "AFTestCase.h" + +#import "AFHTTPSessionManager.h" +#import "AFSecurityPolicy.h" + +@interface AFHTTPSessionManagerTests : AFTestCase +@property (readwrite, nonatomic, strong) AFHTTPSessionManager *manager; +@end + +@implementation AFHTTPSessionManagerTests + +- (void)setUp { + [super setUp]; + self.manager = [[AFHTTPSessionManager alloc] initWithBaseURL:self.baseURL]; +} + +- (void)tearDown { + [self.manager invalidateSessionCancelingTasks:YES]; + [super tearDown]; +} + +#pragma mark - init +- (void)testSharedManagerIsNotEqualToInitdManager { + XCTAssertFalse([[AFHTTPSessionManager manager] isEqual:self.manager]); +} + +#pragma mark - misc + +- (void)testThatOperationInvokesCompletionHandlerWithResponseObjectOnSuccess { + __block id blockResponseObject = nil; + __block id blockError = nil; + + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + + NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/get" relativeToURL:self.baseURL]]; + NSURLSessionDataTask *task = [self.manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + blockResponseObject = responseObject; + blockError = error; + [expectation fulfill]; + }]; + + [task resume]; + + [self waitForExpectationsWithTimeout:10.0 handler:nil]; + + XCTAssertTrue(task.state == NSURLSessionTaskStateCompleted); + XCTAssertNil(blockError); + XCTAssertNotNil(blockResponseObject); +} + +- (void)testThatOperationInvokesFailureCompletionBlockWithErrorOnFailure { + __block id blockError = nil; + + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + + NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/status/404" relativeToURL:self.baseURL]]; + NSURLSessionDataTask *task = [self.manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + blockError = error; + [expectation fulfill]; + }]; + + [task resume]; + + [self waitForExpectationsWithTimeout:10.0 handler:nil]; + + XCTAssertTrue(task.state == NSURLSessionTaskStateCompleted); + XCTAssertNotNil(blockError); +} + +- (void)testThatRedirectBlockIsCalledWhen302IsEncountered { + __block BOOL success; + __block NSError *blockError = nil; + + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + + NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/redirect/1" relativeToURL:self.baseURL]]; + NSURLSessionDataTask *task = [self.manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + blockError = error; + [expectation fulfill]; + }]; + + [self.manager setTaskWillPerformHTTPRedirectionBlock:^NSURLRequest *(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request) { + if (response) { + success = YES; + } + + return request; + }]; + + [task resume]; + + [self waitForExpectationsWithTimeout:10.0 handler:nil]; + + XCTAssertTrue(task.state == NSURLSessionTaskStateCompleted); + XCTAssertNil(blockError); + XCTAssertTrue(success); +} + +- (void)testDownloadFileCompletionSpecifiesURLInCompletionWithManagerDidFinishBlock { + __block BOOL managerDownloadFinishedBlockExecuted = NO; + __block BOOL completionBlockExecuted = NO; + __block NSURL *downloadFilePath = nil; + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + + [self.manager setDownloadTaskDidFinishDownloadingBlock:^NSURL *(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location) { + managerDownloadFinishedBlockExecuted = YES; + NSURL *dirURL = [[[NSFileManager defaultManager] URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject]; + return [dirURL URLByAppendingPathComponent:@"t1.file"]; + }]; + + NSURLSessionDownloadTask *downloadTask; + downloadTask = [self.manager + downloadTaskWithRequest:[NSURLRequest requestWithURL:self.baseURL] + progress:nil + destination:nil + completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { + downloadFilePath = filePath; + completionBlockExecuted = YES; + [expectation fulfill]; + }]; + [downloadTask resume]; + [self waitForExpectationsWithTimeout:10.0 handler:nil]; + XCTAssertTrue(completionBlockExecuted); + XCTAssertTrue(managerDownloadFinishedBlockExecuted); + XCTAssertNotNil(downloadFilePath); +} + +- (void)testDownloadFileCompletionSpecifiesURLInCompletionBlock { + __block BOOL destinationBlockExecuted = NO; + __block BOOL completionBlockExecuted = NO; + __block NSURL *downloadFilePath = nil; + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + + NSURLSessionDownloadTask *downloadTask = [self.manager downloadTaskWithRequest:[NSURLRequest requestWithURL:self.baseURL] + progress:nil + destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { + destinationBlockExecuted = YES; + NSURL *dirURL = [[[NSFileManager defaultManager] URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject]; + return [dirURL URLByAppendingPathComponent:@"t1.file"]; + } + completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { + downloadFilePath = filePath; + completionBlockExecuted = YES; + [expectation fulfill]; + }]; + [downloadTask resume]; + [self waitForExpectationsWithTimeout:10.0 handler:nil]; + XCTAssertTrue(completionBlockExecuted); + XCTAssertTrue(destinationBlockExecuted); + XCTAssertNotNil(downloadFilePath); +} + +- (void)testThatSerializationErrorGeneratesErrorAndNullTaskForGET { + XCTestExpectation *expectation = [self expectationWithDescription:@"Serialization should fail"]; + + [self.manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) { + *error = [NSError errorWithDomain:@"Custom" code:-1 userInfo:nil]; + return @""; + }]; + + NSURLSessionTask *nilTask; + nilTask = [self.manager + GET:@"test" + parameters:@{@"key":@"value"} + progress:nil + success:nil + failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { + XCTAssertNil(task); + [expectation fulfill]; + }]; + XCTAssertNil(nilTask); + [self waitForExpectationsWithTimeout:10.0 handler:nil]; +} + +#pragma mark - NSCoding + +- (void)testSupportsSecureCoding { + XCTAssertTrue([AFHTTPSessionManager supportsSecureCoding]); +} + +- (void)testCanBeEncoded { + NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.manager]; + XCTAssertNotNil(data); +} + +- (void)testCanBeDecoded { + NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.manager]; + AFHTTPSessionManager *newManager = [NSKeyedUnarchiver unarchiveObjectWithData:data]; + XCTAssertNotNil(newManager.securityPolicy); + XCTAssertNotNil(newManager.requestSerializer); + XCTAssertNotNil(newManager.responseSerializer); + XCTAssertNotNil(newManager.baseURL); + XCTAssertNotNil(newManager.session); + XCTAssertNotNil(newManager.session.configuration); +} + +#pragma mark - NSCopying + +- (void)testCanBeCopied { + AFHTTPSessionManager *copyManager = [self.manager copy]; + XCTAssertNotNil(copyManager); +} + +#pragma mark - Progress + +- (void)testDownloadProgressIsReportedForGET { + XCTestExpectation *expectation = [self expectationWithDescription:@"Progress Should equal 1.0"]; + [self.manager + GET:@"image" + parameters:nil + progress:^(NSProgress * _Nonnull downloadProgress) { + if (downloadProgress.fractionCompleted == 1.0) { + [expectation fulfill]; + } + } + success:nil + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testUploadProgressIsReportedForPOST { + NSMutableString *payload = [NSMutableString stringWithString:@"AFNetworking"]; + while ([payload lengthOfBytesUsingEncoding:NSUTF8StringEncoding] < 20000) { + [payload appendString:@"AFNetworking"]; + } + + __weak __block XCTestExpectation *expectation = [self expectationWithDescription:@"Progress Should equal 1.0"]; + + [self.manager + POST:@"post" + parameters:payload + progress:^(NSProgress * _Nonnull uploadProgress) { + if (uploadProgress.fractionCompleted == 1.0) { + [expectation fulfill]; + expectation = nil; + } + } + success:nil + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testUploadProgressIsReportedForStreamingPost { + NSMutableString *payload = [NSMutableString stringWithString:@"AFNetworking"]; + while ([payload lengthOfBytesUsingEncoding:NSUTF8StringEncoding] < 20000) { + [payload appendString:@"AFNetworking"]; + } + + __block __weak XCTestExpectation *expectation = [self expectationWithDescription:@"Progress Should equal 1.0"]; + + [self.manager + POST:@"post" + parameters:nil + constructingBodyWithBlock:^(id _Nonnull formData) { + [formData appendPartWithFileData:[payload dataUsingEncoding:NSUTF8StringEncoding] name:@"AFNetworking" fileName:@"AFNetworking" mimeType:@"text/html"]; + } + progress:^(NSProgress * _Nonnull uploadProgress) { + if (uploadProgress.fractionCompleted == 1.0) { + [expectation fulfill]; + expectation = nil; + } + } + success:nil + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +# pragma mark - HTTP Status Codes + +- (void)testThatSuccessBlockIsCalledFor200 { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.manager + GET:@"status/200" + parameters:nil + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testThatFailureBlockIsCalledFor404 { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.manager + GET:@"status/404" + parameters:nil + progress:nil + success:nil + failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) { + [expectation fulfill]; + }]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testThatResponseObjectIsEmptyFor204 { + __block id urlResponseObject = nil; + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.manager + GET:@"status/204" + parameters:nil + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + urlResponseObject = responseObject; + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + XCTAssertNil(urlResponseObject); +} + +#pragma mark - Rest Interface + +- (void)testGET { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.manager + GET:@"get" + parameters:nil + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + XCTAssertNotNil(responseObject); + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testHEAD { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.manager + HEAD:@"get" + parameters:nil + success:^(NSURLSessionDataTask * _Nonnull task) { + XCTAssertNotNil(task); + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testPOST { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.manager + POST:@"post" + parameters:@{@"key":@"value"} + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + XCTAssertTrue([responseObject[@"form"][@"key"] isEqualToString:@"value"]); + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testPOSTWithConstructingBody { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.manager + POST:@"post" + parameters:@{@"key":@"value"} + constructingBodyWithBlock:^(id _Nonnull formData) { + [formData appendPartWithFileData:[@"Data" dataUsingEncoding:NSUTF8StringEncoding] + name:@"DataName" + fileName:@"DataFileName" + mimeType:@"data"]; + } + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + XCTAssertTrue([responseObject[@"files"][@"DataName"] isEqualToString:@"Data"]); + XCTAssertTrue([responseObject[@"form"][@"key"] isEqualToString:@"value"]); + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testPUT { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.manager + PUT:@"put" + parameters:@{@"key":@"value"} + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + XCTAssertTrue([responseObject[@"form"][@"key"] isEqualToString:@"value"]); + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testDELETE { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.manager + DELETE:@"delete" + parameters:@{@"key":@"value"} + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + XCTAssertTrue([responseObject[@"args"][@"key"] isEqualToString:@"value"]); + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testPATCH { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.manager + PATCH:@"patch" + parameters:@{@"key":@"value"} + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + XCTAssertTrue([responseObject[@"form"][@"key"] isEqualToString:@"value"]); + [expectation fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +#pragma mark - Deprecated Rest Interface + +- (void)testDeprecatedGET { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + [self.manager + GET:@"get" + parameters:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + XCTAssertNotNil(responseObject); + [expectation fulfill]; + } + failure:nil]; +#pragma clang diagnostic pop + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testDeprecatedPOST { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + [self.manager + POST:@"post" + parameters:@{@"key":@"value"} + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + XCTAssertTrue([responseObject[@"form"][@"key"] isEqualToString:@"value"]); + [expectation fulfill]; + } + failure:nil]; +#pragma clang diagnostic pop + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testDeprecatedPOSTWithConstructingBody { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + [self.manager + POST:@"post" + parameters:@{@"key":@"value"} + constructingBodyWithBlock:^(id _Nonnull formData) { + [formData appendPartWithFileData:[@"Data" dataUsingEncoding:NSUTF8StringEncoding] + name:@"DataName" + fileName:@"DataFileName" + mimeType:@"data"]; + } + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + XCTAssertTrue([responseObject[@"files"][@"DataName"] isEqualToString:@"Data"]); + XCTAssertTrue([responseObject[@"form"][@"key"] isEqualToString:@"value"]); + [expectation fulfill]; + } + failure:nil]; +#pragma clang diagnostic pop + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +#pragma mark - Auth + +- (void)testHiddenBasicAuthentication { + __weak XCTestExpectation *expectation = [self expectationWithDescription:@"Request should finish"]; + [self.manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"user" password:@"password"]; + [self.manager + GET:@"hidden-basic-auth/user/password" + parameters:nil + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + [expectation fulfill]; + } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { + XCTFail(@"Request should succeed"); + [expectation fulfill]; + }]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +# pragma mark - Server Trust + +- (void)testInvalidServerTrustProducesCorrectError { + __weak XCTestExpectation *expectation = [self expectationWithDescription:@"Request should fail"]; + NSURL *googleCertificateURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"google.com" withExtension:@"cer"]; + NSData *googleCertificateData = [NSData dataWithContentsOfURL:googleCertificateURL]; + AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"https://apple.com/"]]; + [manager setResponseSerializer:[AFHTTPResponseSerializer serializer]]; + manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:[NSSet setWithObject:googleCertificateData]]; + [manager + GET:@"AFNetworking/AFNetworking" + parameters:nil + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + XCTFail(@"Request should fail"); + [expectation fulfill]; + } + failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { + XCTAssertEqualObjects(error.domain, NSURLErrorDomain); + XCTAssertEqual(error.code, NSURLErrorServerCertificateUntrusted); + [expectation fulfill]; + }]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + [manager invalidateSessionCancelingTasks:YES]; +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFImageDownloaderTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFImageDownloaderTests.m new file mode 100644 index 00000000..ac112f6e --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFImageDownloaderTests.m @@ -0,0 +1,428 @@ +// AFImageDownloaderTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "AFTestCase.h" +#import "AFImageDownloader.h" + +@interface AFImageDownloaderTests : AFTestCase +@property (nonatomic, strong) NSURLRequest *pngRequest; +@property (nonatomic, strong) NSURLRequest *jpegRequest; +@property (nonatomic, strong) AFImageDownloader *downloader; +@end + +@implementation AFImageDownloaderTests + +- (void)setUp { + [super setUp]; + self.downloader = [[AFImageDownloader alloc] init]; + [[AFImageDownloader defaultURLCache] removeAllCachedResponses]; + [[[AFImageDownloader defaultInstance] imageCache] removeAllImages]; + NSURL *pngURL = [NSURL URLWithString:@"https://httpbin.org/image/png"]; + self.pngRequest = [NSURLRequest requestWithURL:pngURL]; + NSURL *jpegURL = [NSURL URLWithString:@"https://httpbin.org/image/jpeg"]; + self.jpegRequest = [NSURLRequest requestWithURL:jpegURL]; +} + +- (void)tearDown { + [self.downloader.sessionManager invalidateSessionCancelingTasks:YES]; + self.downloader = nil; + // Put teardown code here. This method is called after the invocation of each test method in the class. + [super tearDown]; + self.pngRequest = nil; +} + +#pragma mark - Image Download + +- (void)testThatImageDownloaderSingletonCanBeInitialized { + AFImageDownloader *downloader = [AFImageDownloader defaultInstance]; + XCTAssertNotNil(downloader, @"Downloader should not be nil"); +} + +- (void)testThatImageDownloaderCanBeInitializedAndDeinitializedWithActiveDownloads { + [self.downloader downloadImageForURLRequest:self.pngRequest + success:nil + failure:nil]; + self.downloader = nil; + XCTAssertNil(self.downloader, @"Downloader should be nil"); +} + +- (void)testThatImageDownloaderCanDownloadImage { + XCTestExpectation *expectation = [self expectationWithDescription:@"image download should succeed"]; + + __block NSHTTPURLResponse *urlResponse = nil; + __block UIImage *responseImage = nil; + + [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse = response; + responseImage = responseObject; + [expectation fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTAssertNotNil(urlResponse, @"HTTPURLResponse should not be nil"); + XCTAssertNotNil(responseImage, @"Response image should not be nil"); +} + +- (void)testThatItCanDownloadMultipleImagesSimultaneously { + XCTestExpectation *expectation1 = [self expectationWithDescription:@"image 1 download should succeed"]; + __block NSHTTPURLResponse *urlResponse1 = nil; + __block UIImage *responseImage1 = nil; + + [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse1 = response; + responseImage1 = responseObject; + [expectation1 fulfill]; + } + failure:nil]; + + XCTestExpectation *expectation2 = [self expectationWithDescription:@"image 2 download should succeed"]; + __block NSHTTPURLResponse *urlResponse2 = nil; + __block UIImage *responseImage2 = nil; + + [self.downloader + downloadImageForURLRequest:self.jpegRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse2 = response; + responseImage2 = responseObject; + [expectation2 fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTAssertNotNil(urlResponse1, @"HTTPURLResponse should not be nil"); + XCTAssertNotNil(responseImage1, @"Respone image should not be nil"); + + XCTAssertNotNil(urlResponse2, @"HTTPURLResponse should not be nil"); + XCTAssertNotNil(responseImage2, @"Respone image should not be nil"); +} + +- (void)testThatSimultaneouslyRequestsForTheSameAssetReceiveSameResponse { + XCTestExpectation *expectation1 = [self expectationWithDescription:@"image 1 download should succeed"]; + __block NSHTTPURLResponse *urlResponse1 = nil; + __block UIImage *responseImage1 = nil; + + [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse1 = response; + responseImage1 = responseObject; + [expectation1 fulfill]; + } + failure:nil]; + + XCTestExpectation *expectation2 = [self expectationWithDescription:@"image 2 download should succeed"]; + __block NSHTTPURLResponse *urlResponse2 = nil; + __block UIImage *responseImage2 = nil; + + [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse2 = response; + responseImage2 = responseObject; + [expectation2 fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTAssertEqual(urlResponse1, urlResponse2, @"responses should be equal"); + XCTAssertEqual(responseImage2, responseImage2, @"responses should be equal"); +} + +- (void)testThatImageBehindRedirectCanBeDownloaded { + XCTestExpectation *expectation = [self expectationWithDescription:@"image download should succeed"]; + NSURL *redirectURL = [self.jpegRequest URL]; + NSURLRequest *request = [NSURLRequest requestWithURL:redirectURL]; + + __block NSHTTPURLResponse *urlResponse = nil; + __block UIImage *responseImage = nil; + + [self.downloader + downloadImageForURLRequest:request + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse = response; + responseImage = responseObject; + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + XCTAssertNotNil(urlResponse); + XCTAssertNotNil(responseImage); + +} + +#pragma mark - Caching +- (void)testThatResponseIsNilWhenReturnedFromCache { + XCTestExpectation *expectation1 = [self expectationWithDescription:@"image 1 download should succeed"]; + __block NSHTTPURLResponse *urlResponse1 = nil; + __block UIImage *responseImage1 = nil; + + [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse1 = response; + responseImage1 = responseObject; + [expectation1 fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTestExpectation *expectation2 = [self expectationWithDescription:@"image 2 download should succeed"]; + __block NSHTTPURLResponse *urlResponse2 = nil; + __block UIImage *responseImage2 = nil; + + [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse2 = response; + responseImage2 = responseObject; + [expectation2 fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTAssertNotNil(urlResponse1); + XCTAssertNotNil(responseImage1); + XCTAssertNil(urlResponse2); + XCTAssertEqual(responseImage1, responseImage2); +} + +- (void)testThatImageDownloadReceiptIsNilForCachedImage { + XCTestExpectation *expectation1 = [self expectationWithDescription:@"image 1 download should succeed"]; + AFImageDownloadReceipt *receipt1; + receipt1 = [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + [expectation1 fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTestExpectation *expectation2 = [self expectationWithDescription:@"image 2 download should succeed"]; + + AFImageDownloadReceipt *receipt2; + receipt2 = [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + [expectation2 fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTAssertNotNil(receipt1); + XCTAssertNil(receipt2); +} + +- (void)testThatCacheIsIgnoredIfCacheIgnoredInRequest { + XCTestExpectation *expectation1 = [self expectationWithDescription:@"image 1 download should succeed"]; + + __block NSHTTPURLResponse *urlResponse1 = nil; + __block UIImage *responseImage1 = nil; + AFImageDownloadReceipt *receipt1; + receipt1 = [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse1 = response; + responseImage1 = responseObject; + [expectation1 fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTestExpectation *expectation2 = [self expectationWithDescription:@"image 2 download should succeed"]; + NSMutableURLRequest *alteredRequest = [self.pngRequest mutableCopy]; + alteredRequest.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData; + + AFImageDownloadReceipt *receipt2; + __block NSHTTPURLResponse *urlResponse2 = nil; + __block UIImage *responseImage2 = nil; + receipt2 = [self.downloader + downloadImageForURLRequest:alteredRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse2 = response; + responseImage2 = responseObject; + [expectation2 fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTAssertNotNil(receipt1); + XCTAssertNotNil(receipt2); + XCTAssertNotEqual(receipt1, receipt2); + + XCTAssertNotNil(urlResponse1); + XCTAssertNotNil(responseImage1); + + XCTAssertNotNil(urlResponse2); + XCTAssertNotNil(responseImage2); + + XCTAssertNotEqual(responseImage1, responseImage2); +} + +#pragma mark - Cancellation + +- (void)testThatCancellingDownloadCallsCompletionWithCancellationError { + AFImageDownloadReceipt *receipt; + XCTestExpectation *expectation = [self expectationWithDescription:@"image download should fail"]; + __block NSError *responseError = nil; + receipt = [self.downloader + downloadImageForURLRequest:self.pngRequest + success:nil + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + responseError = error; + [expectation fulfill]; + }]; + [self.downloader cancelTaskForImageDownloadReceipt:receipt]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTAssertTrue(responseError.code == NSURLErrorCancelled); + XCTAssertTrue([responseError.domain isEqualToString:NSURLErrorDomain]); +} + +- (void)testThatCancellingDownloadWithMultipleResponseHandlersCancelsFirstYetAllowsSecondToComplete { + XCTestExpectation *expectation1 = [self expectationWithDescription:@"image 1 download should succeed"]; + __block NSHTTPURLResponse *urlResponse = nil; + __block UIImage *responseImage = nil; + + [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse = response; + responseImage = responseObject; + [expectation1 fulfill]; + } + failure:nil]; + + XCTestExpectation *expectation2 = [self expectationWithDescription:@"image 2 download should fail"]; + __block NSError *responseError = nil; + AFImageDownloadReceipt *receipt; + receipt = [self.downloader + downloadImageForURLRequest:self.pngRequest + success:nil + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + responseError = error; + [expectation2 fulfill]; + }]; + [self.downloader cancelTaskForImageDownloadReceipt:receipt]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTAssertTrue(responseError.code == NSURLErrorCancelled); + XCTAssertTrue([responseError.domain isEqualToString:NSURLErrorDomain]); + XCTAssertNotNil(urlResponse); + XCTAssertNotNil(responseImage); +} + +- (void)testThatItCanDownloadAndCancelAndDownloadAgain { + NSArray *imageURLStrings = @[ + @"https://secure.gravatar.com/avatar/5a105e8b9d40e1329780d62ea2265d8a?d=identicon", + @"https://secure.gravatar.com/avatar/6a105e8b9d40e1329780d62ea2265d8a?d=identicon", + @"https://secure.gravatar.com/avatar/7a105e8b9d40e1329780d62ea2265d8a?d=identicon", + @"https://secure.gravatar.com/avatar/8a105e8b9d40e1329780d62ea2265d8a?d=identicon", + @"https://secure.gravatar.com/avatar/9a105e8b9d40e1329780d62ea2265d8a?d=identicon" + ]; + + for (NSString *imageURLString in imageURLStrings) { + XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:@"Request %@ should be cancelled", imageURLString]]; + AFImageDownloadReceipt *receipt = [self.downloader + downloadImageForURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageURLString]] + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + XCTFail(@"Request %@ succeeded when it should have failed", request); + } + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + XCTAssertTrue([error.domain isEqualToString:NSURLErrorDomain]); + XCTAssertTrue([error code] == NSURLErrorCancelled); + [expectation fulfill]; + }]; + [self.downloader cancelTaskForImageDownloadReceipt:receipt]; + } + + for (NSString *imageURLString in imageURLStrings) { + XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:@"Request %@ should succeed", imageURLString]]; + [self.downloader + downloadImageForURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageURLString]] + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + [expectation fulfill]; + } failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + XCTFail(@"Request %@ failed with error %@", request, error); + }]; + } + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +#pragma mark - Threading +- (void)testThatItAlwaysCallsTheSuccessHandlerOnTheMainQueue { + XCTestExpectation *expectation = [self expectationWithDescription:@"image download should succeed"]; + __block BOOL successIsOnMainThread = false; + [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + successIsOnMainThread = [[NSThread currentThread] isMainThread]; + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + XCTAssertTrue(successIsOnMainThread); +} + +- (void)testThatItAlwaysCallsTheFailureHandlerOnTheMainQueue { + NSURL *url = [NSURL URLWithString:@"https://httpbin.org/status/404"]; + NSURLRequest *request = [NSURLRequest requestWithURL:url]; + XCTestExpectation *expectation = [self expectationWithDescription:@"image download should fail"]; + __block BOOL failureIsOnMainThread = false; + [self.downloader + downloadImageForURLRequest:request + success:nil + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + failureIsOnMainThread = [[NSThread currentThread] isMainThread]; + [expectation fulfill]; + }]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + XCTAssertTrue(failureIsOnMainThread); +} + +#pragma mark - misc + +- (void)testThatReceiptIDMatchesReturnedID { + NSUUID *receiptId = [NSUUID UUID]; + AFImageDownloadReceipt *receipt = [self.downloader + downloadImageForURLRequest:self.jpegRequest + withReceiptID:receiptId + success:nil + failure:nil]; + XCTAssertEqual(receiptId, receipt.receiptID); + [self.downloader cancelTaskForImageDownloadReceipt:receipt]; +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFJSONSerializationTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFJSONSerializationTests.m new file mode 100644 index 00000000..1ce27fba --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFJSONSerializationTests.m @@ -0,0 +1,171 @@ +// AFJSONSerializationTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "AFTestCase.h" + +#import "AFURLRequestSerialization.h" +#import "AFURLResponseSerialization.h" + +static NSData * AFJSONTestData() { + return [NSJSONSerialization dataWithJSONObject:@{@"foo": @"bar"} options:0 error:nil]; +} + +#pragma mark - + +@interface AFJSONRequestSerializationTests : AFTestCase +@property (nonatomic, strong) AFJSONRequestSerializer *requestSerializer; +@end + +@implementation AFJSONRequestSerializationTests + +- (void)setUp { + self.requestSerializer = [[AFJSONRequestSerializer alloc] init]; +} + +#pragma mark - + +- (void)testThatJSONRequestSerializationHandlesParametersDictionary { + NSDictionary *parameters = @{@"key":@"value"}; + NSError *error = nil; + NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:AFNetworkingTestsBaseURLString parameters:parameters error:&error]; + + XCTAssertNil(error, @"Serialization error should be nil"); + + NSString *body = [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]; + + XCTAssertTrue([@"{\"key\":\"value\"}" isEqualToString:body], @"Parameters were not encoded correctly"); +} + +- (void)testThatJSONRequestSerializationHandlesParametersArray { + NSArray *parameters = @[@{@"key":@"value"}]; + NSError *error = nil; + NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:AFNetworkingTestsBaseURLString parameters:parameters error:&error]; + + XCTAssertNil(error, @"Serialization error should be nil"); + + NSString *body = [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]; + + XCTAssertTrue([@"[{\"key\":\"value\"}]" isEqualToString:body], @"Parameters were not encoded correctly"); +} + +@end + +#pragma mark - + +@interface AFJSONResponseSerializationTests : AFTestCase +@property (nonatomic, strong) AFJSONResponseSerializer *responseSerializer; +@end + +@implementation AFJSONResponseSerializationTests + +- (void)setUp { + [super setUp]; + self.responseSerializer = [AFJSONResponseSerializer serializer]; +} + +#pragma mark - + +- (void)testThatJSONResponseSerializerAcceptsApplicationJSONMimeType { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"application/json"}]; + + NSError *error = nil; + [self.responseSerializer validateResponse:response data:AFJSONTestData() error:&error]; + + XCTAssertNil(error, @"Error handling application/json"); +} + +- (void)testThatJSONResponseSerializerAcceptsTextJSONMimeType { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"text/json"}]; + NSError *error = nil; + [self.responseSerializer validateResponse:response data:AFJSONTestData()error:&error]; + + XCTAssertNil(error, @"Error handling text/json"); +} + +- (void)testThatJSONResponseSerializerAcceptsTextJavaScriptMimeType { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"text/javascript"}]; + NSError *error = nil; + [self.responseSerializer validateResponse:response data:AFJSONTestData() error:&error]; + + XCTAssertNil(error, @"Error handling text/javascript"); +} + +- (void)testThatJSONResponseSerializerDoesNotAcceptNonStandardJSONMimeType { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"nonstandard/json"}]; + NSError *error = nil; + [self.responseSerializer validateResponse:response data:AFJSONTestData() error:&error]; + + XCTAssertNotNil(error, @"Error should have been thrown for nonstandard/json"); +} + +- (void)testThatJSONResponseSerializerReturnsDictionaryForValidJSONDictionary { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"text/json"}]; + NSError *error = nil; + id responseObject = [self.responseSerializer responseObjectForResponse:response data:AFJSONTestData() error:&error]; + + XCTAssertNil(error, @"Serialization error should be nil"); + XCTAssert([responseObject isKindOfClass:[NSDictionary class]], @"Expected response to be a NSDictionary"); +} + +- (void)testThatJSONResponseSerializerReturnsErrorForInvalidJSON { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type":@"text/json"}]; + NSError *error = nil; + [self.responseSerializer responseObjectForResponse:response data:[@"{invalid}" dataUsingEncoding:NSUTF8StringEncoding] error:&error]; + + XCTAssertNotNil(error, @"Serialization error should not be nil"); +} + +- (void)testThatJSONResponseSerializerReturnsNilObjectAndNilErrorForEmptyData { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type":@"text/json"}]; + NSData *data = [NSData data]; + NSError *error = nil; + id responseObject = [self.responseSerializer responseObjectForResponse:response data:data error:&error]; + XCTAssertNil(responseObject); + XCTAssertNil(error); +} + +- (void)testThatJSONResponseSerializerReturnsNilObjectAndNilErrorForSingleSpace { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type":@"text/json"}]; + NSData *data = [@" " dataUsingEncoding:NSUTF8StringEncoding]; + NSError *error = nil; + id responseObject = [self.responseSerializer responseObjectForResponse:response data:data error:&error]; + XCTAssertNil(responseObject); + XCTAssertNil(error); +} + +- (void)testThatJSONRemovesKeysWithNullValues { + self.responseSerializer.removesKeysWithNullValues = YES; + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type":@"text/json"}]; + NSData *data = [NSJSONSerialization dataWithJSONObject:@{@"key":@"value",@"nullkey":[NSNull null],@"array":@[@{@"subnullkey":[NSNull null]}]} + options:0 + error:nil]; + + NSError *error = nil; + NSDictionary *responseObject = [self.responseSerializer responseObjectForResponse:response + data:data + error:&error]; + XCTAssertNil(error); + XCTAssertNotNil(responseObject[@"key"]); + XCTAssertNil(responseObject[@"nullkey"]); + XCTAssertNil(responseObject[@"array"][0][@"subnullkey"]); +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFNetworkActivityManagerTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFNetworkActivityManagerTests.m new file mode 100644 index 00000000..d12e6467 --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFNetworkActivityManagerTests.m @@ -0,0 +1,181 @@ +// AFNetworkActivityManagerTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "AFTestCase.h" + +#import "AFNetworkActivityIndicatorManager.h" +#import "AFHTTPSessionManager.h" + +@interface AFNetworkActivityManagerTests : AFTestCase +@property (nonatomic, strong) AFNetworkActivityIndicatorManager *networkActivityIndicatorManager; +@property (nonatomic, strong) AFHTTPSessionManager *sessionManager; +@end + +#pragma mark - + +@implementation AFNetworkActivityManagerTests + +- (void)setUp { + [super setUp]; + + self.sessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:self.baseURL sessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + + self.networkActivityIndicatorManager = [[AFNetworkActivityIndicatorManager alloc] init]; + self.networkActivityIndicatorManager.enabled = YES; +} + +- (void)tearDown { + [super tearDown]; + self.networkActivityIndicatorManager = nil; + + [self.sessionManager invalidateSessionCancelingTasks:YES]; +} + +#pragma mark - + +- (void)testThatNetworkActivityIndicatorTurnsOnAndOffIndicatorWhenRequestSucceeds { + self.networkActivityIndicatorManager.activationDelay = 0.0; + self.networkActivityIndicatorManager.completionDelay = 0.0; + + XCTestExpectation *startExpectation = [self expectationWithDescription:@"Indicator Visible"]; + XCTestExpectation *endExpectation = [self expectationWithDescription:@"Indicator Hidden"]; + [self.networkActivityIndicatorManager setNetworkingActivityActionWithBlock:^(BOOL networkActivityIndicatorVisible) { + if (networkActivityIndicatorVisible) { + [startExpectation fulfill]; + } else { + [endExpectation fulfill]; + } + }]; + + XCTestExpectation *requestExpectation = [self expectationWithDescription:@"Request should succeed"]; + [self.sessionManager + GET:@"/delay/1" + parameters:nil + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) { + [requestExpectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testThatNetworkActivityIndicatorTurnsOnAndOffIndicatorWhenRequestFails { + self.networkActivityIndicatorManager.activationDelay = 0.0; + self.networkActivityIndicatorManager.completionDelay = 0.0; + + XCTestExpectation *startExpectation = [self expectationWithDescription:@"Indicator Visible"]; + XCTestExpectation *endExpectation = [self expectationWithDescription:@"Indicator Hidden"]; + [self.networkActivityIndicatorManager setNetworkingActivityActionWithBlock:^(BOOL networkActivityIndicatorVisible) { + if (networkActivityIndicatorVisible) { + [startExpectation fulfill]; + } else { + [endExpectation fulfill]; + } + }]; + + XCTestExpectation *requestExpectation = [self expectationWithDescription:@"Request should fail"]; + [self.sessionManager + GET:@"/status/404" + parameters:nil + progress:nil + success:nil + failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { + [requestExpectation fulfill]; + }]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testThatVisibilityDelaysAreApplied { + + self.networkActivityIndicatorManager.activationDelay = 1.0; + self.networkActivityIndicatorManager.completionDelay = 1.0; + + CFTimeInterval requestStartTime = CACurrentMediaTime(); + __block CFTimeInterval requestEndTime; + __block CFTimeInterval indicatorVisbleTime; + __block CFTimeInterval indicatorHiddenTime; + XCTestExpectation *startExpectation = [self expectationWithDescription:@"Indicator Visible"]; + XCTestExpectation *endExpectation = [self expectationWithDescription:@"Indicator Hidden"]; + [self.networkActivityIndicatorManager setNetworkingActivityActionWithBlock:^(BOOL networkActivityIndicatorVisible) { + if (networkActivityIndicatorVisible) { + indicatorVisbleTime = CACurrentMediaTime(); + [startExpectation fulfill]; + } else { + indicatorHiddenTime = CACurrentMediaTime(); + [endExpectation fulfill]; + } + }]; + + XCTestExpectation *requestExpectation = [self expectationWithDescription:@"Request should succeed"]; + [self.sessionManager + GET:@"/delay/2" + parameters:nil + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) { + requestEndTime = CACurrentMediaTime(); + [requestExpectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + XCTAssertTrue((indicatorVisbleTime - requestStartTime) > self.networkActivityIndicatorManager.activationDelay); + XCTAssertTrue((indicatorHiddenTime - requestEndTime) > self.networkActivityIndicatorManager.completionDelay); +} + +- (void)testThatIndicatorBlockIsOnlyCalledOnceEachForStartAndEndForMultipleRequests { + self.networkActivityIndicatorManager.activationDelay = 1.0; + self.networkActivityIndicatorManager.completionDelay = 1.0; + + XCTestExpectation *startExpectation = [self expectationWithDescription:@"Indicator Visible"]; + XCTestExpectation *endExpectation = [self expectationWithDescription:@"Indicator Hidden"]; + [self.networkActivityIndicatorManager setNetworkingActivityActionWithBlock:^(BOOL networkActivityIndicatorVisible) { + if (networkActivityIndicatorVisible) { + [startExpectation fulfill]; + } else { + [endExpectation fulfill]; + } + }]; + + XCTestExpectation *requestExpectation = [self expectationWithDescription:@"Request should succeed"]; + [self.sessionManager + GET:@"/delay/4" + parameters:nil + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) { + [requestExpectation fulfill]; + } + failure:nil]; + + XCTestExpectation *secondRequestExpectation = [self expectationWithDescription:@"Request should succeed"]; + [self.sessionManager + GET:@"/delay/2" + parameters:nil + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) { + + [secondRequestExpectation fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFNetworkReachabilityManagerTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFNetworkReachabilityManagerTests.m new file mode 100644 index 00000000..05b3c94e --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFNetworkReachabilityManagerTests.m @@ -0,0 +1,124 @@ +// AFNetworkReachabilityManagerTests.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "AFTestCase.h" + +#import "AFNetworkReachabilityManager.h" +#import + +@interface AFNetworkReachabilityManagerTests : AFTestCase +@property (nonatomic, strong) AFNetworkReachabilityManager *addressReachability; +@property (nonatomic, strong) AFNetworkReachabilityManager *domainReachability; +@end + +@implementation AFNetworkReachabilityManagerTests + +- (void)setUp { + [super setUp]; + + //both of these manager objects should always be reachable when the tests are run + self.domainReachability = [AFNetworkReachabilityManager managerForDomain:@"localhost"]; + self.addressReachability = [AFNetworkReachabilityManager manager]; +} + +- (void)tearDown +{ + [self.addressReachability stopMonitoring]; + [self.domainReachability stopMonitoring]; + + [super tearDown]; +} + +- (void)testAddressReachabilityStartsInUnknownState { + XCTAssertEqual(self.addressReachability.networkReachabilityStatus, AFNetworkReachabilityStatusUnknown, + @"Reachability should start in an unknown state"); +} + +- (void)testDomainReachabilityStartsInUnknownState { + XCTAssertEqual(self.domainReachability.networkReachabilityStatus, AFNetworkReachabilityStatusUnknown, + @"Reachability should start in an unknown state"); +} + +- (void)verifyReachabilityNotificationGetsPostedWithManager:(AFNetworkReachabilityManager *)manager +{ + [self expectationForNotification:AFNetworkingReachabilityDidChangeNotification + object:nil + handler:^BOOL(NSNotification *note) { + AFNetworkReachabilityStatus status; + status = [note.userInfo[AFNetworkingReachabilityNotificationStatusItem] integerValue]; + BOOL reachable = (status == AFNetworkReachabilityStatusReachableViaWiFi + || status == AFNetworkReachabilityStatusReachableViaWWAN); + + if (reachable) { + XCTAssert(reachable, + @"Expected network to be reachable but got '%@'", + AFStringFromNetworkReachabilityStatus(status)); + XCTAssertEqual(reachable, manager.isReachable, @"Expected status to match 'isReachable'"); + } + + return reachable; + }]; + + [manager startMonitoring]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testAddressReachabilityNotification { + [self verifyReachabilityNotificationGetsPostedWithManager:self.addressReachability]; +} + +//Commenting out for Travis Stability +//- (void)testDomainReachabilityNotification { +// [self verifyReachabilityNotificationGetsPostedWithManager:self.domainReachability]; +//} + +- (void)verifyReachabilityStatusBlockGetsCalledWithManager:(AFNetworkReachabilityManager *)manager +{ + __weak XCTestExpectation *expectation = [self expectationWithDescription:@"reachability status change block gets called"]; + + typeof(manager) __weak weakManager = manager; + [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { + BOOL reachable = (status == AFNetworkReachabilityStatusReachableViaWiFi + || status == AFNetworkReachabilityStatusReachableViaWWAN); + + XCTAssert(reachable, @"Expected network to be reachable but got '%@'", AFStringFromNetworkReachabilityStatus(status)); + XCTAssertEqual(reachable, weakManager.isReachable, @"Expected status to match 'isReachable'"); + + [expectation fulfill]; + }]; + + [manager startMonitoring]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + [manager setReachabilityStatusChangeBlock:nil]; + +} + +- (void)testAddressReachabilityBlock { + [self verifyReachabilityStatusBlockGetsCalledWithManager:self.addressReachability]; +} + +- (void)testDomainReachabilityBlock { + [self verifyReachabilityStatusBlockGetsCalledWithManager:self.domainReachability]; +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFPropertyListResponseSerializerTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFPropertyListResponseSerializerTests.m new file mode 100644 index 00000000..9a9212bf --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFPropertyListResponseSerializerTests.m @@ -0,0 +1,66 @@ +// AFPropertyListResponseSerializerTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "AFTestCase.h" + +#import "AFURLResponseSerialization.h" + +@interface AFPropertyListResponseSerializerTests : AFTestCase +@property (nonatomic, strong) AFPropertyListResponseSerializer *responseSerializer; +@end + +@implementation AFPropertyListResponseSerializerTests + +- (void)setUp { + [super setUp]; + self.responseSerializer = [AFPropertyListResponseSerializer serializer]; +} + +#pragma mark - + +- (void)testThatPropertyListResponseSerializerHandles204 { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:204 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"application/x-plist"}]; + NSError *error; + id responseObject = [self.responseSerializer responseObjectForResponse:response data:nil error:&error]; + + XCTAssertNil(responseObject, @"Response should be nil when handling 204 with application/x-plist"); + XCTAssertNil(error, @"Error handling application/x-plist"); +} + +- (void)testResponseSerializerCanBeCopied { + AFPropertyListResponseSerializer *copiedSerializer = [self.responseSerializer copy]; + XCTAssertNotNil(copiedSerializer); + XCTAssertNotEqual(copiedSerializer, self.responseSerializer); + XCTAssertTrue(copiedSerializer.format == self.responseSerializer.format); + XCTAssertTrue(copiedSerializer.readOptions == self.responseSerializer.readOptions); +} + +- (void)testResponseSerializerCanBeArchivedAndUnarchived { + NSData *archive = [NSKeyedArchiver archivedDataWithRootObject:self.responseSerializer]; + XCTAssertNotNil(archive); + AFPropertyListResponseSerializer *unarchivedSerializer = [NSKeyedUnarchiver unarchiveObjectWithData:archive]; + XCTAssertNotNil(unarchivedSerializer); + XCTAssertNotEqual(unarchivedSerializer, self.responseSerializer); + XCTAssertTrue(unarchivedSerializer.format == self.responseSerializer.format); + XCTAssertTrue(unarchivedSerializer.readOptions == self.responseSerializer.readOptions); +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFSecurityPolicyTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFSecurityPolicyTests.m new file mode 100644 index 00000000..4d660eb5 --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFSecurityPolicyTests.m @@ -0,0 +1,654 @@ +// AFSecurityPolicyTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "AFTestCase.h" +#import "AFSecurityPolicy.h" + +@interface AFSecurityPolicyTests : AFTestCase + +@end + +static SecTrustRef AFUTTrustChainForCertsInDirectory(NSString *directoryPath) { + NSArray *certFileNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:nil]; + NSMutableArray *certs = [NSMutableArray arrayWithCapacity:[certFileNames count]]; + for (NSString *path in certFileNames) { + NSData *certData = [NSData dataWithContentsOfFile:[directoryPath stringByAppendingPathComponent:path]]; + SecCertificateRef cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData)); + [certs addObject:(__bridge id)(cert)]; + } + + SecPolicyRef policy = SecPolicyCreateBasicX509(); + SecTrustRef trust = NULL; + SecTrustCreateWithCertificates((__bridge CFTypeRef)(certs), policy, &trust); + CFRelease(policy); + + return trust; +} + +static SecTrustRef AFUTHTTPBinOrgServerTrust() { + NSString *bundlePath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] resourcePath]; + NSString *serverCertDirectoryPath = [bundlePath stringByAppendingPathComponent:@"HTTPBinOrgServerTrustChain"]; + + return AFUTTrustChainForCertsInDirectory(serverCertDirectoryPath); +} + +static SecTrustRef AFUTADNNetServerTrust() { + NSString *bundlePath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] resourcePath]; + NSString *serverCertDirectoryPath = [bundlePath stringByAppendingPathComponent:@"ADNNetServerTrustChain"]; + + return AFUTTrustChainForCertsInDirectory(serverCertDirectoryPath); +} + +static SecTrustRef AFUTGoogleComServerTrustPath1() { + NSString *bundlePath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] resourcePath]; + NSString *serverCertDirectoryPath = [bundlePath stringByAppendingPathComponent:@"GoogleComServerTrustChainPath1"]; + + return AFUTTrustChainForCertsInDirectory(serverCertDirectoryPath); +} + +static SecTrustRef AFUTGoogleComServerTrustPath2() { + NSString *bundlePath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] resourcePath]; + NSString *serverCertDirectoryPath = [bundlePath stringByAppendingPathComponent:@"GoogleComServerTrustChainPath2"]; + + return AFUTTrustChainForCertsInDirectory(serverCertDirectoryPath); +} + +static SecCertificateRef AFUTHTTPBinOrgCertificate() { + NSString *certPath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] pathForResource:@"httpbinorg_01192017" ofType:@"cer"]; + NSCAssert(certPath != nil, @"Path for certificate should not be nil"); + NSData *certData = [NSData dataWithContentsOfFile:certPath]; + + return SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData)); +} + +static SecCertificateRef AFUTCOMODORSADomainValidationSecureServerCertificate() { + NSString *certPath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] pathForResource:@"COMODO_RSA_Domain_Validation_Secure_Server_CA" ofType:@"cer"]; + NSCAssert(certPath != nil, @"Path for certificate should not be nil"); + NSData *certData = [NSData dataWithContentsOfFile:certPath]; + + return SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData)); +} + +static SecCertificateRef AFUTCOMODORSACertificate() { + NSString *certPath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] pathForResource:@"COMODO_RSA_Certification_Authority" ofType:@"cer"]; + NSCAssert(certPath != nil, @"Path for certificate should not be nil"); + NSData *certData = [NSData dataWithContentsOfFile:certPath]; + + return SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData)); +} + +static SecCertificateRef AFUTAddTrustExternalRootCertificate() { + NSString *certPath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] pathForResource:@"AddTrust_External_CA_Root" ofType:@"cer"]; + NSCAssert(certPath != nil, @"Path for certificate should not be nil"); + NSData *certData = [NSData dataWithContentsOfFile:certPath]; + + return SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData)); +} + +static SecCertificateRef AFUTGoogleComEquifaxSecureCARootCertificate() { + NSString *certPath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] pathForResource:@"Equifax_Secure_Certificate_Authority_Root" ofType:@"cer"]; + NSCAssert(certPath != nil, @"Path for certificate should not be nil"); + NSData *certData = [NSData dataWithContentsOfFile:certPath]; + + return SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData)); +} + +static SecCertificateRef AFUTGoogleComGeoTrustGlobalCARootCertificate() { + NSString *certPath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] pathForResource:@"GeoTrust_Global_CA_Root" ofType:@"cer"]; + NSCAssert(certPath != nil, @"Path for certificate should not be nil"); + NSData *certData = [NSData dataWithContentsOfFile:certPath]; + + return SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData)); +} + +static SecCertificateRef AFUTSelfSignedCertificateWithoutDomain() { + NSString *certPath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] pathForResource:@"NoDomains" ofType:@"cer"]; + NSCAssert(certPath != nil, @"Path for certificate should not be nil"); + NSData *certData = [NSData dataWithContentsOfFile:certPath]; + + return SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData)); +} + +static SecCertificateRef AFUTSelfSignedCertificateWithCommonNameDomain() { + NSString *certPath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] pathForResource:@"foobar.com" ofType:@"cer"]; + NSCAssert(certPath != nil, @"Path for certificate should not be nil"); + NSData *certData = [NSData dataWithContentsOfFile:certPath]; + + return SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData)); +} + +static SecCertificateRef AFUTSelfSignedCertificateWithDNSNameDomain() { + NSString *certPath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] pathForResource:@"AltName" ofType:@"cer"]; + NSCAssert(certPath != nil, @"Path for certificate should not be nil"); + NSData *certData = [NSData dataWithContentsOfFile:certPath]; + + return SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData)); +} + +static SecTrustRef AFUTTrustWithCertificate(SecCertificateRef certificate) { + NSArray *certs = @[(__bridge id)(certificate)]; + + SecPolicyRef policy = SecPolicyCreateBasicX509(); + SecTrustRef trust = NULL; + SecTrustCreateWithCertificates((__bridge CFTypeRef)(certs), policy, &trust); + CFRelease(policy); + + return trust; +} + +@implementation AFSecurityPolicyTests + +#pragma mark - Default Policy Tests +#pragma mark Default Values Test + +- (void)testDefaultPolicyPinningModeIsSetToNone { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + XCTAssertTrue(policy.SSLPinningMode == AFSSLPinningModeNone, @"Pinning Mode should be set to by default"); +} + +- (void)testDefaultPolicyHasInvalidCertificatesAreDisabledByDefault { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + XCTAssertFalse(policy.allowInvalidCertificates, @"Invalid Certificates Should Be Disabled by Default"); +} + +- (void)testDefaultPolicyHasDomainNamesAreValidatedByDefault { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + XCTAssertTrue(policy.validatesDomainName, @"Domain names should be validated by default"); +} + +- (void)testDefaultPolicyHasNoPinnedCertificates { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + XCTAssertTrue(policy.pinnedCertificates.count == 0, @"The default policy should not have any pinned certificates"); +} + +#pragma mark Positive Server Trust Evaluation Tests + +- (void)testDefaultPolicyDoesAllowHTTPBinOrgCertificate { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + SecTrustRef trust = AFUTHTTPBinOrgServerTrust(); + XCTAssertTrue([policy evaluateServerTrust:trust forDomain:nil], @"Valid Certificate should be allowed by default."); +} + +- (void)testDefaultPolicyDoesAllowHTTPBinOrgCertificateForValidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + SecTrustRef trust = AFUTHTTPBinOrgServerTrust(); + XCTAssertTrue([policy evaluateServerTrust:trust forDomain:@"httpbin.org"], @"Valid Certificate should be allowed by default."); +} + +#pragma mark Negative Server Trust Evaluation Tests + +- (void)testDefaultPolicyDoesNotAllowInvalidCertificate { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + SecCertificateRef certificate = AFUTSelfSignedCertificateWithoutDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + XCTAssertFalse([policy evaluateServerTrust:trust forDomain:nil], @"Invalid Certificates should not be allowed"); +} + +- (void)testDefaultPolicyDoesNotAllowCertificateWithInvalidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + SecTrustRef trust = AFUTHTTPBinOrgServerTrust(); + XCTAssertFalse([policy evaluateServerTrust:trust forDomain:@"apple.com"], @"Certificate should not be allowed because the domain names do not match."); +} + +#pragma mark - Public Key Pinning Tests +#pragma mark Default Values Tests + +- (void)testPolicyWithPublicKeyPinningModeHasPinnedCertificates { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + XCTAssertTrue(policy.pinnedCertificates > 0, @"Policy should contain default pinned certificates"); +} + +- (void)testPolicyWithPublicKeyPinningModeHasHTTPBinOrgPinnedCertificate { + NSBundle *bundle = [NSBundle bundleForClass:[self class]]; + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey withPinnedCertificates:[AFSecurityPolicy certificatesInBundle:bundle]]; + + SecCertificateRef cert = AFUTHTTPBinOrgCertificate(); + NSData *certData = (__bridge NSData *)(SecCertificateCopyData(cert)); + CFRelease(cert); + NSSet *set = [policy.pinnedCertificates objectsPassingTest:^BOOL(NSData *data, BOOL *stop) { + return [data isEqualToData:certData]; + }]; + + XCTAssertEqual(set.count, 1, @"HTTPBin.org certificate not found in the default certificates"); +} + +#pragma mark Positive Server Trust Evaluation Tests +- (void)testPolicyWithPublicKeyPinningAllowsHTTPBinOrgServerTrustWithHTTPBinOrgLeafCertificatePinned { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef certificate = AFUTHTTPBinOrgCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow server trust"); +} + +- (void)testPolicyWithPublicKeyPinningAllowsHTTPBinOrgServerTrustWithHTTPBinOrgIntermediate1CertificatePinned { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef certificate = AFUTCOMODORSADomainValidationSecureServerCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow server trust"); +} + +- (void)testPolicyWithPublicKeyPinningAllowsHTTPBinOrgServerTrustWithHTTPBinOrgIntermediate2CertificatePinned { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef certificate = AFUTCOMODORSACertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow server trust"); +} + +- (void)testPolicyWithPublicKeyPinningAllowsHTTPBinOrgServerTrustWithHTTPBinOrgRootCertificatePinned { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef certificate = AFUTAddTrustExternalRootCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow server trust"); +} + +- (void)testPolicyWithPublicKeyPinningAllowsHTTPBinOrgServerTrustWithEntireCertificateChainPinned { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef httpBinCertificate = AFUTHTTPBinOrgCertificate(); + SecCertificateRef intermedaite1Certificate = AFUTCOMODORSADomainValidationSecureServerCertificate(); + SecCertificateRef intermedaite2Certificate = AFUTCOMODORSACertificate(); + SecCertificateRef rootCertificate = AFUTAddTrustExternalRootCertificate(); + [policy setPinnedCertificates:[NSSet setWithObjects:(__bridge_transfer NSData *)SecCertificateCopyData(httpBinCertificate), + (__bridge_transfer NSData *)SecCertificateCopyData(intermedaite1Certificate), + (__bridge_transfer NSData *)SecCertificateCopyData(intermedaite2Certificate), + (__bridge_transfer NSData *)SecCertificateCopyData(rootCertificate), nil]]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow HTTPBinOrg server trust because at least one of the pinned certificates is valid"); + +} + +- (void)testPolicyWithPublicKeyPinningAllowsHTTPBirnOrgServerTrustWithHTTPbinOrgPinnedCertificateAndAdditionalPinnedCertificates { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef httpBinCertificate = AFUTHTTPBinOrgCertificate(); + SecCertificateRef selfSignedCertificate = AFUTSelfSignedCertificateWithCommonNameDomain(); + [policy setPinnedCertificates:[NSSet setWithObjects:(__bridge_transfer NSData *)SecCertificateCopyData(httpBinCertificate), + (__bridge_transfer NSData *)SecCertificateCopyData(selfSignedCertificate), nil]]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow HTTPBinOrg server trust because at least one of the pinned certificates is valid"); +} + +- (void)testPolicyWithPublicKeyPinningAllowsHTTPBinOrgServerTrustWithHTTPBinOrgLeafCertificatePinnedAndValidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef certificate = AFUTHTTPBinOrgCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:@"httpbin.org"], @"Policy should allow server trust"); +} + +#pragma mark Negative Server Trust Evaluation Tests + +- (void)testPolicyWithPublicKeyPinningAndNoPinnedCertificatesDoesNotAllowHTTPBinOrgServerTrust { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + policy.pinnedCertificates = [NSSet set]; + XCTAssertFalse([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should not allow server trust because the policy is set to public key pinning and it does not contain any pinned certificates."); +} + +- (void)testPolicyWithPublicKeyPinningDoesNotAllowADNServerTrustWithHTTPBinOrgPinnedCertificate { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef certificate = AFUTHTTPBinOrgCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertFalse([policy evaluateServerTrust:AFUTADNNetServerTrust() forDomain:nil], @"Policy should not allow ADN server trust for pinned HTTPBin.org certificate"); +} + +- (void)testPolicyWithPublicKeyPinningDoesNotAllowHTTPBinOrgServerTrustWithHTTPBinOrgLeafCertificatePinnedAndInvalidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef certificate = AFUTHTTPBinOrgCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertFalse([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:@"invaliddomainname.com"], @"Policy should not allow server trust"); +} + +- (void)testPolicyWithPublicKeyPinningDoesNotAllowADNServerTrustWithMultipleInvalidPinnedCertificates { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef httpBinCertificate = AFUTHTTPBinOrgCertificate(); + SecCertificateRef selfSignedCertificate = AFUTSelfSignedCertificateWithCommonNameDomain(); + [policy setPinnedCertificates:[NSSet setWithObjects:(__bridge_transfer NSData *)SecCertificateCopyData(httpBinCertificate), + (__bridge_transfer NSData *)SecCertificateCopyData(selfSignedCertificate), nil]]; + XCTAssertFalse([policy evaluateServerTrust:AFUTADNNetServerTrust() forDomain:nil], @"Policy should not allow ADN server trust because there are no matching pinned certificates"); +} + +#pragma mark - Certificate Pinning Tests +#pragma mark Default Values Tests + +- (void)testPolicyWithCertificatePinningModeHasPinnedCertificates { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + XCTAssertTrue(policy.pinnedCertificates > 0, @"Policy should contain default pinned certificates"); +} + +- (void)testPolicyWithCertificatePinningModeHasHTTPBinOrgPinnedCertificate { + NSBundle *bundle = [NSBundle bundleForClass:[self class]]; + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:[AFSecurityPolicy certificatesInBundle:bundle]]; + + SecCertificateRef cert = AFUTHTTPBinOrgCertificate(); + NSData *certData = (__bridge NSData *)(SecCertificateCopyData(cert)); + CFRelease(cert); + NSSet *set = [policy.pinnedCertificates objectsPassingTest:^BOOL(NSData *data, BOOL *stop) { + return [data isEqualToData:certData]; + }]; + + XCTAssertEqual(set.count, 1, @"HTTPBin.org certificate not found in the default certificates"); +} + +#pragma mark Positive Server Trust Evaluation Tests +- (void)testPolicyWithCertificatePinningAllowsHTTPBinOrgServerTrustWithHTTPBinOrgLeafCertificatePinned { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef certificate = AFUTHTTPBinOrgCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow server trust"); +} + +- (void)testPolicyWithCertificatePinningAllowsHTTPBinOrgServerTrustWithHTTPBinOrgIntermediate1CertificatePinned { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef certificate = AFUTCOMODORSADomainValidationSecureServerCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow server trust"); +} + +- (void)testPolicyWithCertificatePinningAllowsHTTPBinOrgServerTrustWithHTTPBinOrgIntermediate2CertificatePinned { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef certificate = AFUTCOMODORSACertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow server trust"); +} + +- (void)testPolicyWithCertificatePinningAllowsHTTPBinOrgServerTrustWithHTTPBinOrgRootCertificatePinned { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef certificate = AFUTAddTrustExternalRootCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow server trust"); +} + +- (void)testPolicyWithCertificatePinningAllowsHTTPBinOrgServerTrustWithEntireCertificateChainPinned { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef httpBinCertificate = AFUTHTTPBinOrgCertificate(); + SecCertificateRef intermedaite1Certificate = AFUTCOMODORSADomainValidationSecureServerCertificate(); + SecCertificateRef intermedaite2Certificate = AFUTCOMODORSACertificate(); + SecCertificateRef rootCertificate = AFUTAddTrustExternalRootCertificate(); + [policy setPinnedCertificates:[NSSet setWithObjects:(__bridge_transfer NSData *)SecCertificateCopyData(httpBinCertificate), + (__bridge_transfer NSData *)SecCertificateCopyData(intermedaite1Certificate), + (__bridge_transfer NSData *)SecCertificateCopyData(intermedaite2Certificate), + (__bridge_transfer NSData *)SecCertificateCopyData(rootCertificate), nil]]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow HTTPBinOrg server trust because at least one of the pinned certificates is valid"); + +} + +- (void)testPolicyWithCertificatePinningAllowsHTTPBirnOrgServerTrustWithHTTPbinOrgPinnedCertificateAndAdditionalPinnedCertificates { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef httpBinCertificate = AFUTHTTPBinOrgCertificate(); + SecCertificateRef selfSignedCertificate = AFUTSelfSignedCertificateWithCommonNameDomain(); + [policy setPinnedCertificates:[NSSet setWithObjects:(__bridge_transfer NSData *)SecCertificateCopyData(httpBinCertificate), + (__bridge_transfer NSData *)SecCertificateCopyData(selfSignedCertificate), nil]]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow HTTPBinOrg server trust because at least one of the pinned certificates is valid"); +} + +- (void)testPolicyWithCertificatePinningAllowsHTTPBinOrgServerTrustWithHTTPBinOrgLeafCertificatePinnedAndValidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef certificate = AFUTHTTPBinOrgCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:@"httpbin.org"], @"Policy should allow server trust"); +} + +//- (void)testPolicyWithCertificatePinningAllowsGoogleComServerTrustIncompleteChainWithRootCertificatePinnedAndValidDomainName { +// //TODO THIS TEST HAS BEEN DISABLED UNTIL CERTS HAVE BEEN UPDATED. +// //Please see conversation here: https://github.com/AFNetworking/AFNetworking/pull/3159#issuecomment-178647437 +// // +// // Fix certificate validation for servers providing incomplete chains (#3159) - test case +// // +// // google.com has two certification paths and both send incomplete certificate chains, i.e. don't include the Root CA +// // (this can be validated in https://www.ssllabs.com/ssltest/analyze.html?d=google.com) +// // +// // The two certification paths are: +// // - Path 1: *.google.com, Google Internet Authority G2 (with GeoTrust Global CA Root) +// // - Path 2: *.google.com, Google Internet Authority G2, GeoTrust Global CA (cross signed) (with Equifax Secure CA Root) +// // +// // The common goal of using certificate pinning is to prevent MiTM (man-in-the-middle) attacks, so the Root CA's should be pinned to protect the entire chains. +// // Since there's no Root CA being sent, when `-evaluateServerTrust:` invokes `AFCertificateTrustChainForServerTrust(serverTrust)`, the Root CA isn't present +// // Therefore, even though `AFServerTrustIsValid(serverTrust)` succeeds, the next validation fails since no pinned certificate matches the `pinnedCertificates`. +// // By fetching the `AFCertificateTrustChainForServerTrust(serverTrust)` *after* the `AFServerTrustIsValid(serverTrust)` validation, the complete chain is obtained and the Root CA's match. +// +// AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; +// +// // certification path 1 +// SecCertificateRef certificate = AFUTGoogleComGeoTrustGlobalCARootCertificate(); +// policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; +// +// XCTAssertTrue([policy evaluateServerTrust:AFUTGoogleComServerTrustPath1() forDomain:@"google.com"], @"Policy should allow server trust"); +// +// // certification path 2 +// certificate = AFUTGoogleComEquifaxSecureCARootCertificate(); +// policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; +// +// XCTAssertTrue([policy evaluateServerTrust:AFUTGoogleComServerTrustPath2() forDomain:@"google.com"], @"Policy should allow server trust"); +//} + +#pragma mark Negative Server Trust Evaluation Tests + +- (void)testPolicyWithCertificatePinningAndNoPinnedCertificatesDoesNotAllowHTTPBinOrgServerTrust { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + policy.pinnedCertificates = [NSSet set]; + XCTAssertFalse([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should not allow server trust because the policy does not contain any pinned certificates."); +} + +- (void)testPolicyWithCertificatePinningDoesNotAllowADNServerTrustWithHTTPBinOrgPinnedCertificate { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef certificate = AFUTHTTPBinOrgCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertFalse([policy evaluateServerTrust:AFUTADNNetServerTrust() forDomain:nil], @"Policy should not allow ADN server trust for pinned HTTPBin.org certificate"); +} + +- (void)testPolicyWithCertificatePinningDoesNotAllowHTTPBinOrgServerTrustWithHTTPBinOrgLeafCertificatePinnedAndInvalidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef certificate = AFUTHTTPBinOrgCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertFalse([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:@"invaliddomainname.com"], @"Policy should not allow server trust"); +} + +- (void)testPolicyWithCertificatePinningDoesNotAllowADNServerTrustWithMultipleInvalidPinnedCertificates { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef httpBinCertificate = AFUTHTTPBinOrgCertificate(); + SecCertificateRef selfSignedCertificate = AFUTSelfSignedCertificateWithCommonNameDomain(); + [policy setPinnedCertificates:[NSSet setWithObjects:(__bridge_transfer NSData *)SecCertificateCopyData(httpBinCertificate), + (__bridge_transfer NSData *)SecCertificateCopyData(selfSignedCertificate), nil]]; + XCTAssertFalse([policy evaluateServerTrust:AFUTADNNetServerTrust() forDomain:nil], @"Policy should not allow ADN server trust because there are no matching pinned certificates"); +} + +#pragma mark - Domain Name Validation Tests +#pragma mark Positive Evaluation Tests + +- (void)testThatPolicyWithoutDomainNameValidationAllowsServerTrustWithInvalidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + [policy setValidatesDomainName:NO]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:@"invalid.org"], @"Policy should allow server trust because domain name validation is disabled"); +} + +- (void)testThatPolicyWithDomainNameValidationAllowsServerTrustWithValidWildcardDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:@"test.httpbin.org"], @"Policy should allow server trust"); +} + +- (void)testThatPolicyWithDomainNameValidationAndSelfSignedCommonNameCertificateAllowsServerTrust { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef certificate = AFUTSelfSignedCertificateWithCommonNameDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + [policy setPinnedCertificates:[NSSet setWithObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]]; + [policy setAllowInvalidCertificates:YES]; + + XCTAssertTrue([policy evaluateServerTrust:trust forDomain:@"foobar.com"], @"Policy should allow server trust"); +} + +- (void)testThatPolicyWithDomainNameValidationAndSelfSignedDNSCertificateAllowsServerTrust { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef certificate = AFUTSelfSignedCertificateWithDNSNameDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + [policy setPinnedCertificates:[NSSet setWithObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]]; + [policy setAllowInvalidCertificates:YES]; + + XCTAssertTrue([policy evaluateServerTrust:trust forDomain:@"foobar.com"], @"Policy should allow server trust"); +} + +#pragma mark Negative Evaluation Tests + +- (void)testThatPolicyWithDomainNameValidationDoesNotAllowServerTrustWithInvalidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + XCTAssertFalse([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:@"invalid.org"], @"Policy should not allow allow server trust"); +} + +- (void)testThatPolicyWithDomainNameValidationAndSelfSignedNoDomainCertificateDoesNotAllowServerTrust { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef certificate = AFUTSelfSignedCertificateWithoutDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + [policy setPinnedCertificates:[NSSet setWithObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]]; + [policy setAllowInvalidCertificates:YES]; + + XCTAssertFalse([policy evaluateServerTrust:trust forDomain:@"foobar.com"], @"Policy should not allow server trust"); +} + +#pragma mark - Self Signed Certificate Tests +#pragma mark Positive Test Cases + +- (void)testThatPolicyWithInvalidCertificatesAllowedAllowsSelfSignedServerTrust { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + [policy setAllowInvalidCertificates:YES]; + + SecCertificateRef certificate = AFUTSelfSignedCertificateWithDNSNameDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + + XCTAssertTrue([policy evaluateServerTrust:trust forDomain:nil], @"Policy should allow server trust because invalid certificates are allowed"); +} + +- (void)testThatPolicyWithInvalidCertificatesAllowedAndValidPinnedCertificatesDoesAllowSelfSignedServerTrustForValidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + [policy setAllowInvalidCertificates:YES]; + SecCertificateRef certificate = AFUTSelfSignedCertificateWithDNSNameDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + [policy setPinnedCertificates:[NSSet setWithObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]]; + + XCTAssertTrue([policy evaluateServerTrust:trust forDomain:@"foobar.com"], @"Policy should allow server trust because invalid certificates are allowed"); +} + +- (void)testThatPolicyWithInvalidCertificatesAllowedAndNoSSLPinningAndDomainNameValidationDisabledDoesAllowSelfSignedServerTrustForValidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; + [policy setAllowInvalidCertificates:YES]; + [policy setValidatesDomainName:NO]; + + SecCertificateRef certificate = AFUTSelfSignedCertificateWithDNSNameDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + + XCTAssertTrue([policy evaluateServerTrust:trust forDomain:@"foobar.com"], @"Policy should allow server trust because invalid certificates are allowed"); +} + +#pragma mark Negative Test Cases + +- (void)testThatPolicyWithInvalidCertificatesDisabledDoesNotAllowSelfSignedServerTrust { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + + SecCertificateRef certificate = AFUTSelfSignedCertificateWithDNSNameDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + + XCTAssertFalse([policy evaluateServerTrust:trust forDomain:nil], @"Policy should not allow server trust because invalid certificates are not allowed"); +} + +- (void)testThatPolicyWithInvalidCertificatesAllowedAndNoPinnedCertificatesAndPublicKeyPinningModeDoesNotAllowSelfSignedServerTrustForValidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + [policy setAllowInvalidCertificates:YES]; + [policy setPinnedCertificates:[NSSet set]]; + SecCertificateRef certificate = AFUTSelfSignedCertificateWithDNSNameDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + + XCTAssertFalse([policy evaluateServerTrust:trust forDomain:@"foobar.com"], @"Policy should not allow server trust because invalid certificates are allowed but there are no pinned certificates"); +} + +- (void)testThatPolicyWithInvalidCertificatesAllowedAndValidPinnedCertificatesAndNoPinningModeDoesNotAllowSelfSignedServerTrustForValidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; + [policy setAllowInvalidCertificates:YES]; + SecCertificateRef certificate = AFUTSelfSignedCertificateWithDNSNameDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + [policy setPinnedCertificates:[NSSet setWithObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]]; + + XCTAssertFalse([policy evaluateServerTrust:trust forDomain:@"foobar.com"], @"Policy should not allow server trust because invalid certificates are allowed but there are no pinned certificates"); +} + +- (void)testThatPolicyWithInvalidCertificatesAllowedAndNoValidPinnedCertificatesAndNoPinningModeAndDomainValidationDoesNotAllowSelfSignedServerTrustForValidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; + [policy setAllowInvalidCertificates:YES]; + [policy setPinnedCertificates:[NSSet set]]; + + SecCertificateRef certificate = AFUTSelfSignedCertificateWithDNSNameDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + + XCTAssertFalse([policy evaluateServerTrust:trust forDomain:@"foobar.com"], @"Policy should not allow server trust because invalid certificates are allowed but there are no pinned certificates"); +} + +#pragma mark - NSCopying +- (void)testThatPolicyCanBeCopied { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + policy.allowInvalidCertificates = YES; + policy.validatesDomainName = NO; + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(AFUTHTTPBinOrgCertificate())]; + + AFSecurityPolicy *copiedPolicy = [policy copy]; + XCTAssertNotEqual(copiedPolicy, policy); + XCTAssertEqual(copiedPolicy.allowInvalidCertificates, policy.allowInvalidCertificates); + XCTAssertEqual(copiedPolicy.validatesDomainName, policy.validatesDomainName); + XCTAssertEqual(copiedPolicy.SSLPinningMode, policy.SSLPinningMode); + XCTAssertTrue([copiedPolicy.pinnedCertificates isEqualToSet:policy.pinnedCertificates]); +} + +- (void)testThatPolicyCanBeEncodedAndDecoded { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + policy.allowInvalidCertificates = YES; + policy.validatesDomainName = NO; + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(AFUTHTTPBinOrgCertificate())]; + + NSMutableData *archiveData = [NSMutableData new]; + NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:archiveData]; + [archiver encodeObject:policy forKey:@"policy"]; + [archiver finishEncoding]; + + NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:archiveData]; + AFSecurityPolicy *unarchivedPolicy = [unarchiver decodeObjectOfClass:[AFSecurityPolicy class] forKey:@"policy"]; + + XCTAssertNotEqual(unarchivedPolicy, policy); + XCTAssertEqual(unarchivedPolicy.allowInvalidCertificates, policy.allowInvalidCertificates); + XCTAssertEqual(unarchivedPolicy.validatesDomainName, policy.validatesDomainName); + XCTAssertEqual(unarchivedPolicy.SSLPinningMode, policy.SSLPinningMode); + XCTAssertTrue([unarchivedPolicy.pinnedCertificates isEqualToSet:policy.pinnedCertificates]); +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFTestCase.h b/its/plugin/projects/AFNetworking/Tests/Tests/AFTestCase.h new file mode 100644 index 00000000..4f0d02ec --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFTestCase.h @@ -0,0 +1,33 @@ +// AFTestCase.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import + +extern NSString * const AFNetworkingTestsBaseURLString; + +@interface AFTestCase : XCTestCase + +@property (nonatomic, strong, readonly) NSURL *baseURL; +@property (nonatomic, assign) NSTimeInterval networkTimeout; + +- (void)waitForExpectationsWithCommonTimeoutUsingHandler:(XCWaitCompletionHandler)handler; + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFTestCase.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFTestCase.m new file mode 100644 index 00000000..489c8ab0 --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFTestCase.m @@ -0,0 +1,47 @@ +// AFTestCase.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "AFTestCase.h" + +NSString * const AFNetworkingTestsBaseURLString = @"https://httpbin.org/"; + +@implementation AFTestCase + +- (void)setUp { + [super setUp]; + self.networkTimeout = 20.0; +} + +- (void)tearDown { + [super tearDown]; +} + +#pragma mark - + +- (NSURL *)baseURL { + return [NSURL URLWithString:AFNetworkingTestsBaseURLString]; +} + +- (void)waitForExpectationsWithCommonTimeoutUsingHandler:(XCWaitCompletionHandler)handler { + [self waitForExpectationsWithTimeout:self.networkTimeout handler:handler]; +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFUIActivityIndicatorViewTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFUIActivityIndicatorViewTests.m new file mode 100644 index 00000000..89202f3e --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFUIActivityIndicatorViewTests.m @@ -0,0 +1,111 @@ +// AFUIActivityIndicatorViewTests.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "AFTestCase.h" +#import "UIActivityIndicatorView+AFNetworking.h" +#import "AFURLSessionManager.h" + +@interface AFUIActivityIndicatorViewTests : AFTestCase +@property (nonatomic, strong) NSURLRequest *request; +@property (nonatomic, strong) UIActivityIndicatorView *activityIndicatorView; +@property (nonatomic, strong) AFURLSessionManager *sessionManager; +@end + +@implementation AFUIActivityIndicatorViewTests + +- (void)setUp { + [super setUp]; + self.activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite]; + self.request = [NSURLRequest requestWithURL:[self.baseURL URLByAppendingPathComponent:@"delay/1"]]; + self.sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:nil]; +} + +- (void)tearDown { + [super tearDown]; + [self.sessionManager invalidateSessionCancelingTasks:YES]; + self.sessionManager = nil; +} + +- (void)testTaskDidResumeNotificationDoesNotCauseCrashForAIVWithTask { + XCTestExpectation *expectation = [self expectationWithDescription:@"No Crash"]; + [self expectationForNotification:AFNetworkingTaskDidResumeNotification object:nil handler:nil]; + NSURLSessionDataTask *task = [self.sessionManager + dataTaskWithRequest:self.request + completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + [expectation fulfill]; + }]; + + [self.activityIndicatorView setAnimatingWithStateOfTask:task]; + self.activityIndicatorView = nil; + + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + [task cancel]; +} + + +- (void)testTaskDidCompleteNotificationDoesNotCauseCrashForAIVWithTask { + XCTestExpectation *expectation = [self expectationWithDescription:@"No Crash"]; + [self expectationForNotification:AFNetworkingTaskDidCompleteNotification object:nil handler:nil]; + NSURLSessionDataTask *task = [self.sessionManager + dataTaskWithRequest:self.request + completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + //Without the dispatch after, this test would PASS errorenously because the test + //would finish before the notification was posted to all objects that were + //observing it. + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + [expectation fulfill]; + }); + }]; + + [self.activityIndicatorView setAnimatingWithStateOfTask:task]; + self.activityIndicatorView = nil; + + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + [task cancel]; +} + +- (void)testTaskDidSuspendNotificationDoesNotCauseCrashForAIVWithTask { + XCTestExpectation *expectation = [self expectationWithDescription:@"No Crash"]; + [self expectationForNotification:AFNetworkingTaskDidSuspendNotification object:nil handler:nil]; + NSURLSessionDataTask *task = [self.sessionManager + dataTaskWithRequest:self.request + completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + //Without the dispatch after, this test would PASS errorenously because the test + //would finish before the notification was posted to all objects that were + //observing it. + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + [expectation fulfill]; + }); + }]; + + [self.activityIndicatorView setAnimatingWithStateOfTask:task]; + self.activityIndicatorView = nil; + + [task resume]; + [task suspend]; + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + [task cancel]; +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFUIButtonTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFUIButtonTests.m new file mode 100644 index 00000000..6aea93b0 --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFUIButtonTests.m @@ -0,0 +1,115 @@ +// AFUIButtonTests.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import +#import "AFTestCase.h" +#import "UIButton+AFNetworking.h" +#import "AFImageDownloader.h" + +@interface AFUIButtonTests : AFTestCase +@property (nonatomic, strong) UIImage *cachedImage; +@property (nonatomic, strong) NSURLRequest *cachedImageRequest; +@property (nonatomic, strong) UIButton *button; + +@property (nonatomic, strong) NSURL *error404URL; +@property (nonatomic, strong) NSURLRequest *error404URLRequest; + +@property (nonatomic, strong) NSURL *jpegURL; +@property (nonatomic, strong) NSURLRequest *jpegURLRequest; +@end + +@implementation AFUIButtonTests + +- (void)setUp { + [super setUp]; + [[UIButton sharedImageDownloader].imageCache removeAllImages]; + [[[[[[UIButton sharedImageDownloader] sessionManager] session] configuration] URLCache] removeAllCachedResponses]; + [UIButton setSharedImageDownloader:[[AFImageDownloader alloc] init]]; + + self.button = [UIButton new]; + + self.jpegURL = [NSURL URLWithString:@"https://httpbin.org/image/jpeg"]; + self.jpegURLRequest = [NSURLRequest requestWithURL:self.jpegURL]; + + self.error404URL = [NSURL URLWithString:@"https://httpbin.org/status/404"]; + self.error404URLRequest = [NSURLRequest requestWithURL:self.error404URL]; + +} + +- (void)tearDown { + self.button = nil; + [super tearDown]; + +} + +- (void)testThatBackgroundImageChanges { + XCTAssertNil([self.button backgroundImageForState:UIControlStateNormal]); + [self.button setBackgroundImageForState:UIControlStateNormal withURL:self.jpegURL]; + NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(UIButton * _Nonnull button, NSDictionary * _Nullable bindings) { + return [button backgroundImageForState:UIControlStateNormal] != nil; + }]; + + [self expectationForPredicate:predicate + evaluatedWithObject:self.button + handler:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testThatForegroundImageCanBeCancelledAndDownloadedImmediately { + //https://github.com/Alamofire/AlamofireImage/issues/55 + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.button setImageForState:UIControlStateNormal withURL:self.jpegURL]; + [self.button cancelImageDownloadTaskForState:UIControlStateNormal]; + __block UIImage *responseImage; + [self.button + setImageForState:UIControlStateNormal + withURLRequest:self.jpegURLRequest + placeholderImage:nil + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) { + responseImage = image; + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + XCTAssertNotNil(responseImage); +} + +- (void)testThatBackgroundImageCanBeCancelledAndDownloadedImmediately { + //https://github.com/Alamofire/AlamofireImage/issues/55 + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.button setBackgroundImageForState:UIControlStateNormal withURL:self.jpegURL]; + [self.button cancelBackgroundImageDownloadTaskForState:UIControlStateNormal]; + __block UIImage *responseImage; + [self.button + setBackgroundImageForState:UIControlStateNormal + withURLRequest:self.jpegURLRequest + placeholderImage:nil + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) { + responseImage = image; + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + XCTAssertNotNil(responseImage); +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFUIImageViewTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFUIImageViewTests.m new file mode 100644 index 00000000..9261fc5c --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFUIImageViewTests.m @@ -0,0 +1,155 @@ +// AFUIImageViewTests.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "AFTestCase.h" +#import "UIImageView+AFNetworking.h" +#import "AFImageDownloader.h" + +@interface AFUIImageViewTests : AFTestCase +@property (nonatomic, strong) UIImage *cachedImage; +@property (nonatomic, strong) NSURLRequest *cachedImageRequest; +@property (nonatomic, strong) UIImageView *imageView; + +@property (nonatomic, strong) NSURL *error404URL; +@property (nonatomic, strong) NSURLRequest *error404URLRequest; + +@property (nonatomic, strong) NSURL *jpegURL; +@property (nonatomic, strong) NSURLRequest *jpegURLRequest; + +@end + +@implementation AFUIImageViewTests + +- (void)setUp { + [super setUp]; + [[UIImageView sharedImageDownloader].imageCache removeAllImages]; + [[[[[[UIImageView sharedImageDownloader] sessionManager] session] configuration] URLCache] removeAllCachedResponses]; + [UIImageView setSharedImageDownloader:[[AFImageDownloader alloc] init]]; + + self.imageView = [UIImageView new]; + + self.jpegURL = [NSURL URLWithString:@"https://httpbin.org/image/jpeg"]; + self.jpegURLRequest = [NSURLRequest requestWithURL:self.jpegURL]; + + self.error404URL = [NSURL URLWithString:@"https://httpbin.org/status/404"]; + self.error404URLRequest = [NSURLRequest requestWithURL:self.error404URL]; + +} + +- (void)tearDown { + self.imageView = nil; + [super tearDown]; + +} + +- (void)testThatImageCanBeDownloadedFromURL { + XCTAssertNil(self.imageView.image); + [self.imageView setImageWithURL:self.jpegURL]; + [self expectationForPredicate:[NSPredicate predicateWithFormat:@"image != nil"] + evaluatedWithObject:self.imageView + handler:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testThatImageDownloadSucceedsWhenDuplicateRequestIsSentToImageView { + XCTAssertNil(self.imageView.image); + [self.imageView setImageWithURL:self.jpegURL]; + [self.imageView setImageWithURL:self.jpegURL]; + [self expectationForPredicate:[NSPredicate predicateWithFormat:@"image != nil"] + evaluatedWithObject:self.imageView + handler:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testThatPlaceholderImageIsSetIfRequestFails { + UIImage *placeholder = [UIImage imageNamed:@"logo"]; + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should fail"]; + + [self.imageView setImageWithURLRequest:self.error404URLRequest + placeholderImage:placeholder + success:nil + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + [expectation fulfill]; + }]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + XCTAssertEqual(self.imageView.image, placeholder); +} + +- (void)testResponseIsNilWhenLoadedFromCache { + AFImageDownloader *downloader = [UIImageView sharedImageDownloader]; + XCTestExpectation *cacheExpectation = [self expectationWithDescription:@"Cache request should succeed"]; + __block UIImage *downloadImage = nil; + [downloader + downloadImageForURLRequest:self.jpegURLRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + downloadImage = responseObject; + [cacheExpectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + __block UIImage *cachedImage = nil; + __block NSHTTPURLResponse *urlResponse; + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.imageView + setImageWithURLRequest:self.jpegURLRequest + placeholderImage:nil + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) { + urlResponse = response; + cachedImage = image; + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + XCTAssertNil(urlResponse); + XCTAssertNotNil(cachedImage); + XCTAssertEqual(cachedImage, downloadImage); +} + +- (void)testThatImageCanBeCancelledAndDownloadedImmediately { + //https://github.com/Alamofire/AlamofireImage/issues/55 + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.imageView setImageWithURL:self.jpegURL]; + [self.imageView cancelImageDownloadTask]; + __block UIImage *responseImage; + [self.imageView + setImageWithURLRequest:self.jpegURLRequest + placeholderImage:nil + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) { + responseImage = image; + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + XCTAssertNotNil(responseImage); +} + +- (void)testThatNilURLDoesntCrash { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnonnull" + [self.imageView setImageWithURL:nil]; +#pragma clang diagnostic pop + +} + + + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFUIRefreshControlTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFUIRefreshControlTests.m new file mode 100644 index 00000000..6459fc1b --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFUIRefreshControlTests.m @@ -0,0 +1,110 @@ +// AFUIRefreshControlTests.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "AFTestCase.h" +#import "UIRefreshControl+AFNetworking.h" +#import "AFURLSessionManager.h" + +@interface AFUIRefreshControlTests : AFTestCase +@property (nonatomic, strong) NSURLRequest *request; +@property (nonatomic, strong) UIRefreshControl *refreshControl; +@property (nonatomic, strong) AFURLSessionManager *sessionManager; +@end + +@implementation AFUIRefreshControlTests + +- (void)setUp { + [super setUp]; + self.refreshControl = [[UIRefreshControl alloc] init]; + self.request = [NSURLRequest requestWithURL:[self.baseURL URLByAppendingPathComponent:@"delay/1"]]; + self.sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:nil]; +} + +- (void)tearDown { + [super tearDown]; + [self.sessionManager invalidateSessionCancelingTasks:YES]; + self.sessionManager = nil; +} + +- (void)testTaskDidResumeNotificationDoesNotCauseCrashForUIRCWithTask { + XCTestExpectation *expectation = [self expectationWithDescription:@"No Crash"]; + [self expectationForNotification:AFNetworkingTaskDidResumeNotification object:nil handler:nil]; + NSURLSessionDataTask *task = [self.sessionManager + dataTaskWithRequest:self.request + completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + [expectation fulfill]; + }]; + + [self.refreshControl setRefreshingWithStateOfTask:task]; + self.refreshControl = nil; + + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + [task cancel]; +} + +- (void)testTaskDidCompleteNotificationDoesNotCauseCrashForUIRCWithTask { + XCTestExpectation *expectation = [self expectationWithDescription:@"No Crash"]; + [self expectationForNotification:AFNetworkingTaskDidCompleteNotification object:nil handler:nil]; + NSURLSessionDataTask *task = [self.sessionManager + dataTaskWithRequest:self.request + completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + //Without the dispatch after, this test would PASS errorenously because the test + //would finish before the notification was posted to all objects that were + //observing it. + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + [expectation fulfill]; + }); + }]; + + [self.refreshControl setRefreshingWithStateOfTask:task]; + self.refreshControl = nil; + + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + [task cancel]; +} + +- (void)testTaskDidSuspendNotificationDoesNotCauseCrashForUIRCWithTask { + XCTestExpectation *expectation = [self expectationWithDescription:@"No Crash"]; + [self expectationForNotification:AFNetworkingTaskDidSuspendNotification object:nil handler:nil]; + NSURLSessionDataTask *task = [self.sessionManager + dataTaskWithRequest:self.request + completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + //Without the dispatch after, this test would PASS errorenously because the test + //would finish before the notification was posted to all objects that were + //observing it. + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + [expectation fulfill]; + }); + }]; + + [self.refreshControl setRefreshingWithStateOfTask:task]; + self.refreshControl = nil; + + [task resume]; + [task suspend]; + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + [task cancel]; +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFUIWebViewTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFUIWebViewTests.m new file mode 100644 index 00000000..c43b3f90 --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFUIWebViewTests.m @@ -0,0 +1,85 @@ +// AFUIWebViewTests.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import +#import "AFTestCase.h" +#import "UIWebView+AFNetworking.h" + +@interface AFUIWebViewTests : AFTestCase +@property (nonatomic, strong) UIWebView *webView; +@property (nonatomic, strong) NSURLRequest *HTMLRequest; + +@end + +@implementation AFUIWebViewTests + +- (void)setUp { + [super setUp]; + self.webView = [UIWebView new]; + self.HTMLRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/html"]]; +} + +- (void)testNilProgressDoesNotCauseCrash { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.webView + loadRequest:self.HTMLRequest + progress:nil + success:^NSString * _Nonnull(NSHTTPURLResponse * _Nonnull response, NSString * _Nonnull HTML) { + [expectation fulfill]; + return HTML; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testNULLProgressDoesNotCauseCrash { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.webView + loadRequest:self.HTMLRequest + progress:NULL + success:^NSString * _Nonnull(NSHTTPURLResponse * _Nonnull response, NSString * _Nonnull HTML) { + [expectation fulfill]; + return HTML; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testProgressIsSet { + NSProgress* progress = nil; + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.webView + loadRequest:self.HTMLRequest + progress:&progress + success:^NSString * _Nonnull(NSHTTPURLResponse * _Nonnull response, NSString * _Nonnull HTML) { + [expectation fulfill]; + return HTML; + } + failure:nil]; + [self keyValueObservingExpectationForObject:progress + keyPath:@"fractionCompleted" + expectedValue:@(1.0)]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + + + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFURLSessionManagerTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFURLSessionManagerTests.m new file mode 100644 index 00000000..b239267e --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFURLSessionManagerTests.m @@ -0,0 +1,473 @@ +// AFURLSessionManagerTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import + +#import "AFTestCase.h" + +#import "AFURLSessionManager.h" + +@interface AFURLSessionManagerTests : AFTestCase +@property (readwrite, nonatomic, strong) AFURLSessionManager *localManager; +@property (readwrite, nonatomic, strong) AFURLSessionManager *backgroundManager; +@end + + +@implementation AFURLSessionManagerTests + +- (NSURLRequest *)bigImageURLRequest { + NSURL *url = [NSURL URLWithString:@"http://scitechdaily.com/images/New-Image-of-the-Galaxy-Messier-94-also-Known-as-NGC-4736.jpg"]; + NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0]; + return request; +} + +- (void)setUp { + [super setUp]; + self.localManager = [[AFURLSessionManager alloc] init]; + [self.localManager.session.configuration.URLCache removeAllCachedResponses]; + + //Unfortunately, iOS 7 throws an exception when trying to create a background URL Session inside this test target, which means our tests here can only run on iOS 8+ + //Travis actually needs the try catch here. Just doing if ([NSURLSessionConfiguration respondsToSelector:@selector(backgroundSessionWithIdentifier)]) wasn't good enough. + @try { + NSString *identifier = [NSString stringWithFormat:@"com.afnetworking.tests.urlsession.%@", [[NSUUID UUID] UUIDString]]; + NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:identifier]; + self.backgroundManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; + } + @catch (NSException *exception) { + + } +} + +- (void)tearDown { + [super tearDown]; + [self.localManager.session.configuration.URLCache removeAllCachedResponses]; + [self.localManager invalidateSessionCancelingTasks:YES]; + self.localManager = nil; + + [self.backgroundManager invalidateSessionCancelingTasks:YES]; + self.backgroundManager = nil; +} + +#pragma mark Progress - + +- (void)testDataTaskDoesReportDownloadProgress { + NSURLSessionDataTask *task; + + __weak XCTestExpectation *expectation = [self expectationWithDescription:@"Progress should equal 1.0"]; + task = [self.localManager + dataTaskWithRequest:[self bigImageURLRequest] + uploadProgress:nil + downloadProgress:^(NSProgress * _Nonnull downloadProgress) { + if (downloadProgress.fractionCompleted == 1.0) { + [expectation fulfill]; + } + } + completionHandler:nil]; + + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testDataTaskDownloadProgressCanBeKVOd { + NSURLSessionDataTask *task; + + task = [self.localManager + dataTaskWithRequest:[self bigImageURLRequest] + uploadProgress:nil + downloadProgress:nil + completionHandler:nil]; + + NSProgress *progress = [self.localManager downloadProgressForTask:task]; + [self keyValueObservingExpectationForObject:progress keyPath:@"fractionCompleted" + handler:^BOOL(NSProgress *observedProgress, NSDictionary * _Nonnull change) { + double new = [change[@"new"] doubleValue]; + double old = [change[@"old"] doubleValue]; + return new == 1.0 && old != 0.0; + }]; + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testDownloadTaskDoesReportProgress { + __weak XCTestExpectation *expectation = [self expectationWithDescription:@"Progress should equal 1.0"]; + NSURLSessionTask *task; + task = [self.localManager + downloadTaskWithRequest:[self bigImageURLRequest] + progress:^(NSProgress * _Nonnull downloadProgress) { + if (downloadProgress.fractionCompleted == 1.0) { + [expectation fulfill]; + } + } + destination:nil + completionHandler:nil]; + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testUploadTaskDoesReportProgress { + NSMutableString *payload = [NSMutableString stringWithString:@"AFNetworking"]; + while ([payload lengthOfBytesUsingEncoding:NSUTF8StringEncoding] < 20000) { + [payload appendString:@"AFNetworking"]; + } + + NSURL *url = [NSURL URLWithString:[[self.baseURL absoluteString] stringByAppendingString:@"/post"]]; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0]; + [request setHTTPMethod:@"POST"]; + + __weak XCTestExpectation *expectation = [self expectationWithDescription:@"Progress should equal 1.0"]; + + NSURLSessionTask *task; + task = [self.localManager + uploadTaskWithRequest:request + fromData:[payload dataUsingEncoding:NSUTF8StringEncoding] + progress:^(NSProgress * _Nonnull uploadProgress) { + NSLog(@"%@", uploadProgress.localizedDescription); + if ([uploadProgress fractionCompleted] == 1.0) { + [expectation fulfill]; + } + } + completionHandler:nil]; + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testUploadProgressCanBeKVOd { + NSMutableString *payload = [NSMutableString stringWithString:@"AFNetworking"]; + while ([payload lengthOfBytesUsingEncoding:NSUTF8StringEncoding] < 20000) { + [payload appendString:@"AFNetworking"]; + } + + NSURL *url = [NSURL URLWithString:[[self.baseURL absoluteString] stringByAppendingString:@"/post"]]; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0]; + [request setHTTPMethod:@"POST"]; + + NSURLSessionTask *task; + task = [self.localManager + uploadTaskWithRequest:request + fromData:[payload dataUsingEncoding:NSUTF8StringEncoding] + progress:nil + completionHandler:nil]; + + NSProgress *uploadProgress = [self.localManager uploadProgressForTask:task]; + [self keyValueObservingExpectationForObject:uploadProgress keyPath:NSStringFromSelector(@selector(fractionCompleted)) expectedValue:@(1.0)]; + + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +#pragma mark - rdar://17029580 + +- (void)testRDAR17029580IsFixed { + //https://github.com/AFNetworking/AFNetworking/issues/2093 + //https://github.com/AFNetworking/AFNetworking/pull/3205 + //http://openradar.appspot.com/radar?id=5871104061079552 + dispatch_queue_t serial_queue = dispatch_queue_create("com.alamofire.networking.test.RDAR17029580", DISPATCH_QUEUE_SERIAL); + NSMutableArray *taskIDs = [[NSMutableArray alloc] init]; + for (NSInteger i = 0; i < 100; i++) { + XCTestExpectation *expectation = [self expectationWithDescription:@"Wait for task creation"]; + __block NSURLSessionTask *task; + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + task = [self.localManager + dataTaskWithRequest:[NSURLRequest requestWithURL:self.baseURL] + completionHandler:nil]; + dispatch_sync(serial_queue, ^{ + XCTAssertFalse([taskIDs containsObject:@(task.taskIdentifier)]); + [taskIDs addObject:@(task.taskIdentifier)]; + }); + [task cancel]; + [expectation fulfill]; + }); + } + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +#pragma mark - Issue #2702 Tests +// The following tests are all releated to issue #2702 + +- (void)testDidResumeNotificationIsReceivedByLocalDataTaskAfterResume { + NSURLSessionDataTask *task = [self.localManager dataTaskWithRequest:[self _delayURLRequest] + completionHandler:nil]; + [self _testResumeNotificationForTask:task]; +} + +- (void)testDidSuspendNotificationIsReceivedByLocalDataTaskAfterSuspend { + NSURLSessionDataTask *task = [self.localManager dataTaskWithRequest:[self _delayURLRequest] + completionHandler:nil]; + [self _testSuspendNotificationForTask:task]; +} + +- (void)testDidResumeNotificationIsReceivedByBackgroundDataTaskAfterResume { + if (self.backgroundManager) { + NSURLSessionDataTask *task = [self.backgroundManager dataTaskWithRequest:[self _delayURLRequest] + completionHandler:nil]; + [self _testResumeNotificationForTask:task]; + } +} + +- (void)testDidSuspendNotificationIsReceivedByBackgroundDataTaskAfterSuspend { + if (self.backgroundManager) { + NSURLSessionDataTask *task = [self.backgroundManager dataTaskWithRequest:[self _delayURLRequest] + completionHandler:nil]; + [self _testSuspendNotificationForTask:task]; + } +} + +- (void)testDidResumeNotificationIsReceivedByLocalUploadTaskAfterResume { + NSURLSessionUploadTask *task = [self.localManager uploadTaskWithRequest:[self _delayURLRequest] + fromData:[NSData data] + progress:nil + completionHandler:nil]; + [self _testResumeNotificationForTask:task]; +} + +- (void)testDidSuspendNotificationIsReceivedByLocalUploadTaskAfterSuspend { + NSURLSessionUploadTask *task = [self.localManager uploadTaskWithRequest:[self _delayURLRequest] + fromData:[NSData data] + progress:nil + completionHandler:nil]; + [self _testSuspendNotificationForTask:task]; +} + +- (void)testDidResumeNotificationIsReceivedByBackgroundUploadTaskAfterResume { + if (self.backgroundManager) { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnonnull" + NSURLSessionUploadTask *task = [self.backgroundManager uploadTaskWithRequest:[self _delayURLRequest] + fromFile:nil + progress:nil + completionHandler:nil]; +#pragma clang diagnostic pop + [self _testResumeNotificationForTask:task]; + } +} + +- (void)testDidSuspendNotificationIsReceivedByBackgroundUploadTaskAfterSuspend { + if (self.backgroundManager) { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnonnull" + NSURLSessionUploadTask *task = [self.backgroundManager uploadTaskWithRequest:[self _delayURLRequest] + fromFile:nil + progress:nil + completionHandler:nil]; +#pragma clang diagnostic pop + [self _testSuspendNotificationForTask:task]; + } +} + +- (void)testDidResumeNotificationIsReceivedByLocalDownloadTaskAfterResume { + NSURLSessionDownloadTask *task = [self.localManager downloadTaskWithRequest:[self _delayURLRequest] + progress:nil + destination:nil + completionHandler:nil]; + [self _testResumeNotificationForTask:task]; +} + +- (void)testDidSuspendNotificationIsReceivedByLocalDownloadTaskAfterSuspend { + NSURLSessionDownloadTask *task = [self.localManager downloadTaskWithRequest:[self _delayURLRequest] + progress:nil + destination:nil + completionHandler:nil]; + [self _testSuspendNotificationForTask:task]; +} + +- (void)testDidResumeNotificationIsReceivedByBackgroundDownloadTaskAfterResume { + if (self.backgroundManager) { + NSURLSessionDownloadTask *task = [self.backgroundManager downloadTaskWithRequest:[self _delayURLRequest] + progress:nil + destination:nil + completionHandler:nil]; + [self _testResumeNotificationForTask:task]; + } +} + +- (void)testDidSuspendNotificationIsReceivedByBackgroundDownloadTaskAfterSuspend { + if (self.backgroundManager) { + NSURLSessionDownloadTask *task = [self.backgroundManager downloadTaskWithRequest:[self _delayURLRequest] + progress:nil + destination:nil + completionHandler:nil]; + [self _testSuspendNotificationForTask:task]; + } +} + +- (void)testSwizzlingIsProperlyConfiguredForDummyClass { + IMP originalAFResumeIMP = [self _originalAFResumeImplementation]; + IMP originalAFSuspendIMP = [self _originalAFSuspendImplementation]; + XCTAssert(originalAFResumeIMP, @"Swizzled af_resume Method Not Found"); + XCTAssert(originalAFSuspendIMP, @"Swizzled af_suspend Method Not Found"); + XCTAssertNotEqual(originalAFResumeIMP, originalAFSuspendIMP, @"af_resume and af_suspend should not be equal"); +} + +- (void)testSwizzlingIsWorkingAsExpectedForForegroundDataTask { + NSURLSessionTask *task = [self.localManager dataTaskWithRequest:[self _delayURLRequest] + completionHandler:nil]; + [self _testSwizzlingForTask:task]; + [task cancel]; +} + +- (void)testSwizzlingIsWorkingAsExpectedForForegroundUpload { + NSURLSessionTask *task = [self.localManager uploadTaskWithRequest:[self _delayURLRequest] + fromData:[NSData data] + progress:nil + completionHandler:nil]; + [self _testSwizzlingForTask:task]; + [task cancel]; +} + +- (void)testSwizzlingIsWorkingAsExpectedForForegroundDownload { + NSURLSessionTask *task = [self.localManager downloadTaskWithRequest:[self _delayURLRequest] + progress:nil + destination:nil + completionHandler:nil]; + [self _testSwizzlingForTask:task]; + [task cancel]; +} + +- (void)testSwizzlingIsWorkingAsExpectedForBackgroundDataTask { + //iOS 7 doesn't let us use a background manager in these tests, so reference these + //classes directly. There are tests below to confirm background manager continues + //to return the exepcted classes going forward. If those fail in a future iOS version, + //it should point us to a problem here. + [self _testSwizzlingForTaskClass:NSClassFromString(@"__NSCFBackgroundDataTask")]; +} + +- (void)testSwizzlingIsWorkingAsExpectedForBackgroundUploadTask { + //iOS 7 doesn't let us use a background manager in these tests, so reference these + //classes directly. There are tests below to confirm background manager continues + //to return the exepcted classes going forward. If those fail in a future iOS version, + //it should point us to a problem here. + [self _testSwizzlingForTaskClass:NSClassFromString(@"__NSCFBackgroundUploadTask")]; +} + +- (void)testSwizzlingIsWorkingAsExpectedForBackgroundDownloadTask { + //iOS 7 doesn't let us use a background manager in these tests, so reference these + //classes directly. There are tests below to confirm background manager continues + //to return the exepcted classes going forward. If those fail in a future iOS version, + //it should point us to a problem here. + [self _testSwizzlingForTaskClass:NSClassFromString(@"__NSCFBackgroundDownloadTask")]; +} + +- (void)testBackgroundManagerReturnsExpectedClassForDataTask { + if (self.backgroundManager) { + NSURLSessionTask *task = [self.backgroundManager dataTaskWithRequest:[self _delayURLRequest] + completionHandler:nil]; + XCTAssert([NSStringFromClass([task class]) isEqualToString:@"__NSCFBackgroundDataTask"]); + } else { + NSLog(@"Unable to run %@ because self.backgroundManager is nil", NSStringFromSelector(_cmd)); + } +} + +- (void)testBackgroundManagerReturnsExpectedClassForUploadTask { + if (self.backgroundManager) { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnonnull" + NSURLSessionTask *task = [self.backgroundManager uploadTaskWithRequest:[self _delayURLRequest] + fromFile:nil + progress:nil + completionHandler:nil]; +#pragma clang diagnostic pop + XCTAssert([NSStringFromClass([task class]) isEqualToString:@"__NSCFBackgroundUploadTask"]); + } else { + NSLog(@"Unable to run %@ because self.backgroundManager is nil", NSStringFromSelector(_cmd)); + } +} + +- (void)testBackgroundManagerReturnsExpectedClassForDownloadTask { + if (self.backgroundManager) { + NSURLSessionTask *task = [self.backgroundManager downloadTaskWithRequest:[self _delayURLRequest] + progress:nil + destination:nil + completionHandler:nil]; + XCTAssert([NSStringFromClass([task class]) isEqualToString:@"__NSCFBackgroundDownloadTask"]); + } else { + NSLog(@"Unable to run %@ because self.backgroundManager is nil", NSStringFromSelector(_cmd)); + } +} + +#pragma mark - private + +- (void)_testResumeNotificationForTask:(NSURLSessionTask *)task { + [self expectationForNotification:AFNetworkingTaskDidResumeNotification + object:nil + handler:nil]; + [task resume]; + [task suspend]; + [task resume]; + [self waitForExpectationsWithTimeout:2.0 handler:nil]; + [task cancel]; +} + +- (void)_testSuspendNotificationForTask:(NSURLSessionTask *)task { + [self expectationForNotification:AFNetworkingTaskDidSuspendNotification + object:nil + handler:nil]; + [task resume]; + [task suspend]; + [task resume]; + [self waitForExpectationsWithTimeout:2.0 handler:nil]; + [task cancel]; +} + +- (NSURLRequest *)_delayURLRequest { + return [NSURLRequest requestWithURL:[self.baseURL URLByAppendingPathComponent:@"delay/1"]]; +} + +- (IMP)_implementationForTask:(NSURLSessionTask *)task selector:(SEL)selector { + return [self _implementationForClass:[task class] selector:selector]; +} + +- (IMP)_implementationForClass:(Class)class selector:(SEL)selector { + return method_getImplementation(class_getInstanceMethod(class, selector)); +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wundeclared-selector" +- (IMP)_originalAFResumeImplementation { + return method_getImplementation(class_getInstanceMethod(NSClassFromString(@"_AFURLSessionTaskSwizzling"), @selector(af_resume))); +} + +- (IMP)_originalAFSuspendImplementation { + return method_getImplementation(class_getInstanceMethod(NSClassFromString(@"_AFURLSessionTaskSwizzling"), @selector(af_suspend))); +} + +- (void)_testSwizzlingForTask:(NSURLSessionTask *)task { + [self _testSwizzlingForTaskClass:[task class]]; +} + +- (void)_testSwizzlingForTaskClass:(Class)class { + IMP originalAFResumeIMP = [self _originalAFResumeImplementation]; + IMP originalAFSuspendIMP = [self _originalAFSuspendImplementation]; + + IMP taskResumeImp = [self _implementationForClass:class selector:@selector(resume)]; + IMP taskSuspendImp = [self _implementationForClass:class selector:@selector(suspend)]; + XCTAssertEqual(originalAFResumeIMP, taskResumeImp, @"resume has not been properly swizzled for %@", NSStringFromClass(class)); + XCTAssertEqual(originalAFSuspendIMP, taskSuspendImp, @"suspend has not been properly swizzled for %@", NSStringFromClass(class)); + + IMP taskAFResumeImp = [self _implementationForClass:class selector:@selector(af_resume)]; + IMP taskAFSuspendImp = [self _implementationForClass:class selector:@selector(af_suspend)]; + XCTAssert(taskAFResumeImp != NULL, @"af_resume is nil. Something has not been been swizzled right for %@", NSStringFromClass(class)); + XCTAssertNotEqual(taskAFResumeImp, taskResumeImp, @"af_resume has not been properly swizzled for %@", NSStringFromClass(class)); + XCTAssert(taskAFSuspendImp != NULL, @"af_suspend is nil. Something has not been been swizzled right for %@", NSStringFromClass(class)); + XCTAssertNotEqual(taskAFSuspendImp, taskSuspendImp, @"af_suspend has not been properly swizzled for %@", NSStringFromClass(class)); +} +#pragma clang diagnostic pop + +@end diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h new file mode 100644 index 00000000..16139dad --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h @@ -0,0 +1,149 @@ +// AFAutoPurgingImageCache.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import +#import + +#if TARGET_OS_IOS || TARGET_OS_TV +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + The `AFImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache synchronously. + */ +@protocol AFImageCache + +/** + Adds the image to the cache with the given identifier. + + @param image The image to cache. + @param identifier The unique identifier for the image in the cache. + */ +- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier; + +/** + Removes the image from the cache matching the given identifier. + + @param identifier The unique identifier for the image in the cache. + + @return A BOOL indicating whether or not the image was removed from the cache. + */ +- (BOOL)removeImageWithIdentifier:(NSString *)identifier; + +/** + Removes all images from the cache. + + @return A BOOL indicating whether or not all images were removed from the cache. + */ +- (BOOL)removeAllImages; + +/** + Returns the image in the cache associated with the given identifier. + + @param identifier The unique identifier for the image in the cache. + + @return An image for the matching identifier, or nil. + */ +- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier; +@end + + +/** + The `ImageRequestCache` protocol extends the `ImageCache` protocol by adding methods for adding, removing and fetching images from a cache given an `NSURLRequest` and additional identifier. + */ +@protocol AFImageRequestCache + +/** + Adds the image to the cache using an identifier created from the request and additional identifier. + + @param image The image to cache. + @param request The unique URL request identifing the image asset. + @param identifier The additional identifier to apply to the URL request to identify the image. + */ +- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; + +/** + Removes the image from the cache using an identifier created from the request and additional identifier. + + @param request The unique URL request identifing the image asset. + @param identifier The additional identifier to apply to the URL request to identify the image. + + @return A BOOL indicating whether or not all images were removed from the cache. + */ +- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; + +/** + Returns the image from the cache associated with an identifier created from the request and additional identifier. + + @param request The unique URL request identifing the image asset. + @param identifier The additional identifier to apply to the URL request to identify the image. + + @return An image for the matching request and identifier, or nil. + */ +- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; + +@end + +/** + The `AutoPurgingImageCache` in an in-memory image cache used to store images up to a given memory capacity. When the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the internal access date of the image is updated. + */ +@interface AFAutoPurgingImageCache : NSObject + +/** + The total memory capacity of the cache in bytes. + */ +@property (nonatomic, assign) UInt64 memoryCapacity; + +/** + The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory capacity drops below this limit. + */ +@property (nonatomic, assign) UInt64 preferredMemoryUsageAfterPurge; + +/** + The current total memory usage in bytes of all images stored within the cache. + */ +@property (nonatomic, assign, readonly) UInt64 memoryUsage; + +/** + Initialies the `AutoPurgingImageCache` instance with default values for memory capacity and preferred memory usage after purge limit. `memoryCapcity` defaults to `100 MB`. `preferredMemoryUsageAfterPurge` defaults to `60 MB`. + + @return The new `AutoPurgingImageCache` instance. + */ +- (instancetype)init; + +/** + Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage + after purge limit. + + @param memoryCapacity The total memory capacity of the cache in bytes. + @param preferredMemoryUsageAfterPurge The preferred memory usage after purge in bytes. + + @return The new `AutoPurgingImageCache` instance. + */ +- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity; + +@end + +NS_ASSUME_NONNULL_END + +#endif + diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m new file mode 100644 index 00000000..99ad3d65 --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m @@ -0,0 +1,201 @@ +// AFAutoPurgingImageCache.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFAutoPurgingImageCache.h" + +@interface AFCachedImage : NSObject + +@property (nonatomic, strong) UIImage *image; +@property (nonatomic, strong) NSString *identifier; +@property (nonatomic, assign) UInt64 totalBytes; +@property (nonatomic, strong) NSDate *lastAccessDate; +@property (nonatomic, assign) UInt64 currentMemoryUsage; + +@end + +@implementation AFCachedImage + +-(instancetype)initWithImage:(UIImage *)image identifier:(NSString *)identifier { + if (self = [self init]) { + self.image = image; + self.identifier = identifier; + + CGSize imageSize = CGSizeMake(image.size.width * image.scale, image.size.height * image.scale); + CGFloat bytesPerPixel = 4.0; + CGFloat bytesPerRow = imageSize.width * bytesPerPixel; + self.totalBytes = (UInt64)bytesPerPixel * (UInt64)bytesPerRow; + self.lastAccessDate = [NSDate date]; + } + return self; +} + +- (UIImage*)accessImage { + self.lastAccessDate = [NSDate date]; + return self.image; +} + +- (NSString *)description { + NSString *descriptionString = [NSString stringWithFormat:@"Idenfitier: %@ lastAccessDate: %@ ", self.identifier, self.lastAccessDate]; + return descriptionString; + +} + +@end + +@interface AFAutoPurgingImageCache () +@property (nonatomic, strong) NSMutableDictionary *cachedImages; +@property (nonatomic, assign) UInt64 currentMemoryUsage; +@property (nonatomic, strong) dispatch_queue_t synchronizationQueue; +@end + +@implementation AFAutoPurgingImageCache + +- (instancetype)init { + return [self initWithMemoryCapacity:100 * 1024 * 1024 preferredMemoryCapacity:60 * 1024 * 1024]; +} + +- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity { + if (self = [super init]) { + self.memoryCapacity = memoryCapacity; + self.preferredMemoryUsageAfterPurge = preferredMemoryCapacity; + self.cachedImages = [[NSMutableDictionary alloc] init]; + + NSString *queueName = [NSString stringWithFormat:@"com.alamofire.autopurgingimagecache-%@", [[NSUUID UUID] UUIDString]]; + self.synchronizationQueue = dispatch_queue_create([queueName cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT); + + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(removeAllImages) + name:UIApplicationDidReceiveMemoryWarningNotification + object:nil]; + + } + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +- (UInt64)memoryUsage { + __block UInt64 result = 0; + dispatch_sync(self.synchronizationQueue, ^{ + result = self.currentMemoryUsage; + }); + return result; +} + +- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier { + dispatch_barrier_async(self.synchronizationQueue, ^{ + AFCachedImage *cacheImage = [[AFCachedImage alloc] initWithImage:image identifier:identifier]; + + AFCachedImage *previousCachedImage = self.cachedImages[identifier]; + if (previousCachedImage != nil) { + self.currentMemoryUsage -= previousCachedImage.totalBytes; + } + + self.cachedImages[identifier] = cacheImage; + self.currentMemoryUsage += cacheImage.totalBytes; + }); + + dispatch_barrier_async(self.synchronizationQueue, ^{ + if (self.currentMemoryUsage > self.memoryCapacity) { + UInt64 bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge; + NSMutableArray *sortedImages = [NSMutableArray arrayWithArray:self.cachedImages.allValues]; + NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastAccessDate" + ascending:YES]; + [sortedImages sortUsingDescriptors:@[sortDescriptor]]; + + UInt64 bytesPurged = 0; + + for (AFCachedImage *cachedImage in sortedImages) { + [self.cachedImages removeObjectForKey:cachedImage.identifier]; + bytesPurged += cachedImage.totalBytes; + if (bytesPurged >= bytesToPurge) { + break ; + } + } + self.currentMemoryUsage -= bytesPurged; + } + }); +} + +- (BOOL)removeImageWithIdentifier:(NSString *)identifier { + __block BOOL removed = NO; + dispatch_barrier_sync(self.synchronizationQueue, ^{ + AFCachedImage *cachedImage = self.cachedImages[identifier]; + if (cachedImage != nil) { + [self.cachedImages removeObjectForKey:identifier]; + self.currentMemoryUsage -= cachedImage.totalBytes; + removed = YES; + } + }); + return removed; +} + +- (BOOL)removeAllImages { + __block BOOL removed = NO; + dispatch_barrier_sync(self.synchronizationQueue, ^{ + if (self.cachedImages.count > 0) { + [self.cachedImages removeAllObjects]; + self.currentMemoryUsage = 0; + removed = YES; + } + }); + return removed; +} + +- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier { + __block UIImage *image = nil; + dispatch_sync(self.synchronizationQueue, ^{ + AFCachedImage *cachedImage = self.cachedImages[identifier]; + image = [cachedImage accessImage]; + }); + return image; +} + +- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier { + [self addImage:image withIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]]; +} + +- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier { + return [self removeImageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]]; +} + +- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier { + return [self imageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]]; +} + +- (NSString *)imageCacheKeyFromURLRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)additionalIdentifier { + NSString *key = request.URL.absoluteString; + if (additionalIdentifier != nil) { + key = [key stringByAppendingString:additionalIdentifier]; + } + return key; +} + +@end + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h new file mode 100644 index 00000000..a368ad8f --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h @@ -0,0 +1,157 @@ +// AFImageDownloader.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import +#import "AFAutoPurgingImageCache.h" +#import "AFHTTPSessionManager.h" + +NS_ASSUME_NONNULL_BEGIN + +typedef NS_ENUM(NSInteger, AFImageDownloadPrioritization) { + AFImageDownloadPrioritizationFIFO, + AFImageDownloadPrioritizationLIFO +}; + +/** + The `AFImageDownloadReceipt` is an object vended by the `AFImageDownloader` when starting a data task. It can be used to cancel active tasks running on the `AFImageDownloader` session. As a general rule, image data tasks should be cancelled using the `AFImageDownloadReceipt` instead of calling `cancel` directly on the `task` itself. The `AFImageDownloader` is optimized to handle duplicate task scenarios as well as pending versus active downloads. + */ +@interface AFImageDownloadReceipt : NSObject + +/** + The data task created by the `AFImageDownloader`. +*/ +@property (nonatomic, strong) NSURLSessionDataTask *task; + +/** + The unique identifier for the success and failure blocks when duplicate requests are made. + */ +@property (nonatomic, strong) NSUUID *receiptID; +@end + +/** The `AFImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded image is cached in the underlying `NSURLCache` as well as the in-memory image cache. By default, any download request with a cached image equivalent in the image cache will automatically be served the cached image representation. + */ +@interface AFImageDownloader : NSObject + +/** + The image cache used to store all downloaded images in. `AFAutoPurgingImageCache` by default. + */ +@property (nonatomic, strong, nullable) id imageCache; + +/** + The `AFHTTPSessionManager` used to download images. By default, this is configured with an `AFImageResponseSerializer`, and a shared `NSURLCache` for all image downloads. + */ +@property (nonatomic, strong) AFHTTPSessionManager *sessionManager; + +/** + Defines the order prioritization of incoming download requests being inserted into the queue. `AFImageDownloadPrioritizationFIFO` by default. + */ +@property (nonatomic, assign) AFImageDownloadPrioritization downloadPrioritizaton; + +/** + The shared default instance of `AFImageDownloader` initialized with default values. + */ ++ (instancetype)defaultInstance; + +/** + Creates a default `NSURLCache` with common usage parameter values. + + @returns The default `NSURLCache` instance. + */ ++ (NSURLCache *)defaultURLCache; + +/** + Default initializer + + @return An instance of `AFImageDownloader` initialized with default values. + */ +- (instancetype)init; + +/** + Initializes the `AFImageDownloader` instance with the given session manager, download prioritization, maximum active download count and image cache. + + @param sessionManager The session manager to use to download images. + @param downloadPrioritization The download prioritization of the download queue. + @param maximumActiveDownloads The maximum number of active downloads allowed at any given time. Recommend `4`. + @param imageCache The image cache used to store all downloaded images in. + + @return The new `AFImageDownloader` instance. + */ +- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager + downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization + maximumActiveDownloads:(NSInteger)maximumActiveDownloads + imageCache:(nullable id )imageCache; + +/** + Creates a data task using the `sessionManager` instance for the specified URL request. + + If the same data task is already in the queue or currently being downloaded, the success and failure blocks are + appended to the already existing task. Once the task completes, all success or failure blocks attached to the + task are executed in the order they were added. + + @param request The URL request. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + + @return The image download receipt for the data task if available. `nil` if the image is stored in the cache. + cache and the URL request cache policy allows the cache to be used. + */ +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + +/** + Creates a data task using the `sessionManager` instance for the specified URL request. + + If the same data task is already in the queue or currently being downloaded, the success and failure blocks are + appended to the already existing task. Once the task completes, all success or failure blocks attached to the + task are executed in the order they were added. + + @param request The URL request. + @param request The identifier to use for the download receipt that will be created for this request. This must be a unique identifier that does not represent any other request. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + + @return The image download receipt for the data task if available. `nil` if the image is stored in the cache. + cache and the URL request cache policy allows the cache to be used. + */ +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request + withReceiptID:(NSUUID *)receiptID + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + +/** + Cancels the data task in the receipt by removing the corresponding success and failure blocks and cancelling the data task if necessary. + + If the data task is pending in the queue, it will be cancelled if no other success and failure blocks are registered with the data task. If the data task is currently executing or is already completed, the success and failure blocks are removed and will not be called when the task finishes. + + @param imageDownloadReceipt The image download receipt to cancel. + */ +- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt; + +@end + +#endif + +NS_ASSUME_NONNULL_END diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m new file mode 100644 index 00000000..f7aa3d31 --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m @@ -0,0 +1,382 @@ +// AFImageDownloader.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFImageDownloader.h" +#import "AFHTTPSessionManager.h" + +@interface AFImageDownloaderResponseHandler : NSObject +@property (nonatomic, strong) NSUUID *uuid; +@property (nonatomic, copy) void (^successBlock)(NSURLRequest*, NSHTTPURLResponse*, UIImage*); +@property (nonatomic, copy) void (^failureBlock)(NSURLRequest*, NSHTTPURLResponse*, NSError*); +@end + +@implementation AFImageDownloaderResponseHandler + +- (instancetype)initWithUUID:(NSUUID *)uuid + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure { + if (self = [self init]) { + self.uuid = uuid; + self.successBlock = success; + self.failureBlock = failure; + } + return self; +} + +- (NSString *)description { + return [NSString stringWithFormat: @"UUID: %@", [self.uuid UUIDString]]; +} + +@end + +@interface AFImageDownloaderMergedTask : NSObject +@property (nonatomic, strong) NSString *URLIdentifier; +@property (nonatomic, strong) NSUUID *identifier; +@property (nonatomic, strong) NSURLSessionDataTask *task; +@property (nonatomic, strong) NSMutableArray *responseHandlers; + +@end + +@implementation AFImageDownloaderMergedTask + +- (instancetype)initWithURLIdentifier:(NSString *)URLIdentifier identifier:(NSUUID *)identifier task:(NSURLSessionDataTask *)task { + if (self = [self init]) { + self.URLIdentifier = URLIdentifier; + self.task = task; + self.identifier = identifier; + self.responseHandlers = [[NSMutableArray alloc] init]; + } + return self; +} + +- (void)addResponseHandler:(AFImageDownloaderResponseHandler*)handler { + [self.responseHandlers addObject:handler]; +} + +- (void)removeResponseHandler:(AFImageDownloaderResponseHandler*)handler { + [self.responseHandlers removeObject:handler]; +} + +@end + +@implementation AFImageDownloadReceipt + +- (instancetype)initWithReceiptID:(NSUUID *)receiptID task:(NSURLSessionDataTask *)task { + if (self = [self init]) { + self.receiptID = receiptID; + self.task = task; + } + return self; +} + +@end + +@interface AFImageDownloader () + +@property (nonatomic, strong) dispatch_queue_t synchronizationQueue; +@property (nonatomic, strong) dispatch_queue_t responseQueue; + +@property (nonatomic, assign) NSInteger maximumActiveDownloads; +@property (nonatomic, assign) NSInteger activeRequestCount; + +@property (nonatomic, strong) NSMutableArray *queuedMergedTasks; +@property (nonatomic, strong) NSMutableDictionary *mergedTasks; + +@end + + +@implementation AFImageDownloader + ++ (NSURLCache *)defaultURLCache { + return [[NSURLCache alloc] initWithMemoryCapacity:20 * 1024 * 1024 + diskCapacity:150 * 1024 * 1024 + diskPath:@"com.alamofire.imagedownloader"]; +} + ++ (NSURLSessionConfiguration *)defaultURLSessionConfiguration { + NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; + + //TODO set the default HTTP headers + + configuration.HTTPShouldSetCookies = YES; + configuration.HTTPShouldUsePipelining = NO; + + configuration.requestCachePolicy = NSURLRequestUseProtocolCachePolicy; + configuration.allowsCellularAccess = YES; + configuration.timeoutIntervalForRequest = 60.0; + configuration.URLCache = [AFImageDownloader defaultURLCache]; + + return configuration; +} + +- (instancetype)init { + NSURLSessionConfiguration *defaultConfiguration = [self.class defaultURLSessionConfiguration]; + AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:defaultConfiguration]; + sessionManager.responseSerializer = [AFImageResponseSerializer serializer]; + + return [self initWithSessionManager:sessionManager + downloadPrioritization:AFImageDownloadPrioritizationFIFO + maximumActiveDownloads:4 + imageCache:[[AFAutoPurgingImageCache alloc] init]]; +} + +- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager + downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization + maximumActiveDownloads:(NSInteger)maximumActiveDownloads + imageCache:(id )imageCache { + if (self = [super init]) { + self.sessionManager = sessionManager; + + self.downloadPrioritizaton = downloadPrioritization; + self.maximumActiveDownloads = maximumActiveDownloads; + self.imageCache = imageCache; + + self.queuedMergedTasks = [[NSMutableArray alloc] init]; + self.mergedTasks = [[NSMutableDictionary alloc] init]; + self.activeRequestCount = 0; + + NSString *name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.synchronizationqueue-%@", [[NSUUID UUID] UUIDString]]; + self.synchronizationQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_SERIAL); + + name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.responsequeue-%@", [[NSUUID UUID] UUIDString]]; + self.responseQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT); + } + + return self; +} + ++ (instancetype)defaultInstance { + static AFImageDownloader *sharedInstance = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sharedInstance = [[self alloc] init]; + }); + return sharedInstance; +} + +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request + success:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, UIImage * _Nonnull))success + failure:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, NSError * _Nonnull))failure { + return [self downloadImageForURLRequest:request withReceiptID:[NSUUID UUID] success:success failure:failure]; +} + +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request + withReceiptID:(nonnull NSUUID *)receiptID + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure { + __block NSURLSessionDataTask *task = nil; + dispatch_sync(self.synchronizationQueue, ^{ + NSString *URLIdentifier = request.URL.absoluteString; + + // 1) Append the success and failure blocks to a pre-existing request if it already exists + AFImageDownloaderMergedTask *existingMergedTask = self.mergedTasks[URLIdentifier]; + if (existingMergedTask != nil) { + AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID success:success failure:failure]; + [existingMergedTask addResponseHandler:handler]; + task = existingMergedTask.task; + return; + } + + // 2) Attempt to load the image from the image cache if the cache policy allows it + switch (request.cachePolicy) { + case NSURLRequestUseProtocolCachePolicy: + case NSURLRequestReturnCacheDataElseLoad: + case NSURLRequestReturnCacheDataDontLoad: { + UIImage *cachedImage = [self.imageCache imageforRequest:request withAdditionalIdentifier:nil]; + if (cachedImage != nil) { + if (success) { + dispatch_async(dispatch_get_main_queue(), ^{ + success(request, nil, cachedImage); + }); + } + return; + } + break; + } + default: + break; + } + + // 3) Create the request and set up authentication, validation and response serialization + NSUUID *mergedTaskIdentifier = [NSUUID UUID]; + NSURLSessionDataTask *createdTask; + __weak __typeof__(self) weakSelf = self; + + createdTask = [self.sessionManager + dataTaskWithRequest:request + completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + dispatch_async(self.responseQueue, ^{ + __strong __typeof__(weakSelf) strongSelf = weakSelf; + AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier]; + if ([mergedTask.identifier isEqual:mergedTaskIdentifier]) { + mergedTask = [strongSelf safelyRemoveMergedTaskWithURLIdentifier:URLIdentifier]; + if (error) { + for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) { + if (handler.failureBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler.failureBlock(request, (NSHTTPURLResponse*)response, error); + }); + } + } + } else { + [strongSelf.imageCache addImage:responseObject forRequest:request withAdditionalIdentifier:nil]; + + for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) { + if (handler.successBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler.successBlock(request, (NSHTTPURLResponse*)response, responseObject); + }); + } + } + + } + } + [strongSelf safelyDecrementActiveTaskCount]; + [strongSelf safelyStartNextTaskIfNecessary]; + }); + }]; + + // 4) Store the response handler for use when the request completes + AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID + success:success + failure:failure]; + AFImageDownloaderMergedTask *mergedTask = [[AFImageDownloaderMergedTask alloc] + initWithURLIdentifier:URLIdentifier + identifier:mergedTaskIdentifier + task:createdTask]; + [mergedTask addResponseHandler:handler]; + self.mergedTasks[URLIdentifier] = mergedTask; + + // 5) Either start the request or enqueue it depending on the current active request count + if ([self isActiveRequestCountBelowMaximumLimit]) { + [self startMergedTask:mergedTask]; + } else { + [self enqueueMergedTask:mergedTask]; + } + + task = mergedTask.task; + }); + if (task) { + return [[AFImageDownloadReceipt alloc] initWithReceiptID:receiptID task:task]; + } else { + return nil; + } +} + +- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt { + dispatch_sync(self.synchronizationQueue, ^{ + NSString *URLIdentifier = imageDownloadReceipt.task.originalRequest.URL.absoluteString; + AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier]; + NSUInteger index = [mergedTask.responseHandlers indexOfObjectPassingTest:^BOOL(AFImageDownloaderResponseHandler * _Nonnull handler, __unused NSUInteger idx, __unused BOOL * _Nonnull stop) { + return handler.uuid == imageDownloadReceipt.receiptID; + }]; + + if (index != NSNotFound) { + AFImageDownloaderResponseHandler *handler = mergedTask.responseHandlers[index]; + [mergedTask removeResponseHandler:handler]; + NSString *failureReason = [NSString stringWithFormat:@"ImageDownloader cancelled URL request: %@",imageDownloadReceipt.task.originalRequest.URL.absoluteString]; + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey:failureReason}; + NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo]; + if (handler.failureBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler.failureBlock(imageDownloadReceipt.task.originalRequest, nil, error); + }); + } + } + + if (mergedTask.responseHandlers.count == 0 && mergedTask.task.state == NSURLSessionTaskStateSuspended) { + [mergedTask.task cancel]; + [self removeMergedTaskWithURLIdentifier:URLIdentifier]; + } + }); +} + +- (AFImageDownloaderMergedTask*)safelyRemoveMergedTaskWithURLIdentifier:(NSString *)URLIdentifier { + __block AFImageDownloaderMergedTask *mergedTask = nil; + dispatch_sync(self.synchronizationQueue, ^{ + mergedTask = [self removeMergedTaskWithURLIdentifier:URLIdentifier]; + }); + return mergedTask; +} + +//This method should only be called from safely within the synchronizationQueue +- (AFImageDownloaderMergedTask *)removeMergedTaskWithURLIdentifier:(NSString *)URLIdentifier { + AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier]; + [self.mergedTasks removeObjectForKey:URLIdentifier]; + return mergedTask; +} + +- (void)safelyDecrementActiveTaskCount { + dispatch_sync(self.synchronizationQueue, ^{ + if (self.activeRequestCount > 0) { + self.activeRequestCount -= 1; + } + }); +} + +- (void)safelyStartNextTaskIfNecessary { + dispatch_sync(self.synchronizationQueue, ^{ + if ([self isActiveRequestCountBelowMaximumLimit]) { + while (self.queuedMergedTasks.count > 0) { + AFImageDownloaderMergedTask *mergedTask = [self dequeueMergedTask]; + if (mergedTask.task.state == NSURLSessionTaskStateSuspended) { + [self startMergedTask:mergedTask]; + break; + } + } + } + }); +} + +- (void)startMergedTask:(AFImageDownloaderMergedTask *)mergedTask { + [mergedTask.task resume]; + ++self.activeRequestCount; +} + +- (void)enqueueMergedTask:(AFImageDownloaderMergedTask *)mergedTask { + switch (self.downloadPrioritizaton) { + case AFImageDownloadPrioritizationFIFO: + [self.queuedMergedTasks addObject:mergedTask]; + break; + case AFImageDownloadPrioritizationLIFO: + [self.queuedMergedTasks insertObject:mergedTask atIndex:0]; + break; + } +} + +- (AFImageDownloaderMergedTask *)dequeueMergedTask { + AFImageDownloaderMergedTask *mergedTask = nil; + mergedTask = [self.queuedMergedTasks firstObject]; + [self.queuedMergedTasks removeObject:mergedTask]; + return mergedTask; +} + +- (BOOL)isActiveRequestCountBelowMaximumLimit { + return self.activeRequestCount < self.maximumActiveDownloads; +} + +@end + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h new file mode 100644 index 00000000..8b05ad3b --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h @@ -0,0 +1,103 @@ +// AFNetworkActivityIndicatorManager.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import + +#import + +#if TARGET_OS_IOS + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + `AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a session task has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero. + + You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code: + + [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; + + By setting `enabled` to `YES` for `sharedManager`, the network activity indicator will show and hide automatically as requests start and finish. You should not ever need to call `incrementActivityCount` or `decrementActivityCount` yourself. + + See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information: + http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44 + */ +NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropriate instead.") +@interface AFNetworkActivityIndicatorManager : NSObject + +/** + A Boolean value indicating whether the manager is enabled. + + If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO. + */ +@property (nonatomic, assign, getter = isEnabled) BOOL enabled; + +/** + A Boolean value indicating whether the network activity indicator manager is currently active. +*/ +@property (readonly, nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; + +/** + A time interval indicating the minimum duration of networking activity that should occur before the activity indicator is displayed. The default value 1 second. If the network activity indicator should be displayed immediately when network activity occurs, this value should be set to 0 seconds. + + Apple's HIG describes the following: + + > Display the network activity indicator to provide feedback when your app accesses the network for more than a couple of seconds. If the operation finishes sooner than that, you don’t have to show the network activity indicator, because the indicator is likely to disappear before users notice its presence. + + */ +@property (nonatomic, assign) NSTimeInterval activationDelay; + +/** + A time interval indicating the duration of time of no networking activity required before the activity indicator is disabled. This allows for continuous display of the network activity indicator across multiple requests. The default value is 0.17 seconds. + */ + +@property (nonatomic, assign) NSTimeInterval completionDelay; + +/** + Returns the shared network activity indicator manager object for the system. + + @return The systemwide network activity indicator manager. + */ ++ (instancetype)sharedManager; + +/** + Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator. + */ +- (void)incrementActivityCount; + +/** + Decrements the number of active network requests. If this number becomes zero after decrementing, this will stop animating the status bar network activity indicator. + */ +- (void)decrementActivityCount; + +/** + Set the a custom method to be executed when the network activity indicator manager should be hidden/shown. By default, this is null, and the UIApplication Network Activity Indicator will be managed automatically. If this block is set, it is the responsiblity of the caller to manager the network activity indicator going forward. + + @param block A block to be executed when the network activity indicator status changes. + */ +- (void)setNetworkingActivityActionWithBlock:(nullable void (^)(BOOL networkActivityIndicatorVisible))block; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m new file mode 100644 index 00000000..440cf7db --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m @@ -0,0 +1,261 @@ +// AFNetworkActivityIndicatorManager.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "AFNetworkActivityIndicatorManager.h" + +#if TARGET_OS_IOS +#import "AFURLSessionManager.h" + +typedef NS_ENUM(NSInteger, AFNetworkActivityManagerState) { + AFNetworkActivityManagerStateNotActive, + AFNetworkActivityManagerStateDelayingStart, + AFNetworkActivityManagerStateActive, + AFNetworkActivityManagerStateDelayingEnd +}; + +static NSTimeInterval const kDefaultAFNetworkActivityManagerActivationDelay = 1.0; +static NSTimeInterval const kDefaultAFNetworkActivityManagerCompletionDelay = 0.17; + +static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) { + if ([[notification object] respondsToSelector:@selector(originalRequest)]) { + return [(NSURLSessionTask *)[notification object] originalRequest]; + } else { + return nil; + } +} + +typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisible); + +@interface AFNetworkActivityIndicatorManager () +@property (readwrite, nonatomic, assign) NSInteger activityCount; +@property (readwrite, nonatomic, strong) NSTimer *activationDelayTimer; +@property (readwrite, nonatomic, strong) NSTimer *completionDelayTimer; +@property (readonly, nonatomic, getter = isNetworkActivityOccurring) BOOL networkActivityOccurring; +@property (nonatomic, copy) AFNetworkActivityActionBlock networkActivityActionBlock; +@property (nonatomic, assign) AFNetworkActivityManagerState currentState; +@property (nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; + +- (void)updateCurrentStateForNetworkActivityChange; +@end + +@implementation AFNetworkActivityIndicatorManager + ++ (instancetype)sharedManager { + static AFNetworkActivityIndicatorManager *_sharedManager = nil; + static dispatch_once_t oncePredicate; + dispatch_once(&oncePredicate, ^{ + _sharedManager = [[self alloc] init]; + }); + + return _sharedManager; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + self.currentState = AFNetworkActivityManagerStateNotActive; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingTaskDidResumeNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidSuspendNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidCompleteNotification object:nil]; + self.activationDelay = kDefaultAFNetworkActivityManagerActivationDelay; + self.completionDelay = kDefaultAFNetworkActivityManagerCompletionDelay; + + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; + + [_activationDelayTimer invalidate]; + [_completionDelayTimer invalidate]; +} + +- (void)setEnabled:(BOOL)enabled { + _enabled = enabled; + if (enabled == NO) { + [self setCurrentState:AFNetworkActivityManagerStateNotActive]; + } +} + +- (void)setNetworkingActivityActionWithBlock:(void (^)(BOOL networkActivityIndicatorVisible))block { + self.networkActivityActionBlock = block; +} + +- (BOOL)isNetworkActivityOccurring { + @synchronized(self) { + return self.activityCount > 0; + } +} + +- (void)setNetworkActivityIndicatorVisible:(BOOL)networkActivityIndicatorVisible { + if (_networkActivityIndicatorVisible != networkActivityIndicatorVisible) { + [self willChangeValueForKey:@"networkActivityIndicatorVisible"]; + @synchronized(self) { + _networkActivityIndicatorVisible = networkActivityIndicatorVisible; + } + [self didChangeValueForKey:@"networkActivityIndicatorVisible"]; + if (self.networkActivityActionBlock) { + self.networkActivityActionBlock(networkActivityIndicatorVisible); + } else { + [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:networkActivityIndicatorVisible]; + } + } +} + +- (void)setActivityCount:(NSInteger)activityCount { + @synchronized(self) { + _activityCount = activityCount; + } + + dispatch_async(dispatch_get_main_queue(), ^{ + [self updateCurrentStateForNetworkActivityChange]; + }); +} + +- (void)incrementActivityCount { + [self willChangeValueForKey:@"activityCount"]; + @synchronized(self) { + _activityCount++; + } + [self didChangeValueForKey:@"activityCount"]; + + dispatch_async(dispatch_get_main_queue(), ^{ + [self updateCurrentStateForNetworkActivityChange]; + }); +} + +- (void)decrementActivityCount { + [self willChangeValueForKey:@"activityCount"]; + @synchronized(self) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + _activityCount = MAX(_activityCount - 1, 0); +#pragma clang diagnostic pop + } + [self didChangeValueForKey:@"activityCount"]; + + dispatch_async(dispatch_get_main_queue(), ^{ + [self updateCurrentStateForNetworkActivityChange]; + }); +} + +- (void)networkRequestDidStart:(NSNotification *)notification { + if ([AFNetworkRequestFromNotification(notification) URL]) { + [self incrementActivityCount]; + } +} + +- (void)networkRequestDidFinish:(NSNotification *)notification { + if ([AFNetworkRequestFromNotification(notification) URL]) { + [self decrementActivityCount]; + } +} + +#pragma mark - Internal State Management +- (void)setCurrentState:(AFNetworkActivityManagerState)currentState { + @synchronized(self) { + if (_currentState != currentState) { + [self willChangeValueForKey:@"currentState"]; + _currentState = currentState; + switch (currentState) { + case AFNetworkActivityManagerStateNotActive: + [self cancelActivationDelayTimer]; + [self cancelCompletionDelayTimer]; + [self setNetworkActivityIndicatorVisible:NO]; + break; + case AFNetworkActivityManagerStateDelayingStart: + [self startActivationDelayTimer]; + break; + case AFNetworkActivityManagerStateActive: + [self cancelCompletionDelayTimer]; + [self setNetworkActivityIndicatorVisible:YES]; + break; + case AFNetworkActivityManagerStateDelayingEnd: + [self startCompletionDelayTimer]; + break; + } + } + [self didChangeValueForKey:@"currentState"]; + } +} + +- (void)updateCurrentStateForNetworkActivityChange { + if (self.enabled) { + switch (self.currentState) { + case AFNetworkActivityManagerStateNotActive: + if (self.isNetworkActivityOccurring) { + [self setCurrentState:AFNetworkActivityManagerStateDelayingStart]; + } + break; + case AFNetworkActivityManagerStateDelayingStart: + //No op. Let the delay timer finish out. + break; + case AFNetworkActivityManagerStateActive: + if (!self.isNetworkActivityOccurring) { + [self setCurrentState:AFNetworkActivityManagerStateDelayingEnd]; + } + break; + case AFNetworkActivityManagerStateDelayingEnd: + if (self.isNetworkActivityOccurring) { + [self setCurrentState:AFNetworkActivityManagerStateActive]; + } + break; + } + } +} + +- (void)startActivationDelayTimer { + self.activationDelayTimer = [NSTimer + timerWithTimeInterval:self.activationDelay target:self selector:@selector(activationDelayTimerFired) userInfo:nil repeats:NO]; + [[NSRunLoop mainRunLoop] addTimer:self.activationDelayTimer forMode:NSRunLoopCommonModes]; +} + +- (void)activationDelayTimerFired { + if (self.networkActivityOccurring) { + [self setCurrentState:AFNetworkActivityManagerStateActive]; + } else { + [self setCurrentState:AFNetworkActivityManagerStateNotActive]; + } +} + +- (void)startCompletionDelayTimer { + [self.completionDelayTimer invalidate]; + self.completionDelayTimer = [NSTimer timerWithTimeInterval:self.completionDelay target:self selector:@selector(completionDelayTimerFired) userInfo:nil repeats:NO]; + [[NSRunLoop mainRunLoop] addTimer:self.completionDelayTimer forMode:NSRunLoopCommonModes]; +} + +- (void)completionDelayTimerFired { + [self setCurrentState:AFNetworkActivityManagerStateNotActive]; +} + +- (void)cancelActivationDelayTimer { + [self.activationDelayTimer invalidate]; +} + +- (void)cancelCompletionDelayTimer { + [self.completionDelayTimer invalidate]; +} + +@end + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h new file mode 100644 index 00000000..82973475 --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h @@ -0,0 +1,48 @@ +// UIActivityIndicatorView+AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import + +/** + This category adds methods to the UIKit framework's `UIActivityIndicatorView` class. The methods in this category provide support for automatically starting and stopping animation depending on the loading state of a session task. + */ +@interface UIActivityIndicatorView (AFNetworking) + +///---------------------------------- +/// @name Animating for Session Tasks +///---------------------------------- + +/** + Binds the animating state to the state of the specified task. + + @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. + */ +- (void)setAnimatingWithStateOfTask:(nullable NSURLSessionTask *)task; + +@end + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m new file mode 100644 index 00000000..24c8c76d --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m @@ -0,0 +1,124 @@ +// UIActivityIndicatorView+AFNetworking.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "UIActivityIndicatorView+AFNetworking.h" +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFURLSessionManager.h" + +@interface AFActivityIndicatorViewNotificationObserver : NSObject +@property (readonly, nonatomic, weak) UIActivityIndicatorView *activityIndicatorView; +- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView; + +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task; + +@end + +@implementation UIActivityIndicatorView (AFNetworking) + +- (AFActivityIndicatorViewNotificationObserver *)af_notificationObserver { + AFActivityIndicatorViewNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver)); + if (notificationObserver == nil) { + notificationObserver = [[AFActivityIndicatorViewNotificationObserver alloc] initWithActivityIndicatorView:self]; + objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return notificationObserver; +} + +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task { + [[self af_notificationObserver] setAnimatingWithStateOfTask:task]; +} + +@end + +@implementation AFActivityIndicatorViewNotificationObserver + +- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView +{ + self = [super init]; + if (self) { + _activityIndicatorView = activityIndicatorView; + } + return self; +} + +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + + if (task) { + if (task.state != NSURLSessionTaskStateCompleted) { + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreceiver-is-weak" +#pragma clang diagnostic ignored "-Warc-repeated-use-of-weak" + if (task.state == NSURLSessionTaskStateRunning) { + [self.activityIndicatorView startAnimating]; + } else { + [self.activityIndicatorView stopAnimating]; + } +#pragma clang diagnostic pop + + [notificationCenter addObserver:self selector:@selector(af_startAnimating) name:AFNetworkingTaskDidResumeNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidCompleteNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidSuspendNotification object:task]; + } + } +} + +#pragma mark - + +- (void)af_startAnimating { + dispatch_async(dispatch_get_main_queue(), ^{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreceiver-is-weak" + [self.activityIndicatorView startAnimating]; +#pragma clang diagnostic pop + }); +} + +- (void)af_stopAnimating { + dispatch_async(dispatch_get_main_queue(), ^{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreceiver-is-weak" + [self.activityIndicatorView stopAnimating]; +#pragma clang diagnostic pop + }); +} + +#pragma mark - + +- (void)dealloc { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; +} + +@end + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h new file mode 100644 index 00000000..2f4cdab7 --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h @@ -0,0 +1,175 @@ +// UIButton+AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class AFImageDownloader; + +/** + This category adds methods to the UIKit framework's `UIButton` class. The methods in this category provide support for loading remote images and background images asynchronously from a URL. + + @warning Compound values for control `state` (such as `UIControlStateHighlighted | UIControlStateDisabled`) are unsupported. + */ +@interface UIButton (AFNetworking) + +///------------------------------------ +/// @name Accessing the Image Downloader +///------------------------------------ + +/** + Set the shared image downloader used to download images. + + @param imageDownloader The shared image downloader used to download images. +*/ ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader; + +/** + The shared image downloader used to download images. + */ ++ (AFImageDownloader *)sharedImageDownloader; + +///-------------------- +/// @name Setting Image +///-------------------- + +/** + Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + @param state The control state. + @param url The URL used for the image request. + */ +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url; + +/** + Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + @param state The control state. + @param url The URL used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes. + */ +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage; + +/** + Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setImage:forState:` is applied. + + @param state The control state. + @param urlRequest The URL request used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + */ +- (void)setImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + + +///------------------------------- +/// @name Setting Background Image +///------------------------------- + +/** + Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous background image request for the receiver will be cancelled. + + If the background image is cached locally, the background image is set immediately, otherwise the specified placeholder background image will be set immediately, and then the remote background image will be set once the request is finished. + + @param state The control state. + @param url The URL used for the background image request. + */ +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url; + +/** + Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + @param state The control state. + @param url The URL used for the background image request. + @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. + */ +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage; + +/** + Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setBackgroundImage:forState:` is applied. + + @param state The control state. + @param urlRequest The URL request used for the image request. + @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + */ +- (void)setBackgroundImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + + +///------------------------------ +/// @name Canceling Image Loading +///------------------------------ + +/** + Cancels any executing image task for the specified control state of the receiver, if one exists. + + @param state The control state. + */ +- (void)cancelImageDownloadTaskForState:(UIControlState)state; + +/** + Cancels any executing background image task for the specified control state of the receiver, if one exists. + + @param state The control state. + */ +- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m new file mode 100644 index 00000000..9ea2b995 --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m @@ -0,0 +1,305 @@ +// UIButton+AFNetworking.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "UIButton+AFNetworking.h" + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "UIImageView+AFNetworking.h" +#import "AFImageDownloader.h" + +@interface UIButton (_AFNetworking) +@end + +@implementation UIButton (_AFNetworking) + +#pragma mark - + +static char AFImageDownloadReceiptNormal; +static char AFImageDownloadReceiptHighlighted; +static char AFImageDownloadReceiptSelected; +static char AFImageDownloadReceiptDisabled; + +static const char * af_imageDownloadReceiptKeyForState(UIControlState state) { + switch (state) { + case UIControlStateHighlighted: + return &AFImageDownloadReceiptHighlighted; + case UIControlStateSelected: + return &AFImageDownloadReceiptSelected; + case UIControlStateDisabled: + return &AFImageDownloadReceiptDisabled; + case UIControlStateNormal: + default: + return &AFImageDownloadReceiptNormal; + } +} + +- (AFImageDownloadReceipt *)af_imageDownloadReceiptForState:(UIControlState)state { + return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_imageDownloadReceiptKeyForState(state)); +} + +- (void)af_setImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt + forState:(UIControlState)state +{ + objc_setAssociatedObject(self, af_imageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +static char AFBackgroundImageDownloadReceiptNormal; +static char AFBackgroundImageDownloadReceiptHighlighted; +static char AFBackgroundImageDownloadReceiptSelected; +static char AFBackgroundImageDownloadReceiptDisabled; + +static const char * af_backgroundImageDownloadReceiptKeyForState(UIControlState state) { + switch (state) { + case UIControlStateHighlighted: + return &AFBackgroundImageDownloadReceiptHighlighted; + case UIControlStateSelected: + return &AFBackgroundImageDownloadReceiptSelected; + case UIControlStateDisabled: + return &AFBackgroundImageDownloadReceiptDisabled; + case UIControlStateNormal: + default: + return &AFBackgroundImageDownloadReceiptNormal; + } +} + +- (AFImageDownloadReceipt *)af_backgroundImageDownloadReceiptForState:(UIControlState)state { + return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state)); +} + +- (void)af_setBackgroundImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt + forState:(UIControlState)state +{ + objc_setAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end + +#pragma mark - + +@implementation UIButton (AFNetworking) + ++ (AFImageDownloader *)sharedImageDownloader { + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + return objc_getAssociatedObject(self, @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance]; +#pragma clang diagnostic pop +} + ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader { + objc_setAssociatedObject(self, @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url +{ + [self setImageForState:state withURL:url placeholderImage:nil]; +} + +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(UIImage *)placeholderImage +{ + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; + + [self setImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; +} + +- (void)setImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure +{ + if ([self isActiveTaskURLEqualToURLRequest:urlRequest forState:state]) { + return; + } + + [self cancelImageDownloadTaskForState:state]; + + AFImageDownloader *downloader = [[self class] sharedImageDownloader]; + id imageCache = downloader.imageCache; + + //Use the image from the image cache if it exists + UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; + if (cachedImage) { + if (success) { + success(urlRequest, nil, cachedImage); + } else { + [self setImage:cachedImage forState:state]; + } + [self af_setImageDownloadReceipt:nil forState:state]; + } else { + if (placeholderImage) { + [self setImage:placeholderImage forState:state]; + } + + __weak __typeof(self)weakSelf = self; + NSUUID *downloadID = [NSUUID UUID]; + AFImageDownloadReceipt *receipt; + receipt = [downloader + downloadImageForURLRequest:urlRequest + withReceiptID:downloadID + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { + if (success) { + success(request, response, responseObject); + } else if(responseObject) { + [strongSelf setImage:responseObject forState:state]; + } + [strongSelf af_setImageDownloadReceipt:nil forState:state]; + } + + } + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { + if (failure) { + failure(request, response, error); + } + [strongSelf af_setImageDownloadReceipt:nil forState:state]; + } + }]; + + [self af_setImageDownloadReceipt:receipt forState:state]; + } +} + +#pragma mark - + +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url +{ + [self setBackgroundImageForState:state withURL:url placeholderImage:nil]; +} + +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage +{ + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; + + [self setBackgroundImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; +} + +- (void)setBackgroundImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure +{ + if ([self isActiveBackgroundTaskURLEqualToURLRequest:urlRequest forState:state]) { + return; + } + + [self cancelImageDownloadTaskForState:state]; + + AFImageDownloader *downloader = [[self class] sharedImageDownloader]; + id imageCache = downloader.imageCache; + + //Use the image from the image cache if it exists + UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; + if (cachedImage) { + if (success) { + success(urlRequest, nil, cachedImage); + } else { + [self setBackgroundImage:cachedImage forState:state]; + } + [self af_setBackgroundImageDownloadReceipt:nil forState:state]; + } else { + if (placeholderImage) { + [self setBackgroundImage:placeholderImage forState:state]; + } + + __weak __typeof(self)weakSelf = self; + NSUUID *downloadID = [NSUUID UUID]; + AFImageDownloadReceipt *receipt; + receipt = [downloader + downloadImageForURLRequest:urlRequest + withReceiptID:downloadID + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { + if (success) { + success(request, response, responseObject); + } else if(responseObject) { + [strongSelf setBackgroundImage:responseObject forState:state]; + } + [strongSelf af_setImageDownloadReceipt:nil forState:state]; + } + + } + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { + if (failure) { + failure(request, response, error); + } + [strongSelf af_setBackgroundImageDownloadReceipt:nil forState:state]; + } + }]; + + [self af_setBackgroundImageDownloadReceipt:receipt forState:state]; + } +} + +#pragma mark - + +- (void)cancelImageDownloadTaskForState:(UIControlState)state { + AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state]; + if (receipt != nil) { + [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt]; + [self af_setImageDownloadReceipt:nil forState:state]; + } +} + +- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state { + AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state]; + if (receipt != nil) { + [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt]; + [self af_setBackgroundImageDownloadReceipt:nil forState:state]; + } +} + +- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state { + AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state]; + return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; +} + +- (BOOL)isActiveBackgroundTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state { + AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state]; + return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; +} + + +@end + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h new file mode 100644 index 00000000..14744cdd --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h @@ -0,0 +1,35 @@ +// +// UIImage+AFNetworking.h +// +// +// Created by Paulo Ferreira on 08/07/15. +// +// 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 TARGET_OS_IOS || TARGET_OS_TV + +#import + +@interface UIImage (AFNetworking) + ++ (UIImage*) safeImageWithData:(NSData*)data; + +@end + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h new file mode 100644 index 00000000..06df54ac --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h @@ -0,0 +1,109 @@ +// UIImageView+AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class AFImageDownloader; + +/** + This category adds methods to the UIKit framework's `UIImageView` class. The methods in this category provide support for loading remote images asynchronously from a URL. + */ +@interface UIImageView (AFNetworking) + +///------------------------------------ +/// @name Accessing the Image Downloader +///------------------------------------ + +/** + Set the shared image downloader used to download images. + + @param imageDownloader The shared image downloader used to download images. + */ ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader; + +/** + The shared image downloader used to download images. + */ ++ (AFImageDownloader *)sharedImageDownloader; + +///-------------------- +/// @name Setting Image +///-------------------- + +/** + Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` + + @param url The URL used for the image request. + */ +- (void)setImageWithURL:(NSURL *)url; + +/** + Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` + + @param url The URL used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. + */ +- (void)setImageWithURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage; + +/** + Asynchronously downloads an image from the specified URL request, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is applied. + + @param urlRequest The URL request used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + */ +- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + +/** + Cancels any executing image operation for the receiver, if one exists. + */ +- (void)cancelImageDownloadTask; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m new file mode 100644 index 00000000..b4189305 --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m @@ -0,0 +1,161 @@ +// UIImageView+AFNetworking.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "UIImageView+AFNetworking.h" + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFImageDownloader.h" + +@interface UIImageView (_AFNetworking) +@property (readwrite, nonatomic, strong, setter = af_setActiveImageDownloadReceipt:) AFImageDownloadReceipt *af_activeImageDownloadReceipt; +@end + +@implementation UIImageView (_AFNetworking) + +- (AFImageDownloadReceipt *)af_activeImageDownloadReceipt { + return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, @selector(af_activeImageDownloadReceipt)); +} + +- (void)af_setActiveImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt { + objc_setAssociatedObject(self, @selector(af_activeImageDownloadReceipt), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end + +#pragma mark - + +@implementation UIImageView (AFNetworking) + ++ (AFImageDownloader *)sharedImageDownloader { + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + return objc_getAssociatedObject(self, @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance]; +#pragma clang diagnostic pop +} + ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader { + objc_setAssociatedObject(self, @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)setImageWithURL:(NSURL *)url { + [self setImageWithURL:url placeholderImage:nil]; +} + +- (void)setImageWithURL:(NSURL *)url + placeholderImage:(UIImage *)placeholderImage +{ + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; + + [self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; +} + +- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(UIImage *)placeholderImage + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure +{ + + if ([urlRequest URL] == nil) { + [self cancelImageDownloadTask]; + self.image = placeholderImage; + return; + } + + if ([self isActiveTaskURLEqualToURLRequest:urlRequest]){ + return; + } + + [self cancelImageDownloadTask]; + + AFImageDownloader *downloader = [[self class] sharedImageDownloader]; + id imageCache = downloader.imageCache; + + //Use the image from the image cache if it exists + UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; + if (cachedImage) { + if (success) { + success(urlRequest, nil, cachedImage); + } else { + self.image = cachedImage; + } + [self clearActiveDownloadInformation]; + } else { + if (placeholderImage) { + self.image = placeholderImage; + } + + __weak __typeof(self)weakSelf = self; + NSUUID *downloadID = [NSUUID UUID]; + AFImageDownloadReceipt *receipt; + receipt = [downloader + downloadImageForURLRequest:urlRequest + withReceiptID:downloadID + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) { + if (success) { + success(request, response, responseObject); + } else if(responseObject) { + strongSelf.image = responseObject; + } + [strongSelf clearActiveDownloadInformation]; + } + + } + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) { + if (failure) { + failure(request, response, error); + } + [strongSelf clearActiveDownloadInformation]; + } + }]; + + self.af_activeImageDownloadReceipt = receipt; + } +} + +- (void)cancelImageDownloadTask { + if (self.af_activeImageDownloadReceipt != nil) { + [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:self.af_activeImageDownloadReceipt]; + [self clearActiveDownloadInformation]; + } +} + +- (void)clearActiveDownloadInformation { + self.af_activeImageDownloadReceipt = nil; +} + +- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest { + return [self.af_activeImageDownloadReceipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; +} + +@end + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h new file mode 100644 index 00000000..8f1590be --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h @@ -0,0 +1,42 @@ +// UIKit+AFNetworking.h +// +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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 TARGET_OS_IOS || TARGET_OS_TV +#import + +#ifndef _UIKIT_AFNETWORKING_ + #define _UIKIT_AFNETWORKING_ + +#if TARGET_OS_IOS + #import "AFAutoPurgingImageCache.h" + #import "AFImageDownloader.h" + #import "AFNetworkActivityIndicatorManager.h" + #import "UIRefreshControl+AFNetworking.h" + #import "UIWebView+AFNetworking.h" +#endif + + #import "UIActivityIndicatorView+AFNetworking.h" + #import "UIButton+AFNetworking.h" + #import "UIImageView+AFNetworking.h" + #import "UIProgressView+AFNetworking.h" +#endif /* _UIKIT_AFNETWORKING_ */ +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h new file mode 100644 index 00000000..c9d7e3e2 --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h @@ -0,0 +1,64 @@ +// UIProgressView+AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import + +NS_ASSUME_NONNULL_BEGIN + + +/** + This category adds methods to the UIKit framework's `UIProgressView` class. The methods in this category provide support for binding the progress to the upload and download progress of a session task. + */ +@interface UIProgressView (AFNetworking) + +///------------------------------------ +/// @name Setting Session Task Progress +///------------------------------------ + +/** + Binds the progress to the upload progress of the specified session task. + + @param task The session task. + @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. + */ +- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task + animated:(BOOL)animated; + +/** + Binds the progress to the download progress of the specified session task. + + @param task The session task. + @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. + */ +- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task + animated:(BOOL)animated; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m new file mode 100644 index 00000000..5934a617 --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m @@ -0,0 +1,118 @@ +// UIProgressView+AFNetworking.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "UIProgressView+AFNetworking.h" + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFURLSessionManager.h" + +static void * AFTaskCountOfBytesSentContext = &AFTaskCountOfBytesSentContext; +static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedContext; + +#pragma mark - + +@implementation UIProgressView (AFNetworking) + +- (BOOL)af_uploadProgressAnimated { + return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_uploadProgressAnimated)) boolValue]; +} + +- (void)af_setUploadProgressAnimated:(BOOL)animated { + objc_setAssociatedObject(self, @selector(af_uploadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (BOOL)af_downloadProgressAnimated { + return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_downloadProgressAnimated)) boolValue]; +} + +- (void)af_setDownloadProgressAnimated:(BOOL)animated { + objc_setAssociatedObject(self, @selector(af_downloadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task + animated:(BOOL)animated +{ + [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext]; + [task addObserver:self forKeyPath:@"countOfBytesSent" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext]; + + [self af_setUploadProgressAnimated:animated]; +} + +- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task + animated:(BOOL)animated +{ + [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; + [task addObserver:self forKeyPath:@"countOfBytesReceived" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; + + [self af_setDownloadProgressAnimated:animated]; +} + +#pragma mark - NSKeyValueObserving + +- (void)observeValueForKeyPath:(NSString *)keyPath + ofObject:(id)object + change:(__unused NSDictionary *)change + context:(void *)context +{ + if (context == AFTaskCountOfBytesSentContext || context == AFTaskCountOfBytesReceivedContext) { + if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) { + if ([object countOfBytesExpectedToSend] > 0) { + dispatch_async(dispatch_get_main_queue(), ^{ + [self setProgress:[object countOfBytesSent] / ([object countOfBytesExpectedToSend] * 1.0f) animated:self.af_uploadProgressAnimated]; + }); + } + } + + if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) { + if ([object countOfBytesExpectedToReceive] > 0) { + dispatch_async(dispatch_get_main_queue(), ^{ + [self setProgress:[object countOfBytesReceived] / ([object countOfBytesExpectedToReceive] * 1.0f) animated:self.af_downloadProgressAnimated]; + }); + } + } + + if ([keyPath isEqualToString:NSStringFromSelector(@selector(state))]) { + if ([(NSURLSessionTask *)object state] == NSURLSessionTaskStateCompleted) { + @try { + [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(state))]; + + if (context == AFTaskCountOfBytesSentContext) { + [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))]; + } + + if (context == AFTaskCountOfBytesReceivedContext) { + [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))]; + } + } + @catch (NSException * __unused exception) {} + } + } + } +} + +@end + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h new file mode 100644 index 00000000..a6e598e8 --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h @@ -0,0 +1,53 @@ +// UIRefreshControl+AFNetworking.m +// +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import + +#import + +#if TARGET_OS_IOS + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + This category adds methods to the UIKit framework's `UIRefreshControl` class. The methods in this category provide support for automatically beginning and ending refreshing depending on the loading state of a session task. + */ +@interface UIRefreshControl (AFNetworking) + +///----------------------------------- +/// @name Refreshing for Session Tasks +///----------------------------------- + +/** + Binds the refreshing state to the state of the specified task. + + @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. + */ +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m new file mode 100644 index 00000000..d40d01ff --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m @@ -0,0 +1,122 @@ +// UIRefreshControl+AFNetworking.m +// +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "UIRefreshControl+AFNetworking.h" +#import + +#if TARGET_OS_IOS + +#import "AFURLSessionManager.h" + +@interface AFRefreshControlNotificationObserver : NSObject +@property (readonly, nonatomic, weak) UIRefreshControl *refreshControl; +- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl; + +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; + +@end + +@implementation UIRefreshControl (AFNetworking) + +- (AFRefreshControlNotificationObserver *)af_notificationObserver { + AFRefreshControlNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver)); + if (notificationObserver == nil) { + notificationObserver = [[AFRefreshControlNotificationObserver alloc] initWithActivityRefreshControl:self]; + objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return notificationObserver; +} + +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { + [[self af_notificationObserver] setRefreshingWithStateOfTask:task]; +} + +@end + +@implementation AFRefreshControlNotificationObserver + +- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl +{ + self = [super init]; + if (self) { + _refreshControl = refreshControl; + } + return self; +} + +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + + if (task) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreceiver-is-weak" +#pragma clang diagnostic ignored "-Warc-repeated-use-of-weak" + if (task.state == NSURLSessionTaskStateRunning) { + [self.refreshControl beginRefreshing]; + + [notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingTaskDidResumeNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidCompleteNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidSuspendNotification object:task]; + } else { + [self.refreshControl endRefreshing]; + } +#pragma clang diagnostic pop + } +} + +#pragma mark - + +- (void)af_beginRefreshing { + dispatch_async(dispatch_get_main_queue(), ^{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreceiver-is-weak" + [self.refreshControl beginRefreshing]; +#pragma clang diagnostic pop + }); +} + +- (void)af_endRefreshing { + dispatch_async(dispatch_get_main_queue(), ^{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreceiver-is-weak" + [self.refreshControl endRefreshing]; +#pragma clang diagnostic pop + }); +} + +#pragma mark - + +- (void)dealloc { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; +} + +@end + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h new file mode 100644 index 00000000..41c3fb21 --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h @@ -0,0 +1,80 @@ +// UIWebView+AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import + +#import + +#if TARGET_OS_IOS + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class AFHTTPSessionManager; + +/** + This category adds methods to the UIKit framework's `UIWebView` class. The methods in this category provide increased control over the request cycle, including progress monitoring and success / failure handling. + + @discussion When using these category methods, make sure to assign `delegate` for the web view, which implements `–webView:shouldStartLoadWithRequest:navigationType:` appropriately. This allows for tapped links to be loaded through AFNetworking, and can ensure that `canGoBack` & `canGoForward` update their values correctly. + */ +@interface UIWebView (AFNetworking) + +/** + The session manager used to download all requests. + */ +@property (nonatomic, strong) AFHTTPSessionManager *sessionManager; + +/** + Asynchronously loads the specified request. + + @param request A URL request identifying the location of the content to load. This must not be `nil`. + @param progress A progress object monitoring the current download progress. + @param success A block object to be executed when the request finishes loading successfully. This block returns the HTML string to be loaded by the web view, and takes two arguments: the response, and the response string. + @param failure A block object to be executed when the data task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred. + */ +- (void)loadRequest:(NSURLRequest *)request + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success + failure:(nullable void (^)(NSError *error))failure; + +/** + Asynchronously loads the data associated with a particular request with a specified MIME type and text encoding. + + @param request A URL request identifying the location of the content to load. This must not be `nil`. + @param MIMEType The MIME type of the content. Defaults to the content type of the response if not specified. + @param textEncodingName The IANA encoding name, as in `utf-8` or `utf-16`. Defaults to the response text encoding if not specified. +@param progress A progress object monitoring the current download progress. + @param success A block object to be executed when the request finishes loading successfully. This block returns the data to be loaded by the web view and takes two arguments: the response, and the downloaded data. + @param failure A block object to be executed when the data task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred. + */ +- (void)loadRequest:(NSURLRequest *)request + MIMEType:(nullable NSString *)MIMEType + textEncodingName:(nullable NSString *)textEncodingName + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success + failure:(nullable void (^)(NSError *error))failure; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m new file mode 100644 index 00000000..5bc2c79d --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m @@ -0,0 +1,162 @@ +// UIWebView+AFNetworking.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// 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. + +#import "UIWebView+AFNetworking.h" + +#import + +#if TARGET_OS_IOS + +#import "AFHTTPSessionManager.h" +#import "AFURLResponseSerialization.h" +#import "AFURLRequestSerialization.h" + +@interface UIWebView (_AFNetworking) +@property (readwrite, nonatomic, strong, setter = af_setURLSessionTask:) NSURLSessionDataTask *af_URLSessionTask; +@end + +@implementation UIWebView (_AFNetworking) + +- (NSURLSessionDataTask *)af_URLSessionTask { + return (NSURLSessionDataTask *)objc_getAssociatedObject(self, @selector(af_URLSessionTask)); +} + +- (void)af_setURLSessionTask:(NSURLSessionDataTask *)af_URLSessionTask { + objc_setAssociatedObject(self, @selector(af_URLSessionTask), af_URLSessionTask, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end + +#pragma mark - + +@implementation UIWebView (AFNetworking) + +- (AFHTTPSessionManager *)sessionManager { + static AFHTTPSessionManager *_af_defaultHTTPSessionManager = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _af_defaultHTTPSessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + _af_defaultHTTPSessionManager.requestSerializer = [AFHTTPRequestSerializer serializer]; + _af_defaultHTTPSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer]; + }); + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + return objc_getAssociatedObject(self, @selector(sessionManager)) ?: _af_defaultHTTPSessionManager; +#pragma clang diagnostic pop +} + +- (void)setSessionManager:(AFHTTPSessionManager *)sessionManager { + objc_setAssociatedObject(self, @selector(sessionManager), sessionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (AFHTTPResponseSerializer *)responseSerializer { + static AFHTTPResponseSerializer *_af_defaultResponseSerializer = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer]; + }); + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer; +#pragma clang diagnostic pop +} + +- (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { + objc_setAssociatedObject(self, @selector(responseSerializer), responseSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)loadRequest:(NSURLRequest *)request + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + success:(NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success + failure:(void (^)(NSError *error))failure +{ + [self loadRequest:request MIMEType:nil textEncodingName:nil progress:progress success:^NSData *(NSHTTPURLResponse *response, NSData *data) { + NSStringEncoding stringEncoding = NSUTF8StringEncoding; + if (response.textEncodingName) { + CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName); + if (encoding != kCFStringEncodingInvalidId) { + stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding); + } + } + + NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding]; + if (success) { + string = success(response, string); + } + + return [string dataUsingEncoding:stringEncoding]; + } failure:failure]; +} + +- (void)loadRequest:(NSURLRequest *)request + MIMEType:(NSString *)MIMEType + textEncodingName:(NSString *)textEncodingName + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + success:(NSData * (^)(NSHTTPURLResponse *response, NSData *data))success + failure:(void (^)(NSError *error))failure +{ + NSParameterAssert(request); + + if (self.af_URLSessionTask.state == NSURLSessionTaskStateRunning || self.af_URLSessionTask.state == NSURLSessionTaskStateSuspended) { + [self.af_URLSessionTask cancel]; + } + self.af_URLSessionTask = nil; + + __weak __typeof(self)weakSelf = self; + NSURLSessionDataTask *dataTask; + dataTask = [self.sessionManager + GET:request.URL.absoluteString + parameters:nil + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) { + __strong __typeof(weakSelf) strongSelf = weakSelf; + if (success) { + success((NSHTTPURLResponse *)task.response, responseObject); + } + [strongSelf loadData:responseObject MIMEType:MIMEType textEncodingName:textEncodingName baseURL:[task.currentRequest URL]]; + + if ([strongSelf.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) { + [strongSelf.delegate webViewDidFinishLoad:strongSelf]; + } + } + failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) { + if (failure) { + failure(error); + } + }]; + self.af_URLSessionTask = dataTask; + if (progress != nil) { + *progress = [self.sessionManager downloadProgressForTask:dataTask]; + } + [self.af_URLSessionTask resume]; + + if ([self.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) { + [self.delegate webViewDidStartLoad:self]; + } +} + +@end + +#endif \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env b/its/plugin/projects/AFNetworking/fastlane/.env new file mode 100644 index 00000000..46a98e83 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env @@ -0,0 +1,10 @@ +AF_WORKSPACE="AFNetworking.xcworkspace" + +AF_IOS_FRAMEWORK_SCHEME="AFNetworking iOS" +AF_TVOS_FRAMEWORK_SCHEME="AFNetworking tvOS" +AF_OSX_FRAMEWORK_SCHEME="AFNetworking OS X" + +AF_IOS_EXAMPLE_SCHEME="iOS Example" +AF_TVOS_EXAMPLE_SCHEME="tvOS Example" +AF_OSX_EXAMPLE_SCHEME="OS X Example" + diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.default b/its/plugin/projects/AFNetworking/fastlane/.env.default new file mode 100644 index 00000000..be94c17a --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.default @@ -0,0 +1,15 @@ +AF_IOS_SDK=iphonesimulator9.2 +AF_MAC_SDK=macosx10.11 +AF_TVOS_SDK=appletvsimulator9.1 + +AF_CONFIGURATION=Release + +SCAN_WORKSPACE=$AF_WORKSPACE +SCAN_SCHEME=$AF_IOS_FRAMEWORK_SCHEME +SCAN_DESTINATION="OS=9.2,name=iPhone 6s" +SCAN_SDK=$AF_IOS_SDK +SCAN_OUTPUT_DIRECTORY=fastlane/test-output + +EXAMPLE_WORKSPACE=$AF_WORKSPACE +EXAMPLE_SCHEME=$AF_IOS_EXAMPLE_SCHEME +EXAMPLE_DESTINATION=$SCAN_DESTINATION \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.deploy b/its/plugin/projects/AFNetworking/fastlane/.env.deploy new file mode 100644 index 00000000..a123e622 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.deploy @@ -0,0 +1,14 @@ +DEPLOY_BRANCH=master +DEPLOY_PLIST_PATH=Framework/Info.plist +DEPLOY_PODSPEC=AFNetworking.podspec +DEPLOY_REMOTE=origin + +DEPLOY_CHANGELOG_PATH=CHANGELOG.md +DEPLOY_CHANGELOG_DELIMITER=--- + +# Used for CHANGELOG Generation and Github Release Management +GITHUB_OWNER=AFNetworking +GITHUB_REPOSITORY=AFNetworking +# CI Should Provide GITHUB_API_TOKEN + +CARTHAGE_FRAMEWORK_NAME=AFNetworking \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.ios81_xcode7 b/its/plugin/projects/AFNetworking/fastlane/.env.ios81_xcode7 new file mode 100644 index 00000000..fb6f3715 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.ios81_xcode7 @@ -0,0 +1,3 @@ +SCAN_DESTINATION="OS=8.1,name=iPhone 4S" +EXAMPLE_DESTINATION=$SCAN_DESTINATION +SCAN_SDK=iphonesimulator9.0 \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.ios83 b/its/plugin/projects/AFNetworking/fastlane/.env.ios83 new file mode 100644 index 00000000..0d6dca99 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.ios83 @@ -0,0 +1,2 @@ +SCAN_DESTINATION="OS=8.3,name=iPhone 5S" +EXAMPLE_DESTINATION=$SCAN_DESTINATION \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.ios84 b/its/plugin/projects/AFNetworking/fastlane/.env.ios84 new file mode 100644 index 00000000..5c20969d --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.ios84 @@ -0,0 +1,2 @@ +SCAN_DESTINATION="OS=8.4,name=iPhone 6" +EXAMPLE_DESTINATION=$SCAN_DESTINATION \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.ios90_xcode7 b/its/plugin/projects/AFNetworking/fastlane/.env.ios90_xcode7 new file mode 100644 index 00000000..e89b458d --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.ios90_xcode7 @@ -0,0 +1,3 @@ +SCAN_DESTINATION="OS=9.0,name=iPhone 6 Plus" +EXAMPLE_DESTINATION=$SCAN_DESTINATION +SCAN_SDK=iphonesimulator9.0 \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.ios91_xcode71 b/its/plugin/projects/AFNetworking/fastlane/.env.ios91_xcode71 new file mode 100644 index 00000000..5f8dd00c --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.ios91_xcode71 @@ -0,0 +1,3 @@ +SCAN_DESTINATION="OS=9.1,name=iPhone 6s" +EXAMPLE_DESTINATION=$SCAN_DESTINATION +SCAN_SDK=iphonesimulator9.1 \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.ios92 b/its/plugin/projects/AFNetworking/fastlane/.env.ios92 new file mode 100644 index 00000000..67e5e829 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.ios92 @@ -0,0 +1,2 @@ +SCAN_DESTINATION="OS=9.2,name=iPhone 6s" +EXAMPLE_DESTINATION=$SCAN_DESTINATION \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.ios93_xcode73 b/its/plugin/projects/AFNetworking/fastlane/.env.ios93_xcode73 new file mode 100644 index 00000000..b0516eb0 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.ios93_xcode73 @@ -0,0 +1,3 @@ +SCAN_DESTINATION="OS=9.3,name=iPhone 6s" +EXAMPLE_DESTINATION=$SCAN_DESTINATION +SCAN_SDK=iphonesimulator9.3 \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.osx b/its/plugin/projects/AFNetworking/fastlane/.env.osx new file mode 100644 index 00000000..d56e363c --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.osx @@ -0,0 +1,6 @@ +SCAN_SCHEME=$AF_OSX_FRAMEWORK_SCHEME +SCAN_DESTINATION="arch=x86_64" +SCAN_SDK=$AF_OSX_SDK + +EXAMPLE_SCHEME=$AF_OSX_EXAMPLE_SCHEME +EXAMPLE_DESTINATION=$SCAN_DESTINATION \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.tvos90_xcode71 b/its/plugin/projects/AFNetworking/fastlane/.env.tvos90_xcode71 new file mode 100644 index 00000000..98da9c0c --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.tvos90_xcode71 @@ -0,0 +1,6 @@ +SCAN_SCHEME=$AF_TVOS_FRAMEWORK_SCHEME +SCAN_DESTINATION="OS=9.0,name=Apple TV 1080p" +SCAN_SDK=appletvsimulator9.0 + +EXAMPLE_SCHEME=$AF_TVOS_EXAMPLE_SCHEME +EXAMPLE_DESTINATION=$SCAN_DESTINATION \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.tvos91 b/its/plugin/projects/AFNetworking/fastlane/.env.tvos91 new file mode 100644 index 00000000..54cd02b3 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.tvos91 @@ -0,0 +1,6 @@ +SCAN_SCHEME=$AF_TVOS_FRAMEWORK_SCHEME +SCAN_DESTINATION="OS=9.1,name=Apple TV 1080p" +SCAN_SDK=$AF_TVOS_SDK + +EXAMPLE_SCHEME=$AF_TVOS_EXAMPLE_SCHEME +EXAMPLE_DESTINATION=$SCAN_DESTINATION \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/Fastfile b/its/plugin/projects/AFNetworking/fastlane/Fastfile new file mode 100644 index 00000000..6a63d4c4 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/Fastfile @@ -0,0 +1,337 @@ +# Customise this file, documentation can be found here: +# https://github.com/KrauseFx/fastlane/tree/master/docs +# All available actions: https://github.com/KrauseFx/fastlane/blob/master/docs/Actions.md +# can also be listed using the `fastlane actions` command + +# Change the syntax highlighting to Ruby +# All lines starting with a # are ignored when running `fastlane` + +# By default, fastlane will send which actions are used +# No personal data is shared, more information on https://github.com/fastlane/enhancer +# Uncomment the following line to opt out +# opt_out_usage + +# If you want to automatically update fastlane if a new version is available: +# update_fastlane + +# This is the minimum version number required. +# Update this, if you use features of a newer version +fastlane_version "1.37.0" +before_all do + # ENV["SLACK_URL"] = "https://hooks.slack.com/services/..." +end + +#Test Lanes +desc "Runs tests and builds example for the given environment" +desc "The lane to run by ci on every commit This lanes calls the lane `test_framework`." +desc "####Example:" +desc "```\nfastlane ci_commit configuration:Debug --env ios91\n```" +desc "####Options" +desc " * **`configuration`**: The build configuration to use. (`AF_CONFIGURATION`)" +desc "" +lane :ci_commit do |options| + if options[:configuration] + configuration = options[:configuration] + elsif ENV["AF_CONFIGURATION"] + configuration = ENV["AF_CONFIGURATION"] + else + configuration = "Release" + end + + test_framework(configuration: configuration) + + af_pod_spec_lint( + quick:true + ) +end + +desc "Runs all tests for the given environment" +desc "Set `scan` action environment variables to control test configuration" +desc "####Example:" +desc "```\nfastlane test_framework configuration:Debug --env ios91\n```" +desc "####Options" +desc " * **`configuration`**: The build configuration to use." +desc "" +lane :test_framework do |options| + scan( + configuration: options[:configuration] + ) + +end + +desc "Produces code coverage information" +desc "Set `scan` action environment variables to control test configuration" +desc "####Example:" +desc "```\nfastlane code_coverage configuration:Debug\n```" +desc "####Options" +desc " * **`configuration`**: The build configuration to use. The only supported configuration is the `Debug` configuration." +desc "" +lane :code_coverage do |options| + if options[:configuration] != "Debug" + Helper.log.info "Not running code coverage lane for #{options[:configuration]} configuration".yellow + else + scan( + configuration: options[:configuration], + xcargs: "OBJROOT=build GCC_GENERATE_TEST_COVERAGE_FILES=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES" + ) + end +end + + +#Deployment Lanes +desc "Prepares the framework for release" +desc "This lane should be run from your local machine, and will push a tag to the remote when finished." +desc " * Verifies the git branch is clean" +desc " * Ensures the lane is running on the master branch" +desc " * Verifies the Github milestone is ready for release" +desc " * Pulls the remote to verify the latest the branch is up to date" +desc " * Updates the version of the info plist path used by the framework" +desc " * Updates the the version of the podspec" +desc " * Generates a changelog based on the Github milestone" +desc " * Updates the changelog file" +desc " * Commits the changes" +desc " * Pushes the commited branch" +desc " * Creates a tag" +desc " * Pushes the tag" +desc "####Example:" +desc "```\nfastlane prepare_framework_release version:3.0.0 --env deploy\n```" +desc "####Options" +desc "It is recommended to manage these options through a .env file. See `fastlane/.env.deploy` for an example." +desc " * **`version`** (required): The new version of the framework" +desc " * **`allow_dirty_branch`**: Allows the git branch to be dirty before continuing. Defaults to false" +desc " * **`remote`**: The name of the git remote. Defaults to `origin`. (`DEPLOY_REMOTE`)" +desc " * **`allow_branch`**: The name of the branch to build from. Defaults to `master`. (`DEPLOY_BRANCH`)" +desc " * **`skip_validate_github_milestone`**: Skips validating a Github milestone. Defaults to false" +desc " * **`skip_git_pull`**: Skips pulling the git remote. Defaults to false" +desc " * **`skip_plist_update`**: Skips updating the version of the info plist. Defaults to false" +desc " * **`plist_path`**: The path of the plist file to update. (`DEPLOY_PLIST_PATH`)" +desc " * **`skip_podspec_update`**: Skips updating the version of the podspec. Defaults to false" +desc " * **`podspec`**: The path of the podspec file to update. (`DEPLOY_PODSPEC`)" +desc " * **`skip_changelog`**: Skip generating a changelog. Defaults to false." +desc " * **`changelog_path`**: The path to the changelog file. (`DEPLOY_CHANGELOG_PATH`)" +desc " * **`changelog_insert_delimiter`**: The delimiter to insert the changelog after. (`DEPLOY_CHANGELOG_DELIMITER`)" +desc "" + +lane :prepare_framework_release do |options| + if !options[:version] + raise "No version specified!".red + end + + #Ensure the branch is clean + if options[:allow_dirty_branch] != true + ensure_git_status_clean + end + + remote = options[:remote] ? options[:remote] : (ENV["DEPLOY_REMOTE"] ? ENV["DEPLOY_REMOTE"] : "origin") + allowed_branch = options[:allow_branch] ? options[:allow_branch] : (ENV["DEPLOY_BRANCH"] ? ENV["DEPLOY_BRANCH"] : "master") + + #Ensure we are on the right branch + ensure_git_branch( + branch:allowed_branch + ) + + #Verify the Github milestone is ready for release + if options[:skip_validate_github_milestone] != true + af_get_github_milestone( + title: options[:version], + verify_for_release:true + ) + end + + #Pull the latest to ensure we are up to date + if options[:skip_git_pull] != true + sh("git pull #{remote} #{allowed_branch}") + end + + #Update the framework plist + if options[:skip_plist_update] != true + plist_path = options[:plist_path] ? options[:plist_path] : ENV["DEPLOY_PLIST_PATH"] + set_info_plist_value( + path: plist_path, + key: "CFBundleVersion", + value: options[:version] + ) + end + + #Update the podspec + if options[:skip_podspec_update] != true + podspec = options[:podpsec] ? options[:podpsec] : ENV["DEPLOY_PODSPEC"] + version_bump_podspec( + path: podspec, + version_number: options[:version] + ) + + end + + #Generate a Changelog + if options[:skip_changelog] != true + changelog = af_generate_github_milestone_changelog( + milestone: options[:version] + ) + + Helper.log.info "Generated Changelog: #{changelog[:title]} #{changelog[:header]} #{changelog[:changelog]}" + + changelog_path = options[:changelog_path] ? options[:changelog_path] : ENV["DEPLOY_CHANGELOG_PATH"] + changelog_insert_delimiter = options[:changelog_insert_delimiter] ? options[:changelog_insert_delimiter] : ENV["DEPLOY_CHANGELOG_DELIMITER"] + af_insert_text_into_file( + file_path: changelog_path, + text: changelog[:title] + changelog[:header] + changelog[:changelog], + insert_delimiter: changelog_insert_delimiter + ) + end + + if prompt(text: "#{options[:version]} has been prepped for release. If you have any additional changes you would like to make to the README or CHANGELOG, please do those before continuing. Would you like to commit, tag, and push #{options[:version]} to #{remote}?".green, boolean: true,ci_input:"y") + + # commit the branch + git_commit( + path: ".", + message: "Preparing for the #{options[:version]} release" + ) + + #push the branch + push_to_git_remote( + remote: remote + ) + + # tag the repo + add_git_tag( + tag: "#{options[:version]}" + ) + + # push the tag + if options [:skip_push_tags] != true + af_push_git_tags_to_remote( + remote: remote + ) + end + + if !is_ci + notification( + title: "Release Preparation Complete", + message: "The tag #{options[:version]} is now available" + ) + end + + else + Helper.log.info "When finished, commit your changes and create your tag.".red + end +end + + +desc "Completes the framework release" +desc "This lane should be from a CI machine, after the tests have passed on the tag build. This lane does the following:" +desc " * Verifies the git branch is clean" +desc " * Ensures the lane is running on the master branch" +desc " * Pulls the remote to verify the latest the branch is up to date" +desc " * Generates a changelog for the Github Release" +desc " * Creates a Github Release" +desc " * Builds Carthage Frameworks" +desc " * Uploads Carthage Framework to Github Release" +desc " * Pushes podspec to pod trunk" +desc " * Lints the pod spec to ensure it is valid" +desc " * Closes the associated Github milestone" +desc "####Example:" +desc "```\nfastlane complete_framework_release --env deploy\n```" +desc "####Options" +desc "It is recommended to manage these options through a .env file. See `fastlane/.env.deploy` for an example." +desc " * **`version`** (required): The new version of the framework. Defaults to the last tag in the repo" +desc " * **`allow_dirty_branch`**: Allows the git branch to be dirty before continuing. Defaults to false" +desc " * **`remote`**: The name of the git remote. Defaults to `origin`. (`DEPLOY_REMOTE`)" +desc " * **`allow_branch`**: The name of the branch to build from. Defaults to `master`. (`DEPLOY_BRANCH`)" +desc " * **`skip_github_release`**: Skips creating a Github release. Defaults to false" +desc " * **`skip_carthage_framework`**: Skips creating a carthage framework. If building a swift framework, this should be disabled. Defaults to false." +desc " * **`skip_pod_push`**: Skips pushing the podspec to trunk." +desc " * **`skip_podspec_update`**: Skips updating the version of the podspec. Defaults to false" +desc " * **`skip_closing_github_milestone`**: Skips closing the associated Github milestone. Defaults to false" +desc "" +lane :complete_framework_release do |options| + if options[:skip_ci_check] != true + if !is_ci + raise "#{lane_context[SharedValues::LANE_NAME]} should be run from a CI machine. If you want to override this, pass 'skip_ci_check:true'".red + end + end + + version = options[:version] ? options[:version] : last_git_tag.strip + Helper.log.info "Using version #{version}" + + #Ensure clean branch + if options[:allow_dirty_branch] != true + ensure_git_status_clean + end + + remote = options[:remote] ? options[:remote] : (ENV["DEPLOY_REMOTE"] ? ENV["DEPLOY_REMOTE"] : "origin") + allowed_branch = options[:allow_branch] ? options[:allow_branch] : (ENV["DEPLOY_BRANCH"] ? ENV["DEPLOY_BRANCH"] : "master") + + #Ensure we are on the right branch + ensure_git_branch( + branch:allowed_branch + ) + + #Pull the latest to ensure we are up to date + if options[:skip_git_pull] != true + sh("git pull #{remote} #{allowed_branch}") + end + + # Create a release + #* Upload Notes + #* Upload Carthage Asset + if options[:skip_github_release] != true + af_generate_github_milestone_changelog( + milestone: version + ) + + body = lane_context[SharedValues::GITHUB_MILESTONE_CHANGELOG][:header] + lane_context[SharedValues::GITHUB_MILESTONE_CHANGELOG][:changelog] + af_create_github_release( + tag_name: version, + name: version, + body: body + ) + + # generate the carthage zip + if options[:skip_carthage_framework] != true + af_build_carthage_frameworks + + af_upload_asset_for_github_release( + file_path:lane_context[SharedValues::CARTHAGE_FRAMEWORK] + ) + + end + end + + #pod trunk push + if options[:skip_pod_push] != true + pod_push + + #pod spec lint + af_pod_spec_lint + end + + if options[:skip_closing_github_milestone] != true + af_get_github_milestone( + title: version + ) + + af_update_github_milestone( + state: "closed" + ) + end +end + + +after_all do |lane| + # This block is called, only if the executed lane was successful + + # slack( + # message: "Successfully deployed new App Update." + # ) +end + +error do |lane, exception| + # slack( + # message: exception.message, + # success: false + # ) +end + +# More information about multiple platforms in fastlane: https://github.com/KrauseFx/fastlane/blob/master/docs/Platforms.md +# All available actions: https://github.com/KrauseFx/fastlane/blob/master/docs/Actions.md diff --git a/its/plugin/projects/AFNetworking/fastlane/README.md b/its/plugin/projects/AFNetworking/fastlane/README.md new file mode 100644 index 00000000..f32f19ea --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/README.md @@ -0,0 +1,196 @@ +fastlane documentation +================ +# Installation +``` +sudo gem install fastlane +``` +# Available Actions +### ci_commit +``` +fastlane ci_commit +``` +Runs tests and builds example for the given environment + +The lane to run by ci on every commit This lanes calls the lane `test_framework`. + +####Example: + +``` +fastlane ci_commit configuration:Debug --env ios91 +``` + +####Options + + * **`configuration`**: The build configuration to use. (`AF_CONFIGURATION`) + + +### test_framework +``` +fastlane test_framework +``` +Runs all tests for the given environment + +Set `scan` action environment variables to control test configuration + +####Example: + +``` +fastlane test_framework configuration:Debug --env ios91 +``` + +####Options + + * **`configuration`**: The build configuration to use. + + +### code_coverage +``` +fastlane code_coverage +``` +Produces code coverage information + +Set `scan` action environment variables to control test configuration + +####Example: + +``` +fastlane code_coverage configuration:Debug +``` + +####Options + + * **`configuration`**: The build configuration to use. The only supported configuration is the `Debug` configuration. + + +### prepare_framework_release +``` +fastlane prepare_framework_release +``` +Prepares the framework for release + +This lane should be run from your local machine, and will push a tag to the remote when finished. + + * Verifies the git branch is clean + + * Ensures the lane is running on the master branch + + * Verifies the Github milestone is ready for release + + * Pulls the remote to verify the latest the branch is up to date + + * Updates the version of the info plist path used by the framework + + * Updates the the version of the podspec + + * Generates a changelog based on the Github milestone + + * Updates the changelog file + + * Commits the changes + + * Pushes the commited branch + + * Creates a tag + + * Pushes the tag + +####Example: + +``` +fastlane prepare_framework_release version:3.0.0 --env deploy +``` + +####Options + +It is recommended to manage these options through a .env file. See `fastlane/.env.deploy` for an example. + + * **`version`** (required): The new version of the framework + + * **`allow_dirty_branch`**: Allows the git branch to be dirty before continuing. Defaults to false + + * **`remote`**: The name of the git remote. Defaults to `origin`. (`DEPLOY_REMOTE`) + + * **`allow_branch`**: The name of the branch to build from. Defaults to `master`. (`DEPLOY_BRANCH`) + + * **`skip_validate_github_milestone`**: Skips validating a Github milestone. Defaults to false + + * **`skip_git_pull`**: Skips pulling the git remote. Defaults to false + + * **`skip_plist_update`**: Skips updating the version of the info plist. Defaults to false + + * **`plist_path`**: The path of the plist file to update. (`DEPLOY_PLIST_PATH`) + + * **`skip_podspec_update`**: Skips updating the version of the podspec. Defaults to false + + * **`podspec`**: The path of the podspec file to update. (`DEPLOY_PODSPEC`) + + * **`skip_changelog`**: Skip generating a changelog. Defaults to false. + + * **`changelog_path`**: The path to the changelog file. (`DEPLOY_CHANGELOG_PATH`) + + * **`changelog_insert_delimiter`**: The delimiter to insert the changelog after. (`DEPLOY_CHANGELOG_DELIMITER`) + + +### complete_framework_release +``` +fastlane complete_framework_release +``` +Completes the framework release + +This lane should be from a CI machine, after the tests have passed on the tag build. This lane does the following: + + * Verifies the git branch is clean + + * Ensures the lane is running on the master branch + + * Pulls the remote to verify the latest the branch is up to date + + * Generates a changelog for the Github Release + + * Creates a Github Release + + * Builds Carthage Frameworks + + * Uploads Carthage Framework to Github Release + + * Pushes podspec to pod trunk + + * Lints the pod spec to ensure it is valid + + * Closes the associated Github milestone + +####Example: + +``` +fastlane complete_framework_release --env deploy +``` + +####Options + +It is recommended to manage these options through a .env file. See `fastlane/.env.deploy` for an example. + + * **`version`** (required): The new version of the framework. Defaults to the last tag in the repo + + * **`allow_dirty_branch`**: Allows the git branch to be dirty before continuing. Defaults to false + + * **`remote`**: The name of the git remote. Defaults to `origin`. (`DEPLOY_REMOTE`) + + * **`allow_branch`**: The name of the branch to build from. Defaults to `master`. (`DEPLOY_BRANCH`) + + * **`skip_github_release`**: Skips creating a Github release. Defaults to false + + * **`skip_carthage_framework`**: Skips creating a carthage framework. If building a swift framework, this should be disabled. Defaults to false. + + * **`skip_pod_push`**: Skips pushing the podspec to trunk. + + * **`skip_podspec_update`**: Skips updating the version of the podspec. Defaults to false + + * **`skip_closing_github_milestone`**: Skips closing the associated Github milestone. Defaults to false + + + +---- + +This README.md is auto-generated and will be re-generated every time to run [fastlane](https://fastlane.tools). +More information about fastlane can be found on [https://fastlane.tools](https://fastlane.tools). +The documentation of fastlane can be found on [GitHub](https://github.com/fastlane/fastlane). \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/actions/af_build_carthage_frameworks.rb b/its/plugin/projects/AFNetworking/fastlane/actions/af_build_carthage_frameworks.rb new file mode 100644 index 00000000..abe92c5a --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/actions/af_build_carthage_frameworks.rb @@ -0,0 +1,64 @@ +module Fastlane + module Actions + module SharedValues + CARTHAGE_FRAMEWORK = :CARTHAGE_FRAMEWORK + end + + # To share this integration with the other fastlane users: + # - Fork https://github.com/KrauseFx/fastlane + # - Clone the forked repository + # - Move this integration into lib/fastlane/actions + # - Commit, push and submit the pull request + + class AfBuildCarthageFrameworksAction < Action + def self.run(params) + + Actions.sh("carthage build --no-skip-current") + Actions.sh("carthage archive #{params[:framework_name]}") + + path = "#{params[:framework_name]}.framework.zip" + + Actions.lane_context[SharedValues::CARTHAGE_FRAMEWORK] = path + + Helper.log.info "Carthage generated #{params[:framework_name]}.framework" + + return path + end + + ##################################################### + # @!group Documentation + ##################################################### + + def self.description + "Create a Carthage Framework for your project" + end + + def self.available_options + [ + FastlaneCore::ConfigItem.new(key: :framework_name, + env_name: "CARTHAGE_FRAMEWORK_NAME", # The name of the environment variable + description: "The name of the framework for Carthage to generate", # a short description of this parameter + is_string:true) + ] + end + + def self.output + [ + ['CARTHAGE_FRAMEWORK', 'The path to the generate Carthage framework'] + ] + end + + def self.return_value + "The path to the zipped framework" + end + + def self.authors + ["kcharwood"] + end + + def self.is_supported?(platform) + return true + end + end + end +end diff --git a/its/plugin/projects/AFNetworking/fastlane/actions/af_create_github_release.rb b/its/plugin/projects/AFNetworking/fastlane/actions/af_create_github_release.rb new file mode 100644 index 00000000..14477dd4 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/actions/af_create_github_release.rb @@ -0,0 +1,156 @@ +module Fastlane + module Actions + module SharedValues + GITHUB_RELEASE_ID = :GITHUB_RELEASE_ID + GITHUB_RELEASE_HTML_URL = :GITHUB_RELEASE_HTML_URL + GITHUB_RELEASE_UPLOAD_URL_TEMPLATE = :GITHUB_RELEASE_UPLOAD_URL_TEMPLATE + end + + # To share this integration with the other fastlane users: + # - Fork https://github.com/KrauseFx/fastlane + # - Clone the forked repository + # - Move this integration into lib/fastlane/actions + # - Commit, push and submit the pull request + + class AfCreateGithubReleaseAction < Action + def self.run(params) + require 'net/http' + require 'net/https' + require 'json' + require 'base64' + + begin + uri = URI("https://api.github.com/repos/#{params[:owner]}/#{params[:repository]}/releases") + + # Create client + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_PEER + + dict = Hash.new + dict["draft"] = params[:draft] + dict["prerelease"] = params[:prerelease] + dict["body"] = params[:body] if params[:body] + dict["tag_name"] = params[:tag_name] if params[:tag_name] + dict["name"] = params[:name] if params[:name] + body = JSON.dump(dict) + + # Create Request + req = Net::HTTP::Post.new(uri) + # Add headers + req.add_field "Content-Type", "application/json" + # Add headers + api_token = params[:api_token] + req.add_field "Authorization", "Basic #{Base64.strict_encode64(api_token)}" + # Add headers + req.add_field "Accept", "application/vnd.github.v3+json" + # Set header and body + req.add_field "Content-Type", "application/json" + req.body = body + + # Fetch Request + res = http.request(req) + rescue StandardError => e + Helper.log.info "HTTP Request failed (#{e.message})".red + end + + case res.code.to_i + when 201 + json = JSON.parse(res.body) + Helper.log.info "Github Release Created (#{json["id"]})".green + Helper.log.info "#{json["html_url"]}".green + + Actions.lane_context[SharedValues::GITHUB_RELEASE_ID] = json["id"] + Actions.lane_context[SharedValues::GITHUB_RELEASE_HTML_URL] = json["html_url"] + Actions.lane_context[SharedValues::GITHUB_RELEASE_UPLOAD_URL_TEMPLATE] = json["upload_url"] + return json + when 400..499 + json = JSON.parse(res.body) + raise "Error Creating Github Release (#{res.code}): #{json}".red + else + Helper.log.info "Status Code: #{res.code} Body: #{res.body}" + raise "Error Creating Github Release".red + end + end + + ##################################################### + # @!group Documentation + ##################################################### + + def self.description + "Create a Github Release" + end + + def self.available_options + [ + FastlaneCore::ConfigItem.new(key: :owner, + env_name: "GITHUB_OWNER", + description: "The Github Owner", + is_string:true, + optional:false), + FastlaneCore::ConfigItem.new(key: :repository, + env_name: "GITHUB_REPOSITORY", + description: "The Github Repository", + is_string:true, + optional:false), + FastlaneCore::ConfigItem.new(key: :api_token, + env_name: "GITHUB_API_TOKEN", + description: "Personal API Token for GitHub - generate one at https://github.com/settings/tokens", + is_string: true, + optional: false), + FastlaneCore::ConfigItem.new(key: :tag_name, + env_name: "GITHUB_RELEASE_TAG_NAME", + description: "Pass in the tag name", + is_string: true, + optional: false), + FastlaneCore::ConfigItem.new(key: :target_commitish, + env_name: "GITHUB_TARGET_COMMITISH", + description: "Specifies the commitish value that determines where the Git tag is created from. Can be any branch or commit SHA. Unused if the Git tag already exists", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :name, + env_name: "GITHUB_RELEASE_NAME", + description: "The name of the release", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :body, + env_name: "GITHUB_RELEASE_BODY", + description: "Text describing the contents of the tag", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :draft, + env_name: "GITHUB_RELEASE_DRAFT", + description: "true to create a draft (unpublished) release, false to create a published one", + is_string: false, + default_value: false), + FastlaneCore::ConfigItem.new(key: :prerelease, + env_name: "GITHUB_RELEASE_PRERELEASE", + description: "true to identify the release as a prerelease. false to identify the release as a full release", + is_string: false, + default_value: false), + + ] + end + + def self.output + [ + ['GITHUB_RELEASE_ID', 'The Github Release ID'], + ['GITHUB_RELEASE_HTML_URL', 'The Github Release URL'], + ['GITHUB_RELEASE_UPLOAD_URL_TEMPLATE', 'The Github Release Upload URL'] + ] + end + + def self.return_value + "The Hash representing the API response" + end + + def self.authors + ["kcharwood"] + end + + def self.is_supported?(platform) + return true + end + end + end +end diff --git a/its/plugin/projects/AFNetworking/fastlane/actions/af_edit_github_release.rb b/its/plugin/projects/AFNetworking/fastlane/actions/af_edit_github_release.rb new file mode 100644 index 00000000..731b776d --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/actions/af_edit_github_release.rb @@ -0,0 +1,161 @@ +module Fastlane + module Actions + module SharedValues + GITHUB_RELEASE_ID = :GITHUB_RELEASE_ID + GITHUB_RELEASE_HTML_URL = :GITHUB_RELEASE_HTML_URL + GITHUB_RELEASE_UPLOAD_URL_TEMPLATE = :GITHUB_RELEASE_UPLOAD_URL_TEMPLATE + end + + # To share this integration with the other fastlane users: + # - Fork https://github.com/KrauseFx/fastlane + # - Clone the forked repository + # - Move this integration into lib/fastlane/actions + # - Commit, push and submit the pull request + + class AfEditGithubReleaseAction < Action + def self.run(params) + + require 'net/http' + require 'net/https' + require 'json' + require 'base64' + + begin + uri = URI("https://api.github.com/repos/#{params[:owner]}/#{params[:repository]}/releases/#{params[:id]}") + + # Create client + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_PEER + + dict = Hash.new + dict["draft"] = params[:draft] if params[:draft] != nil + dict["prerelease"] = params[:prerelease] if params[:prerelease] != nil + dict["body"] = params[:body] if params[:body] + dict["tag_name"] = params[:tag_name] if params[:tag_name] + dict["name"] = params[:name] if params[:name] + body = JSON.dump(dict) + + # Create Request + req = Net::HTTP::Patch.new(uri) + # Add headers + req.add_field "Content-Type", "application/json" + # Add headers + api_token = params[:api_token] + req.add_field "Authorization", "Basic #{Base64.strict_encode64(api_token)}" + # Add headers + req.add_field "Accept", "application/vnd.github.v3+json" + # Set header and body + req.add_field "Content-Type", "application/json" + req.body = body + + # Fetch Request + res = http.request(req) + rescue StandardError => e + Helper.log.info "HTTP Request failed (#{e.message})".red + end + + case res.code.to_i + when 200 + json = JSON.parse(res.body) + Helper.log.info "Github Release updated".green + + Actions.lane_context[SharedValues::GITHUB_RELEASE_ID] = json["id"] + Actions.lane_context[SharedValues::GITHUB_RELEASE_HTML_URL] = json["html_url"] + Actions.lane_context[SharedValues::GITHUB_RELEASE_UPLOAD_URL_TEMPLATE] = json["upload_url"] + return json + when 400..499 + json = JSON.parse(res.body) + raise "Error Creating Github Release (#{res.code}): #{json["message"]}".red + else + Helper.log.info "Status Code: #{res.code} Body: #{res.body}" + raise "Error Creating Github Release".red + end + end + + ##################################################### + # @!group Documentation + ##################################################### + + def self.description + "Edit a Github Release" + end + + def self.available_options + [ + FastlaneCore::ConfigItem.new(key: :owner, + env_name: "GITHUB_OWNER", + description: "The Github Owner", + is_string:true, + optional:false), + FastlaneCore::ConfigItem.new(key: :repository, + env_name: "GITHUB_REPOSITORY", + description: "The Github Repository", + is_string:true, + optional:false), + FastlaneCore::ConfigItem.new(key: :id, + env_name: "GITHUB_RELEASE_ID", + description: "The Github Release ID", + is_string:true, + default_value:Actions.lane_context[SharedValues::GITHUB_RELEASE_ID]), + FastlaneCore::ConfigItem.new(key: :api_token, + env_name: "GITHUB_API_TOKEN", + description: "Personal API Token for GitHub - generate one at https://github.com/settings/tokens", + is_string: true, + optional: false), + FastlaneCore::ConfigItem.new(key: :tag_name, + env_name: "GITHUB_RELEASE_TAG_NAME", + description: "Pass in the tag name", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :target_commitish, + env_name: "GITHUB_TARGET_COMMITISH", + description: "Specifies the commitish value that determines where the Git tag is created from. Can be any branch or commit SHA. Unused if the Git tag already exists", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :name, + env_name: "GITHUB_RELEASE_NAME", + description: "The name of the release", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :body, + env_name: "GITHUB_RELEASE_BODY", + description: "Text describing the contents of the tag", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :draft, + env_name: "GITHUB_RELEASE_DRAFT", + description: "true to create a draft (unpublished) release, false to create a published one", + is_string: false, + optional: true), + FastlaneCore::ConfigItem.new(key: :prerelease, + env_name: "GITHUB_RELEASE_PRERELEASE", + description: "true to identify the release as a prerelease. false to identify the release as a full release", + is_string: false, + optional: true), + + ] + end + + def self.output + [ + ['GITHUB_RELEASE_ID', 'The Github Release ID'], + ['GITHUB_RELEASE_HTML_URL', 'The Github Release URL'], + ['GITHUB_RELEASE_UPLOAD_URL_TEMPLATE', 'The Github Release Upload URL'] + ] + end + + def self.return_value + "The Hash representing the API response" + end + + def self.authors + ["kcharwood"] + end + + def self.is_supported?(platform) + return true + end + end + end +end diff --git a/its/plugin/projects/AFNetworking/fastlane/actions/af_generate_github_milestone_changelog.rb b/its/plugin/projects/AFNetworking/fastlane/actions/af_generate_github_milestone_changelog.rb new file mode 100644 index 00000000..ca503b60 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/actions/af_generate_github_milestone_changelog.rb @@ -0,0 +1,225 @@ +module Fastlane + module Actions + module SharedValues + GITHUB_MILESTONE_CHANGELOG = :GITHUB_MILESTONE_CHANGELOG + end + + # To share this integration with the other fastlane users: + # - Fork https://github.com/KrauseFx/fastlane + # - Clone the forked repository + # - Move this integration into lib/fastlane/actions + # - Commit, push and submit the pull request + + class AfGenerateGithubMilestoneChangelogAction < Action + def self.english_join(array = nil) + return "" if array.nil? or array.length == 0 + return array[0] if array.length == 1 + array[0..-2].join(", ") + " and " + array[-1] + end + + def self.markdown_for_changelog_section (github_owner, github_repository, api_token, section, issues) + changelog = "\n#### #{section}\n" + issues.each do |issue| + authors = getAuthorsForIssue(github_owner,github_repository, api_token, issue) + + changelog << "* #{issue["title"]}\n" + changelog << " * Implemented by #{english_join(authors)} in [##{issue["number"]}](#{issue["html_url"]}).\n" + end + return changelog + end + + def self.getResponseForURL(url, api_token) + uri = URI(url) + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_PEER + + # Create Request + req = Net::HTTP::Get.new(uri) + req.add_field "Authorization", "Basic #{Base64.strict_encode64(api_token)}" if api_token != nil + req.add_field "Accept", "application/vnd.github.v3+json" + begin + httpResponse = http.request(req) + begin + case httpResponse.code.to_i + when 200..299 + response = JSON.parse(httpResponse.body) + when 400..499 + response = JSON.parse(httpResponse.body) + raise "Error (#{response.code}): #{response["message"]}".red + else + Helper.log.info "Status Code: #{httpResponse.code} Body: #{httpResponse.body}" + raise "Error with request".red + end + + rescue + + end + rescue => ex + raise "Error fetching remote file: #{ex}".red + end + return response + end + + def self.getIssuesForMilestone (github_owner, github_repository, api_token, milestone) + url = "https://api.github.com/search/issues?q=repo:#{github_owner}/#{github_repository}+milestone:#{milestone}+state:closed" + + response = getResponseForURL(url, api_token) + return response["items"] + end + + def self.getAuthorsForIssue(github_owner, github_repository, api_token, issue) + if issue.has_key?("pull_request") + url = "https://api.github.com/repos/#{github_owner}/#{github_repository}/pulls/#{issue["number"]}/commits" + + commits = getResponseForURL(url, api_token) + + authors = Array.new + commits.each do |commit| + author = commit["commit"]["author"] + if authors.include?(author["name"]) == false + authors << author["name"] + end + end + return authors + else + return [issue["user"]["login"]] + end + end + + + def self.run(params) + require 'net/http' + require 'fileutils' + + issues = getIssuesForMilestone(params[:github_owner], params[:github_repository], params[:api_token], params[:milestone]) + + if issues.count == 0 && params[:allow_empty_changelog] == false + raise "No closed issues found for #{params[:milestone]} in #{params[:github_owner]}/#{params[:github_repository]}".red + end + + labels = [params[:added_label_name], params[:updated_label_name], params[:changed_label_name], params[:fixed_label_name], params[:removed_label_name]] + sections = Array.new + labels.each do |label_name| + subissues = issues.select {|issue| issue["labels"].any? {|label| label["name"].downcase == label_name.downcase}} + if subissues.count > 0 + sections << {section: label_name, issues: subissues} + issues = issues - subissues + end + end + + if issues.count > 0 + prompt_text = "There are #{issues.count} issue(s) that have not been properly categorized in this milestone. Do you want to continue?" + if Fastlane::Actions::PromptAction.run(text: prompt_text, boolean: true, ci_input: "y") + if sections.count > 0 + section_label = "Additional Changes" + else + section_label = "Changes" + end + sections << {section: section_label, issues: issues} + else + raise "Aborting since issues have not been categorized." + end + + end + + + date = DateTime.now + result = Hash.new + result[:title] = "\n\n## [#{params[:milestone]}](https://github.com/#{params[:github_owner]}/#{params[:github_repository]}/releases/tag/#{params[:milestone]}) (#{date.strftime("%m/%d/%Y")})" + result[:header] = "\nReleased on #{date.strftime("%A, %B %d, %Y")}. All issues associated with this milestone can be found using this [filter](https://github.com/#{params[:github_owner]}/#{params[:github_repository]}/issues?q=milestone%3A#{params[:milestone]}+is%3Aclosed)." + + result[:changelog] = "\n" + sections.each do |section| + result[:changelog] << markdown_for_changelog_section(params[:github_owner], params[:github_repository], params[:api_token], section[:section], section[:issues]) + end + Actions.lane_context[SharedValues::GITHUB_MILESTONE_CHANGELOG] = result + + return result + end + + ##################################################### + # @!group Documentation + ##################################################### + + def self.description + "Generate a markdown formatted change log for a specific milestone in a Github repository" + end + + def self.details + + "You can use this action to do cool things..." + end + + def self.available_options + [ + FastlaneCore::ConfigItem.new(key: :github_owner, + env_name: "GITHUB_OWNER", + description: "Github Owner for the repository", + is_string: true), + FastlaneCore::ConfigItem.new(key: :github_repository, + env_name: "GITHUB_REPOSITORY", + description: "Github Repository containing the milestone", + is_string: true), + FastlaneCore::ConfigItem.new(key: :api_token, + env_name: "GITHUB_API_TOKEN", + description: "Personal API Token for GitHub - generate one at https://github.com/settings/tokens", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :milestone, + env_name: "FL_GENERATE_GITHUB_MILESTONE_CHANGELOG_MILESTONE", + description: "Milestone to generate changelog notes", + is_string: true), + FastlaneCore::ConfigItem.new(key: :added_label_name, + env_name: "FL_GENERATE_GITHUB_MILESTONE_CHANGELOG_ADDED_LABEL_NAME", + description: "Github label name for all issues added during this milestone", + is_string: true, + default_value: "Added"), + FastlaneCore::ConfigItem.new(key: :updated_label_name, + env_name: "FL_GENERATE_GITHUB_MILESTONE_CHANGELOG_UPDATED_LABEL_NAME", + description: "Github label name for all issues updated during this milestone", + is_string: true, + default_value: "Updated"), + FastlaneCore::ConfigItem.new(key: :changed_label_name, + env_name: "FL_GENERATE_GITHUB_MILESTONE_CHANGELOG_CHANGED_LABEL_NAME", + description: "Github label name for all issues changed during this milestone", + is_string: true, + default_value: "Changed"), + FastlaneCore::ConfigItem.new(key: :fixed_label_name, + env_name: "FL_GENERATE_GITHUB_MILESTONE_CHANGELOG_FIXED_LABEL_NAME", + description: "Github label name for all issues fixed during this milestone", + is_string: true, + default_value: "Fixed"), + FastlaneCore::ConfigItem.new(key: :removed_label_name, + env_name: "FL_GENERATE_GITHUB_MILESTONE_CHANGELOG_REMOVED_LABEL_NAME", + description: "Github label name for all removed added during this milestone", + is_string: true, + default_value: "Removed"), + FastlaneCore::ConfigItem.new(key: :allow_empty_changelog, + env_name: "FL_GENERATE_GITHUB_MILESTONE_CHANGELOG_ALLOW_EMPTY", + description: "Flag which allows an empty changelog. If false, exception is raised if no issues are found", + is_string: false, + default_value: true) + ] + end + + def self.output + [ + ['GITHUB_MILESTONE_CHANGELOG', 'A hash containing a well formatted :header, and the :changelog itself'] + ] + end + + def self.return_value + "Returns a hash containing a well formatted :title, :header, and the :changelog itself, both in markdown" + end + + def self.authors + ["kcharwood"] + end + + def self.is_supported?(platform) + return true + end + end + end +end diff --git a/its/plugin/projects/AFNetworking/fastlane/actions/af_get_github_milestone.rb b/its/plugin/projects/AFNetworking/fastlane/actions/af_get_github_milestone.rb new file mode 100644 index 00000000..9ed273f4 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/actions/af_get_github_milestone.rb @@ -0,0 +1,129 @@ +module Fastlane + module Actions + module SharedValues + GITHUB_MILESTONE_NUMBER = :GITHUB_MILESTONE_NUMBER + end + + # To share this integration with the other fastlane users: + # - Fork https://github.com/KrauseFx/fastlane + # - Clone the forked repository + # - Move this integration into lib/fastlane/actions + # - Commit, push and submit the pull request + + class AfGetGithubMilestoneAction < Action + def self.run(params) + require 'net/http' + require 'net/https' + require 'json' + require 'base64' + + begin + uri = URI("https://api.github.com/repos/#{params[:owner]}/#{params[:repository]}/milestones") + + # Create client + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_PEER + + # Create Request + req = Net::HTTP::Get.new(uri) + # Add headers + if params[:api_token] + api_token = params[:api_token] + req.add_field "Authorization", "Basic #{Base64.strict_encode64(api_token)}" + end + req.add_field "Accept", "application/vnd.github.v3+json" + + # Fetch Request + res = http.request(req) + rescue StandardError => e + Helper.log.info "HTTP Request failed (#{e.message})".red + end + + case res.code.to_i + when 200 + milestones = JSON.parse(res.body) + + milestone = milestones.select {|milestone| milestone["title"] == params[:title]}.first + + if milestone == nil + raise "No milestone found matching #{params[:title]}".red + end + + Helper.log.info "Milestone #{params[:title]}: #{milestone["url"]}".green + + if params[:verify_for_release] == true + raise "Milestone #{params[:title]} is already closed".red unless milestone["state"] == "open" + raise "Milestone #{params[:title]} still has open #{milestone["open_issues"]} issue(s)".red unless milestone["open_issues"] == 0 + raise "Milestone #{params[:title]} has no closed issues".red unless milestone["closed_issues"] > 0 + Helper.log.info "Milestone #{params[:title]} is ready for release!".green + end + + Actions.lane_context[SharedValues::GITHUB_MILESTONE_NUMBER] = milestone["number"] + return milestone + when 400..499 + json = JSON.parse(res.body) + raise "Error Retrieving Github Milestone (#{res.code}): #{json["message"]}".red + else + Helper.log.info "Status Code: #{res.code} Body: #{res.body}" + raise "Retrieving Github Milestone".red + end + + end + + ##################################################### + # @!group Documentation + ##################################################### + + def self.description + "Get a Github Milestone, and optional verify its ready for release" + end + + def self.available_options + [ + FastlaneCore::ConfigItem.new(key: :owner, + env_name: "GITHUB_OWNER", + description: "The Github Owner", + is_string:true, + optional:false), + FastlaneCore::ConfigItem.new(key: :repository, + env_name: "GITHUB_REPOSITORY", + description: "The Github Repository", + is_string:true, + optional:false), + FastlaneCore::ConfigItem.new(key: :api_token, + env_name: "GITHUB_API_TOKEN", + description: "Personal API Token for GitHub - generate one at https://github.com/settings/tokens", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :title, + description: "The milestone title, typically the same as the tag", + is_string: true, + optional: false), + FastlaneCore::ConfigItem.new(key: :verify_for_release, + description: "Verifies there are zero open issues, at least one closed issue, and is not closed", + is_string: false, + default_value:false) + ] + end + + def self.output + [ + ['GITHUB_MILESTONE_NUMBER', 'The milestone number'] + ] + end + + def self.return_value + "A Hash representing the API response" + end + + def self.authors + ["kcharwood"] + end + + def self.is_supported?(platform) + return true + end + end + end +end diff --git a/its/plugin/projects/AFNetworking/fastlane/actions/af_insert_text_into_file.rb b/its/plugin/projects/AFNetworking/fastlane/actions/af_insert_text_into_file.rb new file mode 100644 index 00000000..a308ff0d --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/actions/af_insert_text_into_file.rb @@ -0,0 +1,80 @@ +module Fastlane + module Actions + + # To share this integration with the other fastlane users: + # - Fork https://github.com/KrauseFx/fastlane + # - Clone the forked repository + # - Move this integration into lib/fastlane/actions + # - Commit, push and submit the pull request + class AfInsertTextIntoFileAction < Action + def self.replace(filepath, regexp, *args, &block) + content = File.read(filepath).gsub(regexp, *args, &block) + File.open(filepath, 'wb') { |file| file.write(content) } + end + + def self.run(params) + if params[:insert_delimiter] + replace(params[:file_path], /^#{params[:insert_delimiter]}/mi) do |match| + "#{match} #{params[:text]}" + end + elsif params[:insert_at_bottom] == true + open(params[:file_path], 'a') { |f| f.puts "#{params[:text]}" } + else + file = IO.read(params[:file_path]) + open(params[:file_path], 'w') { |f| f << params[:text] << file} + end + + Helper.log.info "#{params[:file_path]} has been updated".green + end + + ##################################################### + # @!group Documentation + ##################################################### + + def self.description + "Insert text into a file" + end + + def self.details + "Insert text at the top, bottom, or after a delimiter in a file" + end + + def self.available_options + [ + FastlaneCore::ConfigItem.new(key: :file_path, + description: "Path for the file", + is_string: true, + verify_block: proc do |value| + raise "Couldn't find file at path '#{value}'".red unless File.exist?(value) + end), + FastlaneCore::ConfigItem.new(key: :text, + description: "The text to insert", + is_string: true), + FastlaneCore::ConfigItem.new(key: :insert_delimiter, + description: "The delimiter indicating where to insert the text in the file", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :insert_at_bottom, + description: "If no 'insert_delimiter' is provided, the text will be appended to the bottom +of the file if this value is true, or to the top if this value is false", + is_string: false, + default_value: true), + ] + end + + def self.output + end + + def self.return_value + end + + def self.authors + ["kcharwood"] + end + + def self.is_supported?(platform) + return true + end + end + end +end diff --git a/its/plugin/projects/AFNetworking/fastlane/actions/af_pod_spec_lint.rb b/its/plugin/projects/AFNetworking/fastlane/actions/af_pod_spec_lint.rb new file mode 100644 index 00000000..7beef8a0 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/actions/af_pod_spec_lint.rb @@ -0,0 +1,90 @@ +module Fastlane + module Actions + + # To share this integration with the other fastlane users: + # - Fork https://github.com/KrauseFx/fastlane + # - Clone the forked repository + # - Move this integration into lib/fastlane/actions + # - Commit, push and submit the pull request + + class AfPodSpecLintAction < Action + def self.run(params) + commands = ["pod", "spec", "lint"] + if params[:path] + commands << params[:path] + end + + if params[:quick] + commands << "--quick" + end + + if params[:allow_warnings] + commands << "--allow-warnings" + end + + if params[:no_subspecs] + commands << "--no-subspecs" + end + + if params[:subspec] + commands << "--subspec=#{params[:subspec]}" + end + + result = Actions.sh("#{commands.join(" ")}") + Helper.log.info "Successfully linted podspec".green + return result + end + + ##################################################### + # @!group Documentation + ##################################################### + + def self.description + "Lint a pod spec" + end + + def self.available_options + [ + FastlaneCore::ConfigItem.new(key: :path, + description: "The Podspec you want to lint", + optional: true, + verify_block: proc do |value| + raise "Couldn't find file at path '#{value}'".red unless File.exist?(value) + raise "File must be a `.podspec`".red unless value.end_with?(".podspec") + end), + FastlaneCore::ConfigItem.new(key: :quick, + description: "Lint skips checks that would require to download and build the spec", + optional: true, + is_string:false), + FastlaneCore::ConfigItem.new(key: :allow_warnings, + description: "Lint validates even if warnings are present", + optional: true, + is_string:false), + FastlaneCore::ConfigItem.new(key: :no_subspecs, + description: "Lint skips validation of subspecs", + optional: true, + is_string:false), + FastlaneCore::ConfigItem.new(key: :subspec, + description: "Lint validates only the given subspec", + optional: true, + is_string: true), + ] + end + + def self.output + end + + def self.return_value + # If you method provides a return value, you can describe here what it does + end + + def self.authors + ["kcharwood"] + end + + def self.is_supported?(platform) + platform != :android + end + end + end +end diff --git a/its/plugin/projects/AFNetworking/fastlane/actions/af_push_git_tags_to_remote.rb b/its/plugin/projects/AFNetworking/fastlane/actions/af_push_git_tags_to_remote.rb new file mode 100644 index 00000000..ed265dde --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/actions/af_push_git_tags_to_remote.rb @@ -0,0 +1,47 @@ +module Fastlane + module Actions + class AfPushGitTagsToRemoteAction < Action + def self.run(params) + commands = ["git", "push"] + + if params[:remote] + commands << "#{params[:remote]}" + end + + commands << "--tags" + + result = Actions.sh("#{commands.join(" ")}") + Helper.log.info "Tags pushed to remote".green + return result + end + + ##################################################### + # @!group Documentation + ##################################################### + + def self.description + "Push local tags to the remote - this will only push tags" + end + + def self.available_options + [ + FastlaneCore::ConfigItem.new(key: :remote, + env_name: "FL_PUSH_GIT_TAGS_REMOTE", + description: "The remote to push tags too", + is_string:true, + optional:true) + ] + end + + def self.author + ['vittoriom'] + end + + def self.is_supported?(platform) + true + end + end + end + end + + \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/actions/af_update_github_milestone.rb b/its/plugin/projects/AFNetworking/fastlane/actions/af_update_github_milestone.rb new file mode 100644 index 00000000..8fa23c76 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/actions/af_update_github_milestone.rb @@ -0,0 +1,138 @@ +module Fastlane + module Actions + module SharedValues + end + + # To share this integration with the other fastlane users: + # - Fork https://github.com/KrauseFx/fastlane + # - Clone the forked repository + # - Move this integration into lib/fastlane/actions + # - Commit, push and submit the pull request + + class AfUpdateGithubMilestoneAction < Action + def self.run(params) + + require 'net/http' + require 'net/https' + require 'json' + require 'base64' + + begin + uri = URI("https://api.github.com/repos/#{params[:owner]}/#{params[:repository]}/milestones/#{params[:number]}") + + # Create client + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_PEER + + dict = Hash.new + dict["title"] = params[:title] if params[:title] + dict["state"] = params[:state] if params[:state] + dict["description"] = params[:description] if params[:description] + dict["due_on"] = params[:due_on] if params[:due_on] + body = JSON.dump(dict) + + # Create Request + req = Net::HTTP::Patch.new(uri) + req.add_field "Content-Type", "application/json" + api_token = params[:api_token] + req.add_field "Authorization", "Basic #{Base64.strict_encode64(api_token)}" + req.add_field "Accept", "application/vnd.github.v3+json" + req.add_field "Content-Type", "application/json" + req.body = body + + # Fetch Request + res = http.request(req) + rescue StandardError => e + Helper.log.info "HTTP Request failed (#{e.message})".red + end + + case res.code.to_i + when 200 + json = JSON.parse(res.body) + Helper.log.info "Github Release updated".green + + Actions.lane_context[SharedValues::GITHUB_RELEASE_ID] = json["id"] + Actions.lane_context[SharedValues::GITHUB_RELEASE_HTML_URL] = json["html_url"] + Actions.lane_context[SharedValues::GITHUB_RELEASE_UPLOAD_URL_TEMPLATE] = json["upload_url"] + return json + when 400..499 + json = JSON.parse(res.body) + raise "Error Creating Github Release (#{res.code}): #{json["message"]}".red + else + Helper.log.info "Status Code: #{res.code} Body: #{res.body}" + raise "Error Creating Github Release".red + end + end + + ##################################################### + # @!group Documentation + ##################################################### + + def self.description + "Edit a Github Milestone" + end + + def self.available_options + [ + FastlaneCore::ConfigItem.new(key: :owner, + env_name: "GITHUB_OWNER", + description: "The Github Owner", + is_string:true, + optional:false), + FastlaneCore::ConfigItem.new(key: :repository, + env_name: "GITHUB_REPOSITORY", + description: "The Github Repository", + is_string:true, + optional:false), + FastlaneCore::ConfigItem.new(key: :number, + env_name: "GITHUB_MILESTONE_NUMBER", + description: "The Github Release ID", + is_string:true, + default_value:Actions.lane_context[SharedValues::GITHUB_MILESTONE_NUMBER]), + FastlaneCore::ConfigItem.new(key: :api_token, + env_name: "GITHUB_API_TOKEN", + description: "Personal API Token for GitHub - generate one at https://github.com/settings/tokens", + is_string: true, + optional: false), + FastlaneCore::ConfigItem.new(key: :title, + env_name: "GITHUB_MILESTONE_TITLE", + description: "The title to update", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :state, + env_name: "GITHUB_MILESTONE_STATE", + description: "The state to update. Can be `open` or `closed`", + is_string: true, + optional: true, + verify_block: proc do |value| + raise "`state` can only be `open` or `closed".red unless value == "open" || value == "closed" + end), + FastlaneCore::ConfigItem.new(key: :description, + env_name: "GITHUB_MILESTONE_DESCRIPTION", + description: "The description of the milestone", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :due_on, + env_name: "GITHUB_MIELSTONE_DUE_DATE", + description: "The milestone due date. This is a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ", + is_string: true, + optional: true), + + ] + end + + def self.return_value + "The Hash representing the API response" + end + + def self.authors + ["kcharwood"] + end + + def self.is_supported?(platform) + return true + end + end + end +end diff --git a/its/plugin/projects/AFNetworking/fastlane/actions/af_upload_asset_for_github_release.rb b/its/plugin/projects/AFNetworking/fastlane/actions/af_upload_asset_for_github_release.rb new file mode 100644 index 00000000..900e3cfe --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/actions/af_upload_asset_for_github_release.rb @@ -0,0 +1,134 @@ +module Fastlane + module Actions + module SharedValues + GITHUB_UPLOAD_ASSET_URL = :GITHUB_UPLOAD_ASSET_URL + end + + # To share this integration with the other fastlane users: + # - Fork https://github.com/KrauseFx/fastlane + # - Clone the forked repository + # - Move this integration into lib/fastlane/actions + # - Commit, push and submit the pull request + + class AfUploadAssetForGithubReleaseAction < Action + def self.run(params) + require 'net/http' + require 'net/https' + require 'json' + require 'base64' + require 'addressable/template' + + begin + name = params[:name] ? params[:name] : File.basename(params[:file_path]) + expanded_url = Addressable::Template.new(params[:upload_url_template]).expand({name: name, label:params[:label]}).to_s + + uri = URI(expanded_url) + + # Create client + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_PEER + + + # Create Request + req = Net::HTTP::Post.new(uri) + # Add headers + req.add_field "Content-Type", params[:content_type] + # Add headers + api_token = params[:api_token] + req.add_field "Authorization", "Basic #{Base64.strict_encode64(api_token)}" + # Add headers + req.add_field "Accept", "application/vnd.github.v3+json" + # Set header and body + req.add_field "Content-Type", "application/json" + req.body = File.read(params[:file_path]) + + # Fetch Request + res = http.request(req) + rescue StandardError => e + Helper.log.info "HTTP Request failed (#{e.message})".red + end + + case res.code.to_i + when 201 + json = JSON.parse(res.body) + Helper.log.info "#{json["name"]} has been uploaded to the release".green + Actions.lane_context[SharedValues::GITHUB_UPLOAD_ASSET_URL] = json["browser_download_url"] + return json + when 400..499 + json = JSON.parse(res.body) + raise "Error Creating Github Release (#{res.code}): #{json}".red + else + Helper.log.info "Status Code: #{res.code} Body: #{res.body}" + raise "Error Creating Github Release".red + end + end + + ##################################################### + # @!group Documentation + ##################################################### + + def self.description + "Upload an asset to a Github Release" + end + + def self.available_options + # Define all options your action supports. + + # Below a few examples + [ + FastlaneCore::ConfigItem.new(key: :api_token, + env_name: "GITHUB_API_TOKEN", + description: "Personal API Token for GitHub - generate one at https://github.com/settings/tokens", + is_string: true, + optional: false), + FastlaneCore::ConfigItem.new(key: :upload_url_template, + env_name: "GITHUB_RELEASE_UPLOAD_URL_TEMPLATE", + description: "The Github Release Upload URL", + is_string:true, + default_value:Actions.lane_context[SharedValues::GITHUB_RELEASE_UPLOAD_URL_TEMPLATE]), + FastlaneCore::ConfigItem.new(key: :file_path, + env_name: "GITHUB_RELEASE_UPLOAD_FILE_PATH", + description: "Path for the file", + is_string: true, + verify_block: proc do |value| + raise "Couldn't find file at path '#{value}'".red unless File.exist?(value) + end), + FastlaneCore::ConfigItem.new(key: :name, + env_name: "GITHUB_RELEASE_UPLOAD_NAME", + description: "Name of the upload asset. Defaults to the base name of 'file_path'}", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :label, + env_name: "GITHUB_RELEASE_UPLOAD_LABEL", + description: "An alternate short description of the asset", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :content_type, + env_name: "GITHUB_RELEASE_UPLOAD_CONTENT_TYPE", + description: "The content type for the upload", + is_string: true, + default_value: "application/zip") + ] + end + + def self.output + [ + ['GITHUB_UPLOAD_ASSET_URL', 'A url for the newly created asset'] + ] + end + + def self.return_value + "The hash representing the API response" + end + + def self.authors + ["kcharwood"] + end + + def self.is_supported?(platform) + return true + end + end + end +end diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/.gitignore b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/.gitignore new file mode 100644 index 00000000..f076e756 --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/.gitignore @@ -0,0 +1,13 @@ +# Generated by CocoaPods +BitriseSampleUnitAndOtherTestsApp.xcworkspace +# Do not commit pods +Pods +# Intermediates +DerivedData +*.build +build +.sonar +compile_commands.json +# Fastlane reports +fastlane/report.xml +fastlane/test_output/ diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp.xcodeproj/project.pbxproj b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp.xcodeproj/project.pbxproj new file mode 100644 index 00000000..846e60f9 --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp.xcodeproj/project.pbxproj @@ -0,0 +1,529 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 034A115CFB09157FF7774084 /* libPods-BitriseSampleUnitAndOtherTestsAppTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 4A1C2291B3F12AB7FE98610D /* libPods-BitriseSampleUnitAndOtherTestsAppTests.a */; }; + BA0609DC1AA610E100F24A40 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = BA0609DB1AA610E100F24A40 /* main.m */; }; + BA0609DF1AA610E100F24A40 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = BA0609DE1AA610E100F24A40 /* AppDelegate.m */; }; + BA0609E21AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsApp.xcdatamodeld in Sources */ = {isa = PBXBuildFile; fileRef = BA0609E01AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsApp.xcdatamodeld */; }; + BA0609E51AA610E100F24A40 /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = BA0609E41AA610E100F24A40 /* ViewController.m */; }; + BA0609E81AA610E100F24A40 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = BA0609E61AA610E100F24A40 /* Main.storyboard */; }; + BA0609EA1AA610E100F24A40 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = BA0609E91AA610E100F24A40 /* Images.xcassets */; }; + BA0609ED1AA610E100F24A40 /* LaunchScreen.xib in Resources */ = {isa = PBXBuildFile; fileRef = BA0609EB1AA610E100F24A40 /* LaunchScreen.xib */; }; + BA0609F91AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsAppTests.m in Sources */ = {isa = PBXBuildFile; fileRef = BA0609F81AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsAppTests.m */; }; + BA7CF5CA1AA61A7A00DEB100 /* KiwiSampleSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = BA7CF5C91AA61A7A00DEB100 /* KiwiSampleSpec.m */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + BA0609F31AA610E100F24A40 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BA0609CE1AA610E100F24A40 /* Project object */; + proxyType = 1; + remoteGlobalIDString = BA0609D51AA610E100F24A40; + remoteInfo = BitriseSampleUnitAndOtherTestsApp; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 4A1C2291B3F12AB7FE98610D /* libPods-BitriseSampleUnitAndOtherTestsAppTests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-BitriseSampleUnitAndOtherTestsAppTests.a"; sourceTree = BUILT_PRODUCTS_DIR; }; + 61199DC195E180BBB3AA23C7 /* Pods-BitriseSampleUnitAndOtherTestsAppTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-BitriseSampleUnitAndOtherTestsAppTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-BitriseSampleUnitAndOtherTestsAppTests/Pods-BitriseSampleUnitAndOtherTestsAppTests.release.xcconfig"; sourceTree = ""; }; + 7E1D6E3986AFC399154EA64A /* Pods-BitriseSampleUnitAndOtherTestsAppTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-BitriseSampleUnitAndOtherTestsAppTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-BitriseSampleUnitAndOtherTestsAppTests/Pods-BitriseSampleUnitAndOtherTestsAppTests.debug.xcconfig"; sourceTree = ""; }; + BA0609D61AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = BitriseSampleUnitAndOtherTestsApp.app; sourceTree = BUILT_PRODUCTS_DIR; }; + BA0609DA1AA610E100F24A40 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + BA0609DB1AA610E100F24A40 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; + BA0609DD1AA610E100F24A40 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; + BA0609DE1AA610E100F24A40 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; + BA0609E11AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsApp.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = BitriseSampleUnitAndOtherTestsApp.xcdatamodel; sourceTree = ""; }; + BA0609E31AA610E100F24A40 /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = ""; }; + BA0609E41AA610E100F24A40 /* ViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = ""; }; + BA0609E71AA610E100F24A40 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + BA0609E91AA610E100F24A40 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = ""; }; + BA0609EC1AA610E100F24A40 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/LaunchScreen.xib; sourceTree = ""; }; + BA0609F21AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsAppTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = BitriseSampleUnitAndOtherTestsAppTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + BA0609F71AA610E100F24A40 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + BA0609F81AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsAppTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = BitriseSampleUnitAndOtherTestsAppTests.m; sourceTree = ""; }; + BA7CF5C91AA61A7A00DEB100 /* KiwiSampleSpec.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = KiwiSampleSpec.m; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + BA0609D31AA610E100F24A40 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BA0609EF1AA610E100F24A40 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 034A115CFB09157FF7774084 /* libPods-BitriseSampleUnitAndOtherTestsAppTests.a in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 41062A375877A3BBAFC6FC09 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 4A1C2291B3F12AB7FE98610D /* libPods-BitriseSampleUnitAndOtherTestsAppTests.a */, + ); + name = Frameworks; + sourceTree = ""; + }; + 585C9977CABCF795A39E691A /* Pods */ = { + isa = PBXGroup; + children = ( + 7E1D6E3986AFC399154EA64A /* Pods-BitriseSampleUnitAndOtherTestsAppTests.debug.xcconfig */, + 61199DC195E180BBB3AA23C7 /* Pods-BitriseSampleUnitAndOtherTestsAppTests.release.xcconfig */, + ); + name = Pods; + sourceTree = ""; + }; + BA0609CD1AA610E000F24A40 = { + isa = PBXGroup; + children = ( + BA0609D81AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsApp */, + BA0609F51AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsAppTests */, + BA0609D71AA610E100F24A40 /* Products */, + 585C9977CABCF795A39E691A /* Pods */, + 41062A375877A3BBAFC6FC09 /* Frameworks */, + ); + sourceTree = ""; + }; + BA0609D71AA610E100F24A40 /* Products */ = { + isa = PBXGroup; + children = ( + BA0609D61AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsApp.app */, + BA0609F21AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsAppTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + BA0609D81AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsApp */ = { + isa = PBXGroup; + children = ( + BA0609DD1AA610E100F24A40 /* AppDelegate.h */, + BA0609DE1AA610E100F24A40 /* AppDelegate.m */, + BA0609E31AA610E100F24A40 /* ViewController.h */, + BA0609E41AA610E100F24A40 /* ViewController.m */, + BA0609E61AA610E100F24A40 /* Main.storyboard */, + BA0609E91AA610E100F24A40 /* Images.xcassets */, + BA0609EB1AA610E100F24A40 /* LaunchScreen.xib */, + BA0609E01AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsApp.xcdatamodeld */, + BA0609D91AA610E100F24A40 /* Supporting Files */, + ); + path = BitriseSampleUnitAndOtherTestsApp; + sourceTree = ""; + }; + BA0609D91AA610E100F24A40 /* Supporting Files */ = { + isa = PBXGroup; + children = ( + BA0609DA1AA610E100F24A40 /* Info.plist */, + BA0609DB1AA610E100F24A40 /* main.m */, + ); + name = "Supporting Files"; + sourceTree = ""; + }; + BA0609F51AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsAppTests */ = { + isa = PBXGroup; + children = ( + BA7CF5C91AA61A7A00DEB100 /* KiwiSampleSpec.m */, + BA0609F81AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsAppTests.m */, + BA0609F61AA610E100F24A40 /* Supporting Files */, + ); + path = BitriseSampleUnitAndOtherTestsAppTests; + sourceTree = ""; + }; + BA0609F61AA610E100F24A40 /* Supporting Files */ = { + isa = PBXGroup; + children = ( + BA0609F71AA610E100F24A40 /* Info.plist */, + ); + name = "Supporting Files"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + BA0609D51AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsApp */ = { + isa = PBXNativeTarget; + buildConfigurationList = BA0609FC1AA610E100F24A40 /* Build configuration list for PBXNativeTarget "BitriseSampleUnitAndOtherTestsApp" */; + buildPhases = ( + BA0609D21AA610E100F24A40 /* Sources */, + BA0609D31AA610E100F24A40 /* Frameworks */, + BA0609D41AA610E100F24A40 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = BitriseSampleUnitAndOtherTestsApp; + productName = BitriseSampleUnitAndOtherTestsApp; + productReference = BA0609D61AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsApp.app */; + productType = "com.apple.product-type.application"; + }; + BA0609F11AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsAppTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = BA0609FF1AA610E100F24A40 /* Build configuration list for PBXNativeTarget "BitriseSampleUnitAndOtherTestsAppTests" */; + buildPhases = ( + 20F1B93E6202C972E5B4404D /* Check Pods Manifest.lock */, + BA0609EE1AA610E100F24A40 /* Sources */, + BA0609EF1AA610E100F24A40 /* Frameworks */, + BA0609F01AA610E100F24A40 /* Resources */, + 2DDCD1A2A0EAD8F03EFB5548 /* Copy Pods Resources */, + B8F3940202BFA0A79732360A /* Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + BA0609F41AA610E100F24A40 /* PBXTargetDependency */, + ); + name = BitriseSampleUnitAndOtherTestsAppTests; + productName = BitriseSampleUnitAndOtherTestsAppTests; + productReference = BA0609F21AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsAppTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + BA0609CE1AA610E100F24A40 /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 0610; + ORGANIZATIONNAME = Bitrise; + TargetAttributes = { + BA0609D51AA610E100F24A40 = { + CreatedOnToolsVersion = 6.1.1; + }; + BA0609F11AA610E100F24A40 = { + CreatedOnToolsVersion = 6.1.1; + TestTargetID = BA0609D51AA610E100F24A40; + }; + }; + }; + buildConfigurationList = BA0609D11AA610E100F24A40 /* Build configuration list for PBXProject "BitriseSampleUnitAndOtherTestsApp" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = BA0609CD1AA610E000F24A40; + productRefGroup = BA0609D71AA610E100F24A40 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + BA0609D51AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsApp */, + BA0609F11AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsAppTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + BA0609D41AA610E100F24A40 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + BA0609E81AA610E100F24A40 /* Main.storyboard in Resources */, + BA0609ED1AA610E100F24A40 /* LaunchScreen.xib in Resources */, + BA0609EA1AA610E100F24A40 /* Images.xcassets in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BA0609F01AA610E100F24A40 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 20F1B93E6202C972E5B4404D /* Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; + 2DDCD1A2A0EAD8F03EFB5548 /* Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-BitriseSampleUnitAndOtherTestsAppTests/Pods-BitriseSampleUnitAndOtherTestsAppTests-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; + B8F3940202BFA0A79732360A /* Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-BitriseSampleUnitAndOtherTestsAppTests/Pods-BitriseSampleUnitAndOtherTestsAppTests-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + BA0609D21AA610E100F24A40 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + BA0609DF1AA610E100F24A40 /* AppDelegate.m in Sources */, + BA0609E21AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsApp.xcdatamodeld in Sources */, + BA0609E51AA610E100F24A40 /* ViewController.m in Sources */, + BA0609DC1AA610E100F24A40 /* main.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BA0609EE1AA610E100F24A40 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + BA7CF5CA1AA61A7A00DEB100 /* KiwiSampleSpec.m in Sources */, + BA0609F91AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsAppTests.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + BA0609F41AA610E100F24A40 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = BA0609D51AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsApp */; + targetProxy = BA0609F31AA610E100F24A40 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + BA0609E61AA610E100F24A40 /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + BA0609E71AA610E100F24A40 /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + BA0609EB1AA610E100F24A40 /* LaunchScreen.xib */ = { + isa = PBXVariantGroup; + children = ( + BA0609EC1AA610E100F24A40 /* Base */, + ); + name = LaunchScreen.xib; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + BA0609FA1AA610E100F24A40 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.1; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + BA0609FB1AA610E100F24A40 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = YES; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.1; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + BA0609FD1AA610E100F24A40 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + INFOPLIST_FILE = BitriseSampleUnitAndOtherTestsApp/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + BA0609FE1AA610E100F24A40 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + INFOPLIST_FILE = BitriseSampleUnitAndOtherTestsApp/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; + BA060A001AA610E100F24A40 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7E1D6E3986AFC399154EA64A /* Pods-BitriseSampleUnitAndOtherTestsAppTests.debug.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + FRAMEWORK_SEARCH_PATHS = ( + "$(SDKROOT)/Developer/Library/Frameworks", + "$(inherited)", + ); + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + INFOPLIST_FILE = BitriseSampleUnitAndOtherTestsAppTests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_NAME = "$(TARGET_NAME)"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/BitriseSampleUnitAndOtherTestsApp.app/BitriseSampleUnitAndOtherTestsApp"; + }; + name = Debug; + }; + BA060A011AA610E100F24A40 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 61199DC195E180BBB3AA23C7 /* Pods-BitriseSampleUnitAndOtherTestsAppTests.release.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + FRAMEWORK_SEARCH_PATHS = ( + "$(SDKROOT)/Developer/Library/Frameworks", + "$(inherited)", + ); + INFOPLIST_FILE = BitriseSampleUnitAndOtherTestsAppTests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_NAME = "$(TARGET_NAME)"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/BitriseSampleUnitAndOtherTestsApp.app/BitriseSampleUnitAndOtherTestsApp"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + BA0609D11AA610E100F24A40 /* Build configuration list for PBXProject "BitriseSampleUnitAndOtherTestsApp" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + BA0609FA1AA610E100F24A40 /* Debug */, + BA0609FB1AA610E100F24A40 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + BA0609FC1AA610E100F24A40 /* Build configuration list for PBXNativeTarget "BitriseSampleUnitAndOtherTestsApp" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + BA0609FD1AA610E100F24A40 /* Debug */, + BA0609FE1AA610E100F24A40 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + BA0609FF1AA610E100F24A40 /* Build configuration list for PBXNativeTarget "BitriseSampleUnitAndOtherTestsAppTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + BA060A001AA610E100F24A40 /* Debug */, + BA060A011AA610E100F24A40 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCVersionGroup section */ + BA0609E01AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsApp.xcdatamodeld */ = { + isa = XCVersionGroup; + children = ( + BA0609E11AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsApp.xcdatamodel */, + ); + currentVersion = BA0609E11AA610E100F24A40 /* BitriseSampleUnitAndOtherTestsApp.xcdatamodel */; + path = BitriseSampleUnitAndOtherTestsApp.xcdatamodeld; + sourceTree = ""; + versionGroupType = wrapper.xcdatamodel; + }; +/* End XCVersionGroup section */ + }; + rootObject = BA0609CE1AA610E100F24A40 /* Project object */; +} diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..86d371e8 --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp.xcodeproj/project.xcworkspace/xcshareddata/BitriseSampleUnitAndOtherTestsApp.xccheckout b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp.xcodeproj/project.xcworkspace/xcshareddata/BitriseSampleUnitAndOtherTestsApp.xccheckout new file mode 100644 index 00000000..fa1f40e5 --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp.xcodeproj/project.xcworkspace/xcshareddata/BitriseSampleUnitAndOtherTestsApp.xccheckout @@ -0,0 +1,41 @@ + + + + + IDESourceControlProjectFavoriteDictionaryKey + + IDESourceControlProjectIdentifier + 07529588-2568-4464-9D55-E3A30DB2D63A + IDESourceControlProjectName + BitriseSampleUnitAndOtherTestsApp + IDESourceControlProjectOriginsDictionary + + D8379880FB320D8E1DBD87F3490D48DFF1337CDB + github.com:bitrise-io/sample-apps-ios-unit-and-other-tests.git + + IDESourceControlProjectPath + BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp.xcodeproj + IDESourceControlProjectRelativeInstallPathDictionary + + D8379880FB320D8E1DBD87F3490D48DFF1337CDB + ../../.. + + IDESourceControlProjectURL + github.com:bitrise-io/sample-apps-ios-unit-and-other-tests.git + IDESourceControlProjectVersion + 111 + IDESourceControlProjectWCCIdentifier + D8379880FB320D8E1DBD87F3490D48DFF1337CDB + IDESourceControlProjectWCConfigurations + + + IDESourceControlRepositoryExtensionIdentifierKey + public.vcs.git + IDESourceControlWCCIdentifierKey + D8379880FB320D8E1DBD87F3490D48DFF1337CDB + IDESourceControlWCCName + sample-apps-ios-unit-and-other-tests + + + + diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp.xcodeproj/xcshareddata/xcschemes/BitriseSampleUnitAndOtherTestsApp.xcscheme b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp.xcodeproj/xcshareddata/xcschemes/BitriseSampleUnitAndOtherTestsApp.xcscheme new file mode 100644 index 00000000..7f21e26e --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp.xcodeproj/xcshareddata/xcschemes/BitriseSampleUnitAndOtherTestsApp.xcscheme @@ -0,0 +1,110 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/AppDelegate.h b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/AppDelegate.h new file mode 100644 index 00000000..a65752d1 --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/AppDelegate.h @@ -0,0 +1,25 @@ +// +// AppDelegate.h +// BitriseSampleUnitAndOtherTestsApp +// +// Created by Viktor Benei on 3/3/15. +// Copyright (c) 2015 Bitrise. All rights reserved. +// + +#import +#import + +@interface AppDelegate : UIResponder + +@property (strong, nonatomic) UIWindow *window; + +@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext; +@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel; +@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator; + +- (void)saveContext; +- (NSURL *)applicationDocumentsDirectory; + + +@end + diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/AppDelegate.m b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/AppDelegate.m new file mode 100644 index 00000000..dd5b82c6 --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/AppDelegate.m @@ -0,0 +1,127 @@ +// +// AppDelegate.m +// BitriseSampleUnitAndOtherTestsApp +// +// Created by Viktor Benei on 3/3/15. +// Copyright (c) 2015 Bitrise. All rights reserved. +// + +#import "AppDelegate.h" + +@interface AppDelegate () + +@end + +@implementation AppDelegate + + +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { + // Override point for customization after application launch. + return YES; +} + +- (void)applicationWillResignActive:(UIApplication *)application { + // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. +} + +- (void)applicationDidEnterBackground:(UIApplication *)application { + // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. +} + +- (void)applicationWillEnterForeground:(UIApplication *)application { + // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. +} + +- (void)applicationDidBecomeActive:(UIApplication *)application { + // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. +} + +- (void)applicationWillTerminate:(UIApplication *)application { + // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. + // Saves changes in the application's managed object context before the application terminates. + [self saveContext]; +} + +#pragma mark - Core Data stack + +@synthesize managedObjectContext = _managedObjectContext; +@synthesize managedObjectModel = _managedObjectModel; +@synthesize persistentStoreCoordinator = _persistentStoreCoordinator; + +- (NSURL *)applicationDocumentsDirectory { + // The directory the application uses to store the Core Data store file. This code uses a directory named "com.bitrise.BitriseSampleUnitAndOtherTestsApp" in the application's documents directory. + return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; +} + +- (NSManagedObjectModel *)managedObjectModel { + // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model. + if (_managedObjectModel != nil) { + return _managedObjectModel; + } + NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"BitriseSampleUnitAndOtherTestsApp" withExtension:@"momd"]; + _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; + return _managedObjectModel; +} + +- (NSPersistentStoreCoordinator *)persistentStoreCoordinator { + // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. + if (_persistentStoreCoordinator != nil) { + return _persistentStoreCoordinator; + } + + // Create the coordinator and store + + _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; + NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"BitriseSampleUnitAndOtherTestsApp.sqlite"]; + NSError *error = nil; + NSString *failureReason = @"There was an error creating or loading the application's saved data."; + if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { + // Report any error we got. + NSMutableDictionary *dict = [NSMutableDictionary dictionary]; + dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data"; + dict[NSLocalizedFailureReasonErrorKey] = failureReason; + dict[NSUnderlyingErrorKey] = error; + error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict]; + // Replace this with code to handle the error appropriately. + // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. + NSLog(@"Unresolved error %@, %@", error, [error userInfo]); + abort(); + } + + return _persistentStoreCoordinator; +} + + +- (NSManagedObjectContext *)managedObjectContext { + // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) + if (_managedObjectContext != nil) { + return _managedObjectContext; + } + + NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; + if (!coordinator) { + return nil; + } + _managedObjectContext = [[NSManagedObjectContext alloc] init]; + [_managedObjectContext setPersistentStoreCoordinator:coordinator]; + return _managedObjectContext; +} + +#pragma mark - Core Data Saving support + +- (void)saveContext { + NSManagedObjectContext *managedObjectContext = self.managedObjectContext; + if (managedObjectContext != nil) { + NSError *error = nil; + if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) { + // Replace this implementation with code to handle the error appropriately. + // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. + NSLog(@"Unresolved error %@, %@", error, [error userInfo]); + abort(); + } + } +} + +@end diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/Base.lproj/LaunchScreen.xib b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/Base.lproj/LaunchScreen.xib new file mode 100644 index 00000000..3c0ad3fe --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/Base.lproj/LaunchScreen.xib @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/Base.lproj/Main.storyboard b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/Base.lproj/Main.storyboard new file mode 100644 index 00000000..f56d2f3b --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/Base.lproj/Main.storyboard @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp.xcdatamodeld/.xccurrentversion b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp.xcdatamodeld/.xccurrentversion new file mode 100644 index 00000000..7a2b9665 --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp.xcdatamodeld/.xccurrentversion @@ -0,0 +1,8 @@ + + + + + _XCCurrentVersionName + BitriseSampleUnitAndOtherTestsApp.xcdatamodel + + diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp.xcdatamodeld/BitriseSampleUnitAndOtherTestsApp.xcdatamodel/contents b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp.xcdatamodeld/BitriseSampleUnitAndOtherTestsApp.xcdatamodel/contents new file mode 100644 index 00000000..193f33c9 --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp.xcdatamodeld/BitriseSampleUnitAndOtherTestsApp.xcdatamodel/contents @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/Images.xcassets/AppIcon.appiconset/Contents.json b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/Images.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..36d2c80d --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/Images.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "3x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/Info.plist b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/Info.plist new file mode 100644 index 00000000..e47f46e1 --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/Info.plist @@ -0,0 +1,47 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + com.bitrise.$(PRODUCT_NAME:rfc1034identifier) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/ViewController.h b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/ViewController.h new file mode 100644 index 00000000..8d84cc56 --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/ViewController.h @@ -0,0 +1,15 @@ +// +// ViewController.h +// BitriseSampleUnitAndOtherTestsApp +// +// Created by Viktor Benei on 3/3/15. +// Copyright (c) 2015 Bitrise. All rights reserved. +// + +#import + +@interface ViewController : UIViewController + + +@end + diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/ViewController.m b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/ViewController.m new file mode 100644 index 00000000..cf68b7e8 --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/ViewController.m @@ -0,0 +1,27 @@ +// +// ViewController.m +// BitriseSampleUnitAndOtherTestsApp +// +// Created by Viktor Benei on 3/3/15. +// Copyright (c) 2015 Bitrise. All rights reserved. +// + +#import "ViewController.h" + +@interface ViewController () + +@end + +@implementation ViewController + +- (void)viewDidLoad { + [super viewDidLoad]; + // Do any additional setup after loading the view, typically from a nib. +} + +- (void)didReceiveMemoryWarning { + [super didReceiveMemoryWarning]; + // Dispose of any resources that can be recreated. +} + +@end diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/main.m b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/main.m new file mode 100644 index 00000000..262bbc00 --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsApp/main.m @@ -0,0 +1,16 @@ +// +// main.m +// BitriseSampleUnitAndOtherTestsApp +// +// Created by Viktor Benei on 3/3/15. +// Copyright (c) 2015 Bitrise. All rights reserved. +// + +#import +#import "AppDelegate.h" + +int main(int argc, char * argv[]) { + @autoreleasepool { + return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); + } +} diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsAppTests/BitriseSampleUnitAndOtherTestsAppTests.m b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsAppTests/BitriseSampleUnitAndOtherTestsAppTests.m new file mode 100644 index 00000000..d3bd580f --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsAppTests/BitriseSampleUnitAndOtherTestsAppTests.m @@ -0,0 +1,40 @@ +// +// BitriseSampleUnitAndOtherTestsAppTests.m +// BitriseSampleUnitAndOtherTestsAppTests +// +// Created by Viktor Benei on 3/3/15. +// Copyright (c) 2015 Bitrise. All rights reserved. +// + +#import +#import + +@interface BitriseSampleUnitAndOtherTestsAppTests : XCTestCase + +@end + +@implementation BitriseSampleUnitAndOtherTestsAppTests + +- (void)setUp { + [super setUp]; + // Put setup code here. This method is called before the invocation of each test method in the class. +} + +- (void)tearDown { + // Put teardown code here. This method is called after the invocation of each test method in the class. + [super tearDown]; +} + +- (void)testExample { + // This is an example of a functional test case. + XCTAssert(YES, @"Pass"); +} + +- (void)testPerformanceExample { + // This is an example of a performance test case. + [self measureBlock:^{ + // Put the code you want to measure the time of here. + }]; +} + +@end diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsAppTests/Info.plist b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsAppTests/Info.plist new file mode 100644 index 00000000..a13b0ec4 --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsAppTests/Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + com.bitrise.$(PRODUCT_NAME:rfc1034identifier) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + + diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsAppTests/KiwiSampleSpec.m b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsAppTests/KiwiSampleSpec.m new file mode 100644 index 00000000..93cb7616 --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/BitriseSampleUnitAndOtherTestsAppTests/KiwiSampleSpec.m @@ -0,0 +1,21 @@ +// +// KiwiSampleSpec.m +// BitriseSampleUnitAndOtherTestsApp +// +// Created by Viktor Benei on 3/3/15. +// Copyright (c) 2015 Bitrise. All rights reserved. +// + +#import "Kiwi.h" + +SPEC_BEGIN(KiwiSampleSpec) + +describe(@"KiwiSample", ^{ + it(@"is pretty cool", ^{ + NSUInteger a = 16; + NSUInteger b = 26; + [[theValue(a + b) should] equal:theValue(42)]; + }); +}); + +SPEC_END \ No newline at end of file diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/Podfile.lock b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/Podfile.lock new file mode 100644 index 00000000..de629f5c --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/Podfile.lock @@ -0,0 +1,10 @@ +PODS: + - Kiwi (2.3.1) + +DEPENDENCIES: + - Kiwi + +SPEC CHECKSUMS: + Kiwi: f038a6c61f7a9e4d7766bff5717aa3b3fdb75f55 + +COCOAPODS: 0.39.0 diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/fastlane/Fastfile b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/fastlane/Fastfile new file mode 100644 index 00000000..750b1937 --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/fastlane/Fastfile @@ -0,0 +1,62 @@ +# vim: set filetype=ruby: +fastlane_version "1.61.0" +opt_out_usage + +lane :clean do + sh "cd .. && rm -rf build/" + sh "cd .. && rm -rf BitriseSampleUnitAndOtherTestsApp.xcworkspace/" + sh "cd .. && rm -rf DerivedData/" + sh "cd .. && rm -rf Pods/" + sh "cd .. && rm -f fastlane/report.xml" + sh "cd .. && rm -rf fastlane/test_output/" + sh "cd .. && rm -f compile_commands.json" +end + +platform :ios do + before_all do + # Uncomment to enable auto-install of Xcode and/or auto-detection of DEVELOPER_DIR + #xcode_install(version: "7.2") + cocoapods + end + + lane :test_and_analyze do + # Ensure clean simulator state for tests + sh "killall 'iOS Simulator' 'iPhone Simulator' 'Simulator' || true" + sh "SNAPSHOT_FORCE_DELETE=true snapshot reset_simulators" + + # Run xcodebuild test and analyze actions + scan( + workspace: "BitriseSampleUnitAndOtherTestsApp.xcworkspace", + scheme: "BitriseSampleUnitAndOtherTestsApp", + xcargs: "-derivedDataPath DerivedData analyze CLANG_ANALYZER_OUTPUT_DIR=#{Dir.pwd}/../build/reports/clang/", + code_coverage: true, + output_types: "html,junit,json-compilation-database", + output_directory: "build/reports", + ) + + # Don't keep analysis on Pods + sh "cd .. && rm -rf build/reports/clang/StaticAnalyzer/Pods/" + + # Move JUnit reports into their own directory and make files match naming standard + sh "cd .. && mkdir build/reports/junit/" + sh "cd .. && mv build/reports/report.junit build/reports/junit/TESTS-BitriseSampleUnitAndOtherTestsApp.xml" + end + + lane :oclint do + sh "cd .. && cp build/reports/report.json-compilation-database compile_commands.json" + sh "cd .. && mkdir -p build/reports" + oclint( + select_regex: /BitriseSampleUnitAndOtherTestsApp\/.*/, + report_type: "pmd", + report_path: "build/reports/oclint.xml", + max_priority_1: 10000, + max_priority_2: 10000, + max_priority_3: 10000, + ) + sh "cd .. && rm -f compile_commands.json" + end + + lane :lizard do + sh "cd .. && lizard --xml BitriseSampleUnitAndOtherTestsApp/ > build/reports/lizard.xml" + end +end diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/fastlane/README.md b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/fastlane/README.md new file mode 100644 index 00000000..8c1dd45b --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/fastlane/README.md @@ -0,0 +1,32 @@ +fastlane documentation +================ +# Installation +``` +sudo gem install fastlane +``` +# Available Actions +### clean +``` +fastlane clean +``` + + +---- + +## iOS +### ios test_and_analyze +``` +fastlane ios test_and_analyze +``` + +### ios oclint +``` +fastlane ios oclint +``` + + +---- + +This README.md is auto-generated and will be re-generated every time to run [fastlane](https://fastlane.tools). +More information about fastlane can be found on [https://fastlane.tools](https://fastlane.tools). +The documentation of fastlane can be found on [GitHub](https://github.com/fastlane/fastlane). \ No newline at end of file diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/podfile b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/podfile new file mode 100644 index 00000000..7ee6118f --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/podfile @@ -0,0 +1,16 @@ +# Podfile + +# Select the appropriate platform below +# Specify the minimum supported iOS version (or later) required by Kiwi +platform :ios, '8.0' +# platform :osx + +# +# Some other entries might already exist in the file +# ... +# + +# Add Kiwi as an exclusive dependency for the Tests target +target :BitriseSampleUnitAndOtherTestsAppTests, :exclusive => true do + pod 'Kiwi' +end diff --git a/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/sonar-project.properties b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/sonar-project.properties new file mode 100644 index 00000000..5b7946b4 --- /dev/null +++ b/its/plugin/projects/BitriseSampleUnitAndOtherTestsApp/sonar-project.properties @@ -0,0 +1,6 @@ +sonar.projectKey=BitriseSampleUnitAndOtherTestsApp +sonar.projectName=BitriseSampleUnitAndOtherTestsApp +sonar.projectVersion=1.0 + +sonar.sources=BitriseSampleUnitAndOtherTestsApp +sonar.tests=BitriseSampleUnitAndOtherTestsAppTests diff --git a/its/plugin/tests/pom.xml b/its/plugin/tests/pom.xml new file mode 100644 index 00000000..b44c97f1 --- /dev/null +++ b/its/plugin/tests/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + + org.sonarqubecommunity.objectivec + objective-c-its-plugin + 0.5.0-SNAPSHOT + + + objective-c-its-plugin-tests + SonarQube Objective-C (Community) :: ITs :: Plugin :: Tests + + + true + + + + + org.sonarsource.orchestrator + sonar-orchestrator + ${orchestrator.version} + test + + + com.oracle + ojdbc6 + + + + + org.codehaus.sonar + sonar-plugin-api + test + + + junit + junit + test + + + org.easytesting + fest-assert + test + + + + + + + + maven-surefire-plugin + + + org/sonar/its/objectivec/Tests.java + + + + + + + diff --git a/its/plugin/tests/src/test/java/org/sonar/its/objectivec/ObjectiveCTest.java b/its/plugin/tests/src/test/java/org/sonar/its/objectivec/ObjectiveCTest.java new file mode 100644 index 00000000..79436858 --- /dev/null +++ b/its/plugin/tests/src/test/java/org/sonar/its/objectivec/ObjectiveCTest.java @@ -0,0 +1,75 @@ +/* + * SonarQube Objective-C (Community) :: ITs :: Plugin :: Tests + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.its.objectivec; + +import com.sonar.orchestrator.Orchestrator; +import com.sonar.orchestrator.build.SonarScanner; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Test; +import org.sonar.wsclient.Sonar; +import org.sonar.wsclient.services.Measure; +import org.sonar.wsclient.services.Resource; +import org.sonar.wsclient.services.ResourceQuery; + +import java.io.IOException; +import java.net.URISyntaxException; + +import static org.fest.assertions.Assertions.assertThat; + +public class ObjectiveCTest { + private static final String PROJECT_KEY = "BitriseSampleUnitAndOtherTestsApp"; + private static final String SRC_DIR_NAME = "BitriseSampleUnitAndOtherTestsApp"; + + @ClassRule + public static Orchestrator orchestrator = Tests.ORCHESTRATOR; + + private static Sonar sonar; + + @BeforeClass + public static void startServer() throws IOException, URISyntaxException { + sonar = orchestrator.getServer().getWsClient(); + } + + @Test + public void testSimpleBuild() { + SonarScanner scanner = SonarScanner.create() + .setProjectDir(Tests.projectDirectoryFor(PROJECT_KEY)); + orchestrator.executeBuild(scanner); + + assertThat(getResourceMeasure(PROJECT_KEY, "files").getValue()).isEqualTo(5); + assertThat(getResourceMeasure(getResourceKey(PROJECT_KEY, "main.m"), "lines").getValue()).isGreaterThan(1); + assertThat(getResource(getResourceKey(PROJECT_KEY, "DoesNotExist.m"))).isNull(); + } + + private String getResourceKey(String projectKey, String fileName) { + return projectKey + ":" + SRC_DIR_NAME + "/" + fileName; + } + + private Resource getResource(String resourceKey) { + return sonar.find(ResourceQuery.create(resourceKey)); + } + + private Measure getResourceMeasure(String resourceKey, String metricKey) { + Resource resource = sonar.find(ResourceQuery.createForMetrics(resourceKey, metricKey.trim())); + assertThat(resource).isNotNull(); + return resource.getMeasure(metricKey.trim()); + } +} diff --git a/its/plugin/tests/src/test/java/org/sonar/its/objectivec/Tests.java b/its/plugin/tests/src/test/java/org/sonar/its/objectivec/Tests.java new file mode 100644 index 00000000..1f60cd73 --- /dev/null +++ b/its/plugin/tests/src/test/java/org/sonar/its/objectivec/Tests.java @@ -0,0 +1,57 @@ +/* + * SonarQube Objective-C (Community) :: ITs :: Plugin :: Tests + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.its.objectivec; + +import com.sonar.orchestrator.Orchestrator; +import com.sonar.orchestrator.OrchestratorBuilder; +import com.sonar.orchestrator.locator.FileLocation; +import org.junit.ClassRule; +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +import java.io.File; + +@RunWith(Suite.class) +@Suite.SuiteClasses({ + ObjectiveCTest.class +}) +public class Tests { + + public static final String PROJECT_ROOT_DIR = "../projects/"; + private static final String PLUGIN_KEY = "objectivec"; + + @ClassRule + public static final Orchestrator ORCHESTRATOR; + + static { + OrchestratorBuilder orchestratorBuilder = Orchestrator.builderEnv() + .addPlugin(FileLocation.byWildcardMavenFilename( + new File("../../../sonar-objective-c-plugin/target"), "sonar-objective-c-plugin-*.jar")); + ORCHESTRATOR = orchestratorBuilder.build(); + } + + public static boolean is_after_plugin(String version) { + return ORCHESTRATOR.getConfiguration().getPluginVersion(PLUGIN_KEY).isGreaterThanOrEquals(version); + } + + public static File projectDirectoryFor(String projectDirName) { + return new File(Tests.PROJECT_ROOT_DIR + projectDirName + "/"); + } +} \ No newline at end of file diff --git a/its/pom.xml b/its/pom.xml new file mode 100644 index 00000000..f01b8d6f --- /dev/null +++ b/its/pom.xml @@ -0,0 +1,23 @@ + + + 4.0.0 + + + org.sonarqubecommunity.objectivec + objective-c + 0.5.0-SNAPSHOT + + + objective-c-its + SonarQube Objective-C (Community) :: ITs + pom + + + plugin + + + + true + true + + diff --git a/objective-c-squid/pom.xml b/objective-c-squid/pom.xml new file mode 100644 index 00000000..73a4be35 --- /dev/null +++ b/objective-c-squid/pom.xml @@ -0,0 +1,55 @@ + + 4.0.0 + + + org.sonarqubecommunity.objectivec + objective-c + 0.5.0-SNAPSHOT + + + objective-c-squid + + SonarQube Objective-C (Community) :: Squid + + + + org.codehaus.sonar + sonar-plugin-api + + + org.sonarsource.sslr + sslr-core + + + org.sonarsource.sslr-squid-bridge + sslr-squid-bridge + + + + org.codehaus.sonar + sonar-testing-harness + test + + + org.sonarsource.sslr + sslr-testing-harness + test + + + junit + junit + test + + + org.easytesting + fest-assert + test + + + ch.qos.logback + logback-classic + test + + + diff --git a/src/main/java/org/sonar/objectivec/ObjectiveCAstScanner.java b/objective-c-squid/src/main/java/org/sonar/objectivec/ObjectiveCAstScanner.java similarity index 60% rename from src/main/java/org/sonar/objectivec/ObjectiveCAstScanner.java rename to objective-c-squid/src/main/java/org/sonar/objectivec/ObjectiveCAstScanner.java index ae3b590e..6ccc5f04 100644 --- a/src/main/java/org/sonar/objectivec/ObjectiveCAstScanner.java +++ b/objective-c-squid/src/main/java/org/sonar/objectivec/ObjectiveCAstScanner.java @@ -1,7 +1,7 @@ /* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,17 +13,17 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.objectivec; -import java.io.File; -import java.util.Collection; - -import org.sonar.objectivec.api.ObjectiveCGrammar; +import com.sonar.sslr.api.Grammar; +import com.sonar.sslr.impl.Parser; import org.sonar.objectivec.api.ObjectiveCMetric; +import org.sonar.objectivec.highlighter.SonarComponents; +import org.sonar.objectivec.highlighter.SyntaxHighlighterVisitor; import org.sonar.objectivec.parser.ObjectiveCParser; import org.sonar.squidbridge.AstScanner; import org.sonar.squidbridge.CommentAnalyser; @@ -37,21 +37,25 @@ import org.sonar.squidbridge.metrics.LinesOfCodeVisitor; import org.sonar.squidbridge.metrics.LinesVisitor; -import com.sonar.sslr.impl.Parser; +import javax.annotation.Nullable; +import java.io.File; +import java.util.Collection; public class ObjectiveCAstScanner { private ObjectiveCAstScanner() { + // prevents outside instantiation } /** * Helper method for testing checks without having to deploy them on a Sonar instance. */ - public static SourceFile scanSingleFile(File file, SquidAstVisitor... visitors) { + @SafeVarargs + public static SourceFile scanSingleFile(File file, SquidAstVisitor... visitors) { if (!file.isFile()) { throw new IllegalArgumentException("File '" + file + "' not found."); } - AstScanner scanner = create(new ObjectiveCConfiguration(), visitors); + AstScanner scanner = create(new ObjectiveCConfiguration(), null, visitors); scanner.scanFile(file); Collection sources = scanner.getIndex().search(new QueryByType(SourceFile.class)); if (sources.size() != 1) { @@ -60,11 +64,13 @@ public static SourceFile scanSingleFile(File file, SquidAstVisitor create(ObjectiveCConfiguration conf, SquidAstVisitor... visitors) { - final SquidAstVisitorContextImpl context = new SquidAstVisitorContextImpl(new SourceProject("Objective-C Project")); - final Parser parser = ObjectiveCParser.create(conf); + @SafeVarargs + public static AstScanner create(ObjectiveCConfiguration conf, + @Nullable SonarComponents sonarComponents, SquidAstVisitor... visitors) { + final SquidAstVisitorContextImpl context = new SquidAstVisitorContextImpl<>(new SourceProject("Objective-C Project")); + final Parser parser = ObjectiveCParser.create(conf); - AstScanner.Builder builder = AstScanner. builder(context).setBaseParser(parser); + AstScanner.Builder builder = AstScanner.builder(context).setBaseParser(parser); /* Metrics */ builder.withMetrics(ObjectiveCMetric.values()); @@ -89,15 +95,25 @@ public String getContents(String comment) { }); /* Files */ - builder.setFilesMetric(ObjectiveCMetric.FILES); + builder.setFilesMetric(ObjectiveCMetric.FILES); /* Metrics */ - builder.withSquidAstVisitor(new LinesVisitor(ObjectiveCMetric.LINES)); - builder.withSquidAstVisitor(new LinesOfCodeVisitor(ObjectiveCMetric.LINES_OF_CODE)); - builder.withSquidAstVisitor(CommentsVisitor. builder().withCommentMetric(ObjectiveCMetric.COMMENT_LINES) - .withNoSonar(true) - .withIgnoreHeaderComment(conf.getIgnoreHeaderComments()) - .build()); + builder.withSquidAstVisitor(new LinesVisitor<>(ObjectiveCMetric.LINES)); + builder.withSquidAstVisitor(new LinesOfCodeVisitor<>(ObjectiveCMetric.LINES_OF_CODE)); + builder.withSquidAstVisitor(CommentsVisitor.builder().withCommentMetric(ObjectiveCMetric.COMMENT_LINES) + .withNoSonar(true) + .withIgnoreHeaderComment(conf.getIgnoreHeaderComments()) + .build()); + + /* Syntax highlighter */ + if (sonarComponents != null) { + builder.withSquidAstVisitor(new SyntaxHighlighterVisitor(sonarComponents, conf.getCharset())); + } + + /* External visitors */ + for (SquidAstVisitor visitor : visitors) { + builder.withSquidAstVisitor(visitor); + } return builder.build(); } diff --git a/src/main/java/org/sonar/objectivec/ObjectiveCConfiguration.java b/objective-c-squid/src/main/java/org/sonar/objectivec/ObjectiveCConfiguration.java similarity index 74% rename from src/main/java/org/sonar/objectivec/ObjectiveCConfiguration.java rename to objective-c-squid/src/main/java/org/sonar/objectivec/ObjectiveCConfiguration.java index cee56859..1a424d21 100644 --- a/src/main/java/org/sonar/objectivec/ObjectiveCConfiguration.java +++ b/objective-c-squid/src/main/java/org/sonar/objectivec/ObjectiveCConfiguration.java @@ -1,7 +1,7 @@ /* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,21 +13,22 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.objectivec; -import java.nio.charset.Charset; +import org.sonar.squidbridge.api.SquidConfiguration; -import org.sonar.squid.api.SquidConfiguration; +import java.nio.charset.Charset; public class ObjectiveCConfiguration extends SquidConfiguration { private boolean ignoreHeaderComments; public ObjectiveCConfiguration() { + // no-op } public ObjectiveCConfiguration(Charset charset) { diff --git a/objective-c-squid/src/main/java/org/sonar/objectivec/api/ObjectiveCGrammar.java b/objective-c-squid/src/main/java/org/sonar/objectivec/api/ObjectiveCGrammar.java new file mode 100644 index 00000000..fe2f1146 --- /dev/null +++ b/objective-c-squid/src/main/java/org/sonar/objectivec/api/ObjectiveCGrammar.java @@ -0,0 +1,41 @@ +/* + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.objectivec.api; + +import com.sonar.sslr.api.Grammar; +import org.sonar.sslr.grammar.GrammarRuleKey; +import org.sonar.sslr.grammar.LexerfulGrammarBuilder; + +import static com.sonar.sslr.api.GenericTokenType.EOF; + +public enum ObjectiveCGrammar implements GrammarRuleKey { + + COMPILATION_UNIT; + + public static Grammar create() { + LexerfulGrammarBuilder b = LexerfulGrammarBuilder.create(); + + b.rule(COMPILATION_UNIT).is(b.zeroOrMore(b.nextNot(EOF), b.anyToken()), EOF); + b.setRootRule(COMPILATION_UNIT); + + return b.buildWithMemoizationOfMatchesForAllRules(); + } + +} diff --git a/src/main/java/org/sonar/objectivec/api/ObjectiveCKeyword.java b/objective-c-squid/src/main/java/org/sonar/objectivec/api/ObjectiveCKeyword.java similarity index 90% rename from src/main/java/org/sonar/objectivec/api/ObjectiveCKeyword.java rename to objective-c-squid/src/main/java/org/sonar/objectivec/api/ObjectiveCKeyword.java index df2c1a81..142e7e6a 100644 --- a/src/main/java/org/sonar/objectivec/api/ObjectiveCKeyword.java +++ b/objective-c-squid/src/main/java/org/sonar/objectivec/api/ObjectiveCKeyword.java @@ -1,7 +1,7 @@ /* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +13,9 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.objectivec.api; @@ -112,6 +112,7 @@ public enum ObjectiveCKeyword implements TokenType { ELSE("else"), ENUM("enum"), EXTERN("extern"), + FALSE("false"), FLOAT("float"), FOR("for"), GOTO("goto"), @@ -126,6 +127,7 @@ public enum ObjectiveCKeyword implements TokenType { STATIC("static"), STRUCT("struct"), SWITCH("switch"), + TRUE("true"), TYPEDEF("typedef"), UNION("union"), UNSIGNED("unsigned"), @@ -137,6 +139,7 @@ public enum ObjectiveCKeyword implements TokenType { BOOL("BOOL"), SUPER("super"), + SELF("self"), ID("id"), CLASS("Class"), IMP("IMP"), @@ -147,18 +150,21 @@ public enum ObjectiveCKeyword implements TokenType { private final String value; - private ObjectiveCKeyword(String value) { + /*private*/ ObjectiveCKeyword(String value) { this.value = value; } + @Override public String getName() { return name(); } + @Override public String getValue() { return value; } + @Override public boolean hasToBeSkippedFromAst(AstNode node) { return false; } diff --git a/src/main/java/org/sonar/objectivec/api/ObjectiveCMetric.java b/objective-c-squid/src/main/java/org/sonar/objectivec/api/ObjectiveCMetric.java similarity index 76% rename from src/main/java/org/sonar/objectivec/api/ObjectiveCMetric.java rename to objective-c-squid/src/main/java/org/sonar/objectivec/api/ObjectiveCMetric.java index 23058102..194dcd17 100644 --- a/src/main/java/org/sonar/objectivec/api/ObjectiveCMetric.java +++ b/objective-c-squid/src/main/java/org/sonar/objectivec/api/ObjectiveCMetric.java @@ -1,7 +1,7 @@ /* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +13,9 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.objectivec.api; @@ -27,26 +27,30 @@ public enum ObjectiveCMetric implements MetricDef { LINES, LINES_OF_CODE, COMMENT_LINES, - STATEMENTS, COMPLEXITY, FUNCTIONS; + @Override public String getName() { return name(); } + @Override public boolean isCalculatedMetric() { return false; } + @Override public boolean aggregateIfThereIsAlreadyAValue() { return true; } + @Override public boolean isThereAggregationFormula() { return true; } + @Override public CalculatedMetricFormula getCalculatedMetricFormula() { return null; } diff --git a/src/main/java/org/sonar/objectivec/api/ObjectiveCPunctuator.java b/objective-c-squid/src/main/java/org/sonar/objectivec/api/ObjectiveCPunctuator.java similarity index 82% rename from src/main/java/org/sonar/objectivec/api/ObjectiveCPunctuator.java rename to objective-c-squid/src/main/java/org/sonar/objectivec/api/ObjectiveCPunctuator.java index d6bba1ad..d917db2f 100644 --- a/src/main/java/org/sonar/objectivec/api/ObjectiveCPunctuator.java +++ b/objective-c-squid/src/main/java/org/sonar/objectivec/api/ObjectiveCPunctuator.java @@ -1,7 +1,7 @@ /* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +13,9 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.objectivec.api; @@ -89,22 +89,26 @@ public enum ObjectiveCPunctuator implements TokenType { MINUSLT("->"), MINUSLTSTAR("->*"), + DOT("."), DOTSTAR(".*"); private final String value; - private ObjectiveCPunctuator(String word) { + /*private*/ ObjectiveCPunctuator(String word) { this.value = word; } + @Override public String getName() { return name(); } + @Override public String getValue() { return value; } + @Override public boolean hasToBeSkippedFromAst(AstNode node) { return false; } diff --git a/src/main/java/org/sonar/objectivec/api/ObjectiveCTokenType.java b/objective-c-squid/src/main/java/org/sonar/objectivec/api/ObjectiveCTokenType.java similarity index 58% rename from src/main/java/org/sonar/objectivec/api/ObjectiveCTokenType.java rename to objective-c-squid/src/main/java/org/sonar/objectivec/api/ObjectiveCTokenType.java index 553b7129..43712110 100644 --- a/src/main/java/org/sonar/objectivec/api/ObjectiveCTokenType.java +++ b/objective-c-squid/src/main/java/org/sonar/objectivec/api/ObjectiveCTokenType.java @@ -1,7 +1,7 @@ /* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,29 +13,42 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.objectivec.api; +import com.google.common.collect.ImmutableList; import com.sonar.sslr.api.AstNode; import com.sonar.sslr.api.TokenType; -public enum ObjectiveCTokenType implements TokenType { +import java.util.List; - NUMERIC_LITERAL; +public enum ObjectiveCTokenType implements TokenType { + CHARACTER_LITERAL, + DOUBLE_LITERAL, + FLOAT_LITERAL, + INTEGER_LITERAL, + LONG_LITERAL, + STRING_LITERAL; + @Override public String getName() { return name(); } + @Override public String getValue() { return name(); } + @Override public boolean hasToBeSkippedFromAst(AstNode node) { return false; } + public static List numberLiterals() { + return ImmutableList.of(DOUBLE_LITERAL, FLOAT_LITERAL, INTEGER_LITERAL, LONG_LITERAL); + } } diff --git a/objective-c-squid/src/main/java/org/sonar/objectivec/api/package-info.java b/objective-c-squid/src/main/java/org/sonar/objectivec/api/package-info.java new file mode 100644 index 00000000..176f3d34 --- /dev/null +++ b/objective-c-squid/src/main/java/org/sonar/objectivec/api/package-info.java @@ -0,0 +1,23 @@ +/* + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +@ParametersAreNonnullByDefault +package org.sonar.objectivec.api; + +import javax.annotation.ParametersAreNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/org/sonar/objectivec/checks/CheckList.java b/objective-c-squid/src/main/java/org/sonar/objectivec/checks/CheckList.java similarity index 65% rename from src/main/java/org/sonar/objectivec/checks/CheckList.java rename to objective-c-squid/src/main/java/org/sonar/objectivec/checks/CheckList.java index be5d018f..0d9c55eb 100644 --- a/src/main/java/org/sonar/objectivec/checks/CheckList.java +++ b/objective-c-squid/src/main/java/org/sonar/objectivec/checks/CheckList.java @@ -1,7 +1,7 @@ /* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,29 +13,29 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.objectivec.checks; -import java.util.List; - import com.google.common.collect.ImmutableList; +import java.util.List; + public final class CheckList { public static final String REPOSITORY_KEY = "objectivec"; - public static final String SONAR_WAY_PROFILE = "Sonar way"; + public static final String SONAR_WAY_PROFILE = "SonarQube way"; private CheckList() { } public static List getChecks() { - return ImmutableList. of( - - ); + return ImmutableList.of( + // Add checks here + ); } } diff --git a/objective-c-squid/src/main/java/org/sonar/objectivec/checks/package-info.java b/objective-c-squid/src/main/java/org/sonar/objectivec/checks/package-info.java new file mode 100644 index 00000000..64255f1c --- /dev/null +++ b/objective-c-squid/src/main/java/org/sonar/objectivec/checks/package-info.java @@ -0,0 +1,23 @@ +/* + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +@ParametersAreNonnullByDefault +package org.sonar.objectivec.checks; + +import javax.annotation.ParametersAreNonnullByDefault; \ No newline at end of file diff --git a/objective-c-squid/src/main/java/org/sonar/objectivec/highlighter/SonarComponents.java b/objective-c-squid/src/main/java/org/sonar/objectivec/highlighter/SonarComponents.java new file mode 100644 index 00000000..422e288a --- /dev/null +++ b/objective-c-squid/src/main/java/org/sonar/objectivec/highlighter/SonarComponents.java @@ -0,0 +1,49 @@ +/* + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.objectivec.highlighter; + +import org.sonar.api.BatchExtension; +import org.sonar.api.batch.fs.FileSystem; +import org.sonar.api.batch.fs.InputFile; +import org.sonar.api.component.ResourcePerspectives; +import org.sonar.api.source.Highlightable; + +import javax.annotation.CheckForNull; +import java.io.File; + +public class SonarComponents implements BatchExtension { + + private final ResourcePerspectives resourcePerspectives; + private final FileSystem fs; + + public SonarComponents(ResourcePerspectives resourcePerspectives, FileSystem fs) { + this.resourcePerspectives = resourcePerspectives; + this.fs = fs; + } + + @CheckForNull + public InputFile inputFileFor(File file) { + return fs.inputFile(fs.predicates().hasAbsolutePath(file.getAbsolutePath())); + } + + public Highlightable highlightableFor(InputFile inputFile) { + return resourcePerspectives.as(Highlightable.class, inputFile); + } +} diff --git a/objective-c-squid/src/main/java/org/sonar/objectivec/highlighter/SyntaxHighlighterVisitor.java b/objective-c-squid/src/main/java/org/sonar/objectivec/highlighter/SyntaxHighlighterVisitor.java new file mode 100644 index 00000000..c9ba113a --- /dev/null +++ b/objective-c-squid/src/main/java/org/sonar/objectivec/highlighter/SyntaxHighlighterVisitor.java @@ -0,0 +1,154 @@ +/* + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.objectivec.highlighter; + +import com.google.common.base.Preconditions; +import com.google.common.base.Throwables; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Lists; +import com.google.common.io.Files; +import com.sonar.sslr.api.AstAndTokenVisitor; +import com.sonar.sslr.api.AstNode; +import com.sonar.sslr.api.AstNodeType; +import com.sonar.sslr.api.Grammar; +import com.sonar.sslr.api.Token; +import com.sonar.sslr.api.Trivia; +import org.sonar.api.batch.fs.InputFile; +import org.sonar.api.source.Highlightable; +import org.sonar.objectivec.api.ObjectiveCKeyword; +import org.sonar.objectivec.api.ObjectiveCTokenType; +import org.sonar.squidbridge.SquidAstVisitor; + +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.List; +import java.util.Map; + +public class SyntaxHighlighterVisitor extends SquidAstVisitor implements AstAndTokenVisitor { + private static final Map TYPES; + + static { + ImmutableMap.Builder typesBuilder = ImmutableMap.builder(); + // Add grammar types to highlight here + TYPES = typesBuilder.build(); + } + + private final SonarComponents sonarComponents; + private final Charset charset; + + private Highlightable.HighlightingBuilder highlighting; + private List lineStart; + + public SyntaxHighlighterVisitor(SonarComponents sonarComponents, Charset charset) { + this.sonarComponents = Preconditions.checkNotNull(sonarComponents); + this.charset = charset; + } + + @Override + public void init() { + for (AstNodeType type : TYPES.keySet()) { + subscribeTo(type); + } + } + + @Override + public void visitFile(AstNode astNode) { + if (astNode == null) { + // parse error + return; + } + + InputFile inputFile = sonarComponents.inputFileFor(getContext().getFile()); + Preconditions.checkNotNull(inputFile); + highlighting = sonarComponents.highlightableFor(inputFile).newHighlighting(); + + lineStart = Lists.newArrayList(); + final String content; + try { + content = Files.toString(getContext().getFile(), charset); + } catch (IOException e) { + throw Throwables.propagate(e); + } + lineStart.add(0); + for (int i = 0; i < content.length(); i++) { + if (content.charAt(i) == '\n' || (content.charAt(i) == '\r' && i + 1 < content.length() && content.charAt(i + 1) != '\n')) { + lineStart.add(i + 1); + } + } + } + + @Override + public void visitNode(AstNode astNode) { + highlighting.highlight(astNode.getFromIndex(), astNode.getToIndex(), TYPES.get(astNode.getType())); + } + + @Override + public void visitToken(Token token) { + // Use org.sonar.api.batch.sensor.highlighting.TypeOfText here? + + for (Trivia trivia : token.getTrivia()) { + if (trivia.isComment()) { + Token triviaToken = trivia.getToken(); + if (triviaToken.getValue().startsWith("/**")) { + highlightToken(triviaToken, "j"); + } else if (triviaToken.getValue().startsWith("/*")) { + highlightToken(triviaToken, "cppd"); + } else { + highlightToken(triviaToken, "cd"); + } + } + } + + if (token.getType() instanceof ObjectiveCKeyword) { + highlightToken(token, "k"); + } + + if (ObjectiveCTokenType.numberLiterals().contains(token.getType())) { + highlightToken(token, "c"); + } + + if (ObjectiveCTokenType.STRING_LITERAL.equals(token.getType()) + || ObjectiveCTokenType.CHARACTER_LITERAL.equals(token.getType())) { + highlightToken(token, "s"); + } + } + + private void highlightToken(Token token, String typeOfText) { + int offset = getOffset(token.getLine(), token.getColumn()); + highlighting.highlight(offset, offset + token.getValue().length(), typeOfText); + } + + /** + * @param line starts from 1 + * @param column starts from 0 + */ + private int getOffset(int line, int column) { + return lineStart.get(line - 1) + column; + } + + @Override + public void leaveFile(AstNode astNode) { + if (astNode == null) { + // parse error + return; + } + highlighting.done(); + } +} diff --git a/objective-c-squid/src/main/java/org/sonar/objectivec/highlighter/package-info.java b/objective-c-squid/src/main/java/org/sonar/objectivec/highlighter/package-info.java new file mode 100644 index 00000000..0d67a3fd --- /dev/null +++ b/objective-c-squid/src/main/java/org/sonar/objectivec/highlighter/package-info.java @@ -0,0 +1,23 @@ +/* + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +@ParametersAreNonnullByDefault +package org.sonar.objectivec.highlighter; + +import javax.annotation.ParametersAreNonnullByDefault; \ No newline at end of file diff --git a/objective-c-squid/src/main/java/org/sonar/objectivec/lexer/BackslashChannel.java b/objective-c-squid/src/main/java/org/sonar/objectivec/lexer/BackslashChannel.java new file mode 100644 index 00000000..4bdaf728 --- /dev/null +++ b/objective-c-squid/src/main/java/org/sonar/objectivec/lexer/BackslashChannel.java @@ -0,0 +1,46 @@ +/* + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.objectivec.lexer; + +import com.sonar.sslr.impl.Lexer; +import org.sonar.sslr.channel.Channel; +import org.sonar.sslr.channel.CodeReader; + +/** + * @author Sonar C++ Plugin (Community) authors + */ +public class BackslashChannel extends Channel { + @Override + public boolean consume(CodeReader code, Lexer output) { + char ch = (char) code.peek(); + + if ((ch == '\\') && isNewLine(code.charAt(1))) { + // just throw away the backslash + code.pop(); + return true; + } + + return false; + } + + private static boolean isNewLine(char ch) { + return (ch == '\n') || (ch == '\r'); + } +} diff --git a/objective-c-squid/src/main/java/org/sonar/objectivec/lexer/CharacterLiteralsChannel.java b/objective-c-squid/src/main/java/org/sonar/objectivec/lexer/CharacterLiteralsChannel.java new file mode 100644 index 00000000..bb3c603a --- /dev/null +++ b/objective-c-squid/src/main/java/org/sonar/objectivec/lexer/CharacterLiteralsChannel.java @@ -0,0 +1,114 @@ +/* + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.objectivec.lexer; + +import com.sonar.sslr.api.Token; +import com.sonar.sslr.impl.Lexer; +import org.sonar.objectivec.api.ObjectiveCTokenType; +import org.sonar.sslr.channel.Channel; +import org.sonar.sslr.channel.CodeReader; + +/** + * @author Sonar C++ Plugin (Community) authors + */ +public class CharacterLiteralsChannel extends Channel { + private static final char EOF = (char) -1; + + private final StringBuilder sb = new StringBuilder(); + + private int index; + private char ch; + + @Override + public boolean consume(CodeReader code, Lexer output) { + int line = code.getLinePosition(); + int column = code.getColumnPosition(); + index = 0; + readPrefix(code); + if ((ch != '\'')) { + return false; + } + if (!read(code)) { + return false; + } + readUdSuffix(code); + for (int i = 0; i < index; i++) { + sb.append((char) code.pop()); + } + output.addToken(Token.builder() + .setLine(line) + .setColumn(column) + .setURI(output.getURI()) + .setValueAndOriginalValue(sb.toString()) + .setType(ObjectiveCTokenType.CHARACTER_LITERAL) + .build()); + sb.setLength(0); + return true; + } + + private boolean read(CodeReader code) { + index++; + while (code.charAt(index) != ch) { + if (code.charAt(index) == EOF) { + return false; + } + if (code.charAt(index) == '\\') { + // escape + index++; + } + index++; + } + index++; + return true; + } + + private void readPrefix(CodeReader code) { + ch = code.charAt(index); + if ((ch == 'u') || (ch == 'U') || ch == 'L') { + index++; + ch = code.charAt(index); + } + } + + private void readUdSuffix(CodeReader code) { + for (int start_index = index, len = 0; ; index++) { + char c = code.charAt(index); + if (c == EOF) { + return; + } + if ((c >= 'a' && c <= 'z') + || (c >= 'A' && c <= 'Z') + || (c == '_')) { + len++; + } else { + if (c >= '0' && c <= '9') { + if (len > 0) { + len++; + } else { + index = start_index; + return; + } + } else { + return; + } + } + } + } +} diff --git a/objective-c-squid/src/main/java/org/sonar/objectivec/lexer/ObjectiveCLexer.java b/objective-c-squid/src/main/java/org/sonar/objectivec/lexer/ObjectiveCLexer.java new file mode 100644 index 00000000..4d97e16c --- /dev/null +++ b/objective-c-squid/src/main/java/org/sonar/objectivec/lexer/ObjectiveCLexer.java @@ -0,0 +1,103 @@ +/* + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.objectivec.lexer; + +import com.sonar.sslr.api.GenericTokenType; +import com.sonar.sslr.impl.Lexer; +import com.sonar.sslr.impl.channel.BlackHoleChannel; +import com.sonar.sslr.impl.channel.IdentifierAndKeywordChannel; +import com.sonar.sslr.impl.channel.PunctuatorChannel; +import org.sonar.objectivec.ObjectiveCConfiguration; +import org.sonar.objectivec.api.ObjectiveCKeyword; +import org.sonar.objectivec.api.ObjectiveCPunctuator; + +import static com.sonar.sslr.impl.channel.RegexpChannelBuilder.commentRegexp; +import static com.sonar.sslr.impl.channel.RegexpChannelBuilder.regexp; +import static org.sonar.objectivec.api.ObjectiveCTokenType.DOUBLE_LITERAL; +import static org.sonar.objectivec.api.ObjectiveCTokenType.FLOAT_LITERAL; +import static org.sonar.objectivec.api.ObjectiveCTokenType.INTEGER_LITERAL; +import static org.sonar.objectivec.api.ObjectiveCTokenType.LONG_LITERAL; + +public class ObjectiveCLexer { + private static final String EXP_REGEXP = "(?:[Ee][+-]?+[0-9_]++)"; + private static final String BINARY_EXP_REGEXP = "(?:[Pp][+-]?+[0-9_]++)"; + private static final String FLOATING_LITERAL_WITHOUT_SUFFIX_REGEXP = "(?:" + + // Decimal + "[0-9][0-9_]*+\\.([0-9_]++)?+" + EXP_REGEXP + "?+" + + "|" + "\\.[0-9][0-9_]*+" + EXP_REGEXP + "?+" + + "|" + "[0-9][0-9_]*+" + EXP_REGEXP + + // Hexadecimal + "|" + "0[xX][0-9_a-fA-F]++\\.[0-9_a-fA-F]*+" + BINARY_EXP_REGEXP + + "|" + "0[xX][0-9_a-fA-F]++" + BINARY_EXP_REGEXP + + ")"; + private static final String INTEGER_LITERAL_REGEXP = "(?:" + + // Hexadecimal + "0[xX][0-9_a-fA-F]++" + + // Binary (Java 7) + "|" + "0[bB][01_]++" + + // Decimal and Octal + "|" + "[0-9][0-9_]*+" + + ")"; + + private ObjectiveCLexer() { + // prevents outside instantiation + } + + public static Lexer create() { + return create(new ObjectiveCConfiguration()); + } + + public static Lexer create(ObjectiveCConfiguration conf) { + return Lexer.builder() + .withCharset(conf.getCharset()) + .withFailIfNoChannelToConsumeOneCharacter(true) + + /* Remove whitespace */ + .withChannel(new BlackHoleChannel("\\s++")) + + /* Comments */ + .withChannel(commentRegexp("//[^\\n\\r]*+")) + .withChannel(commentRegexp("/\\*", "[\\s\\S]*?", "\\*/")) + + /* Backslash at the end of the line: just throw away */ + .withChannel(new BackslashChannel()) + + /* Character literals */ + .withChannel(new CharacterLiteralsChannel()) + + /* String literals */ + .withChannel(new StringLiteralsChannel()) + + /* Number literals */ + .withChannel(regexp(FLOAT_LITERAL, FLOATING_LITERAL_WITHOUT_SUFFIX_REGEXP + "[fF]|[0-9][0-9_]*+[fF]")) + .withChannel(regexp(DOUBLE_LITERAL, FLOATING_LITERAL_WITHOUT_SUFFIX_REGEXP + "[dD]?+|[0-9][0-9_]*+[dD]")) + .withChannel(regexp(LONG_LITERAL, INTEGER_LITERAL_REGEXP + "[lL]")) + .withChannel(regexp(INTEGER_LITERAL, INTEGER_LITERAL_REGEXP)) + + /* Identifiers, keywords, and punctuators */ + .withChannel(new IdentifierAndKeywordChannel("[#@]?[a-zA-Z]([a-zA-Z0-9_]*[a-zA-Z0-9])?+((\\s+)?\\*)?", true, ObjectiveCKeyword.values())) + .withChannel(new PunctuatorChannel(ObjectiveCPunctuator.values())) + + /* All other tokens -- must be last channel */ + .withChannel(regexp(GenericTokenType.IDENTIFIER, "[^\r\n\\s/]+")) + + .build(); + } +} diff --git a/objective-c-squid/src/main/java/org/sonar/objectivec/lexer/StringLiteralsChannel.java b/objective-c-squid/src/main/java/org/sonar/objectivec/lexer/StringLiteralsChannel.java new file mode 100644 index 00000000..0ce6e785 --- /dev/null +++ b/objective-c-squid/src/main/java/org/sonar/objectivec/lexer/StringLiteralsChannel.java @@ -0,0 +1,165 @@ +/* + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.objectivec.lexer; + +import com.sonar.sslr.api.Token; +import com.sonar.sslr.impl.Lexer; +import org.sonar.objectivec.api.ObjectiveCTokenType; +import org.sonar.sslr.channel.Channel; +import org.sonar.sslr.channel.CodeReader; + +/** + * @author Sonar C++ Plugin (Community) authors + */ +public class StringLiteralsChannel extends Channel { + private static final char EOF = (char) -1; + + private final StringBuilder sb = new StringBuilder(); + + private int index; + private char ch; + private boolean isRawString = false; + + @Override + public boolean consume(CodeReader code, Lexer output) { + int line = code.getLinePosition(); + int column = code.getColumnPosition(); + index = 0; + readStringPrefix(code); + if ((ch != '\"')) { + return false; + } + if (isRawString) { + if (!readRawString(code)) { + return false; + } + } else { + if (!readString(code)) { + return false; + } + } + readUdSuffix(code); + for (int i = 0; i < index; i++) { + sb.append((char) code.pop()); + } + output.addToken(Token.builder() + .setLine(line) + .setColumn(column) + .setURI(output.getURI()) + .setValueAndOriginalValue(sb.toString()) + .setType(ObjectiveCTokenType.STRING_LITERAL) + .build()); + sb.setLength(0); + return true; + } + + private boolean readString(CodeReader code) { + index++; + while (code.charAt(index) != ch) { + if (code.charAt(index) == EOF) { + return false; + } + if (code.charAt(index) == '\\') { + // escape + index++; + } + index++; + } + index++; + return true; + } + + private boolean readRawString(CodeReader code) { + // "delimiter( raw_character* )delimiter" + index++; + while (code.charAt(index) != '(') { // delimiter + if (code.charAt(index) == EOF) { + return false; + } + sb.append(code.charAt(index)); + index++; + } + String delimiter = sb.toString(); + do { + sb.setLength(0); + while (code.charAt(index) != ')') { // raw_character* + if (code.charAt(index) == EOF) { + return false; + } + index++; + } + index++; + while (code.charAt(index) != '"') { // delimiter + if (code.charAt(index) == EOF) { + return false; + } + sb.append(code.charAt(index)); + index++; + } + } while (!sb.toString().equals(delimiter)); + sb.setLength(0); + index++; + return true; + } + + private void readStringPrefix(CodeReader code) { + ch = code.charAt(index); + isRawString = false; + if ((ch == 'u') || (ch == 'U') || ch == 'L' || ch == '@') { + index++; + if (ch == 'u' && code.charAt(index) == '8') { + index++; + } + if (code.charAt(index) == ' ') + index++; + ch = code.charAt(index); + } + if (ch == 'R') { + index++; + isRawString = true; + ch = code.charAt(index); + } + } + + private void readUdSuffix(CodeReader code) { + for (int start_index = index, len = 0; ; index++) { + char c = code.charAt(index); + if (c == EOF) { + return; + } + if ((c >= 'a' && c <= 'z') + || (c >= 'A' && c <= 'Z') + || (c == '_')) { + len++; + } else { + if (c >= '0' && c <= '9') { + if (len > 0) { + len++; + } else { + index = start_index; + return; + } + } else { + return; + } + } + } + } +} diff --git a/objective-c-squid/src/main/java/org/sonar/objectivec/lexer/package-info.java b/objective-c-squid/src/main/java/org/sonar/objectivec/lexer/package-info.java new file mode 100644 index 00000000..fb8724fa --- /dev/null +++ b/objective-c-squid/src/main/java/org/sonar/objectivec/lexer/package-info.java @@ -0,0 +1,23 @@ +/* + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +@ParametersAreNonnullByDefault +package org.sonar.objectivec.lexer; + +import javax.annotation.ParametersAreNonnullByDefault; \ No newline at end of file diff --git a/objective-c-squid/src/main/java/org/sonar/objectivec/package-info.java b/objective-c-squid/src/main/java/org/sonar/objectivec/package-info.java new file mode 100644 index 00000000..424a3dbb --- /dev/null +++ b/objective-c-squid/src/main/java/org/sonar/objectivec/package-info.java @@ -0,0 +1,23 @@ +/* + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +@ParametersAreNonnullByDefault +package org.sonar.objectivec; + +import javax.annotation.ParametersAreNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/org/sonar/objectivec/parser/ObjectiveCParser.java b/objective-c-squid/src/main/java/org/sonar/objectivec/parser/ObjectiveCParser.java similarity index 56% rename from src/main/java/org/sonar/objectivec/parser/ObjectiveCParser.java rename to objective-c-squid/src/main/java/org/sonar/objectivec/parser/ObjectiveCParser.java index 6f0d2c19..3fbda558 100644 --- a/src/main/java/org/sonar/objectivec/parser/ObjectiveCParser.java +++ b/objective-c-squid/src/main/java/org/sonar/objectivec/parser/ObjectiveCParser.java @@ -1,7 +1,7 @@ /* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,32 +13,32 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.objectivec.parser; +import com.sonar.sslr.api.Grammar; +import com.sonar.sslr.impl.Parser; import org.sonar.objectivec.ObjectiveCConfiguration; import org.sonar.objectivec.api.ObjectiveCGrammar; import org.sonar.objectivec.lexer.ObjectiveCLexer; -import com.sonar.sslr.impl.Parser; -import com.sonar.sslr.impl.events.ParsingEventListener; - public class ObjectiveCParser { private ObjectiveCParser() { + // Prevent outside instantiation } - public static Parser create(ParsingEventListener... parsingEventListeners) { - return create(new ObjectiveCConfiguration(), parsingEventListeners); + public static Parser create() { + return create(new ObjectiveCConfiguration()); } - public static Parser create(ObjectiveCConfiguration conf, ParsingEventListener... parsingEventListeners) { - return Parser.builder((ObjectiveCGrammar) new ObjectiveCGrammarImpl()) + public static Parser create(ObjectiveCConfiguration conf) { + return Parser.builder(ObjectiveCGrammar.create()) .withLexer(ObjectiveCLexer.create(conf)) - .setParsingEventListeners(parsingEventListeners).build(); + .build(); } } diff --git a/src/main/java/org/sonar/objectivec/parser/ObjectiveCGrammarImpl.java b/objective-c-squid/src/main/java/org/sonar/objectivec/parser/package-info.java similarity index 50% rename from src/main/java/org/sonar/objectivec/parser/ObjectiveCGrammarImpl.java rename to objective-c-squid/src/main/java/org/sonar/objectivec/parser/package-info.java index 14bb779f..4b22d0b6 100644 --- a/src/main/java/org/sonar/objectivec/parser/ObjectiveCGrammarImpl.java +++ b/objective-c-squid/src/main/java/org/sonar/objectivec/parser/package-info.java @@ -1,7 +1,7 @@ /* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,24 +13,11 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +@ParametersAreNonnullByDefault package org.sonar.objectivec.parser; -import static com.sonar.sslr.api.GenericTokenType.EOF; -import static com.sonar.sslr.api.GenericTokenType.LITERAL; -import static com.sonar.sslr.impl.matcher.GrammarFunctions.Standard.o2n; - -import org.sonar.objectivec.api.ObjectiveCGrammar; - -public class ObjectiveCGrammarImpl extends ObjectiveCGrammar { - - public ObjectiveCGrammarImpl() { - - program.is(o2n(LITERAL), EOF); - - } - -} +import javax.annotation.ParametersAreNonnullByDefault; \ No newline at end of file diff --git a/src/test/java/org/sonar/objectivec/ObjectiveCAstScannerTest.java b/objective-c-squid/src/test/java/org/sonar/objectivec/ObjectiveCAstScannerTest.java similarity index 84% rename from src/test/java/org/sonar/objectivec/ObjectiveCAstScannerTest.java rename to objective-c-squid/src/test/java/org/sonar/objectivec/ObjectiveCAstScannerTest.java index ea40f1f6..2988862a 100644 --- a/src/test/java/org/sonar/objectivec/ObjectiveCAstScannerTest.java +++ b/objective-c-squid/src/test/java/org/sonar/objectivec/ObjectiveCAstScannerTest.java @@ -1,7 +1,7 @@ /* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +13,9 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.objectivec; diff --git a/src/test/java/org/sonar/objectivec/api/ObjectiveCPunctuatorTest.java b/objective-c-squid/src/test/java/org/sonar/objectivec/api/ObjectiveCPunctuatorTest.java similarity index 68% rename from src/test/java/org/sonar/objectivec/api/ObjectiveCPunctuatorTest.java rename to objective-c-squid/src/test/java/org/sonar/objectivec/api/ObjectiveCPunctuatorTest.java index 052b19c2..8fac9bb1 100644 --- a/src/test/java/org/sonar/objectivec/api/ObjectiveCPunctuatorTest.java +++ b/objective-c-squid/src/test/java/org/sonar/objectivec/api/ObjectiveCPunctuatorTest.java @@ -1,7 +1,7 @@ /* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +13,9 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.objectivec.api; @@ -28,7 +28,7 @@ public class ObjectiveCPunctuatorTest { @Test public void test() { - assertThat(ObjectiveCPunctuator.values().length, is(48)); + assertThat(ObjectiveCPunctuator.values().length, is(49)); } } diff --git a/src/test/java/org/sonar/objectivec/lexer/ObjectiveCLexerTest.java b/objective-c-squid/src/test/java/org/sonar/objectivec/lexer/ObjectiveCLexerTest.java similarity index 82% rename from src/test/java/org/sonar/objectivec/lexer/ObjectiveCLexerTest.java rename to objective-c-squid/src/test/java/org/sonar/objectivec/lexer/ObjectiveCLexerTest.java index 080c41cf..80fb27f7 100644 --- a/src/test/java/org/sonar/objectivec/lexer/ObjectiveCLexerTest.java +++ b/objective-c-squid/src/test/java/org/sonar/objectivec/lexer/ObjectiveCLexerTest.java @@ -1,7 +1,7 @@ /* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org + * SonarQube Objective-C (Community) :: Squid + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +13,9 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.objectivec.lexer; @@ -33,6 +33,7 @@ import com.sonar.sslr.api.GenericTokenType; import com.sonar.sslr.api.Token; import com.sonar.sslr.impl.Lexer; +import org.sonar.objectivec.api.ObjectiveCKeyword; public class ObjectiveCLexerTest { @@ -63,7 +64,7 @@ public void lexEndOflineComment() { @Test public void lexLineOfCode() { - assertThat(lexer.lex("[self init];"), hasToken("[self", GenericTokenType.LITERAL)); + assertThat(lexer.lex("[self init];"), hasToken("self", ObjectiveCKeyword.SELF)); } @Test @@ -76,7 +77,7 @@ public void lexEmptyLine() { @Test public void lexSampleFile() { List tokens = lexer.lex(new File("src/test/resources/objcSample.h")); - assertThat(tokens.size(), equalTo(16)); + assertThat(tokens.size(), equalTo(26)); assertThat(tokens, hasToken(GenericTokenType.EOF)); } diff --git a/src/test/resources/Profile.m b/objective-c-squid/src/test/resources/Profile.m similarity index 100% rename from src/test/resources/Profile.m rename to objective-c-squid/src/test/resources/Profile.m diff --git a/src/test/resources/objcSample.h b/objective-c-squid/src/test/resources/objcSample.h similarity index 100% rename from src/test/resources/objcSample.h rename to objective-c-squid/src/test/resources/objcSample.h diff --git a/pom.xml b/pom.xml index 8cf7bd1e..ab48fc98 100644 --- a/pom.xml +++ b/pom.xml @@ -2,40 +2,22 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - - - sonar - http://repository.sonarsource.org/content/repositories/sonar - - - - - - sonar - http://repository.sonarsource.org/content/repositories/sonar - - - - org.codehaus.sonar-plugins + org.sonarsource.parent parent - 18 + 29 - org.codehaus.sonar-plugin.objectivec - sonar-objective-c-plugin - 0.4.0 - - sonar-plugin - - Objective-C Sonar Plugin - Enables analysis of Objective-C projects into Sonar. - https://github.com/octo-technology/sonar-objective-c - + org.sonarqubecommunity.objectivec + objective-c + 0.5.0-SNAPSHOT + pom + SonarQube Objective-C (Community) 2012 - OCTO Technology + OCTO Technology, Backelite, and contributors + mailto:sonarqube@googlegroups.com @@ -45,6 +27,13 @@ + + objective-c-squid + sonar-objective-c-plugin + sslr-objective-c-toolkit + its + + cyrilpicat @@ -56,11 +45,11 @@ Gilles Grousset https://github.com/zippy1978 - + dbregeon Denis Bregeon Incept5 LLC - + fhelg François Helg @@ -77,112 +66,106 @@ Mete Balci https://github.com/metebalci + + agh92 + Andrés Gil Herrera + https://github.com/agh92 + + + mjdetullio + Matthew DeTullio + https://github.com/mjdetullio + + - scm:git:git@github.com:octo-technology/sonar-objective-c.git - scm:git:git@github.com:octo-technology/sonar-objective-c.git - https://github.com/octo-technology/sonar-objective-c + scm:git:git@github.com:mjdetullio/sonar-objective-c.git + scm:git:git@github.com:mjdetullio/sonar-objective-c.git + https://github.com/mjdetullio/sonar-objective-c + + GitHub + https://github.com/mjdetullio/sonar-objective-c/issues + + - Cloudbees - https://rfelden.ci.cloudbees.com/job/sonar-objective-c/ + Travis CI + https://travis-ci.org/mjdetullio/sonar-objective-c - OCTO Technology - Sonar Objective-C Plugin - - true - - 4.3 - 1.20 - - - org.sonar.plugins.objectivec.ObjectiveCPlugin - ObjectiveC - + ${project.organization.name} + ${project.organization.url} + 4.5.2 + 1.21 + 3.10.1 - - - org.codehaus.sonar - sonar-plugin-api - ${sonar.version} - - - org.codehaus.sonar - sonar-testing-harness - ${sonar.version} - - - org.codehaus.sonar - sonar-deprecated - ${sonar.version} - - - - org.codehaus.sonar.sslr - sslr-core - ${sslr.version} - - - org.codehaus.sonar.sslr - sslr-xpath - ${sslr.version} - - - org.codehaus.sonar.sslr - sslr-toolkit - ${sslr.version} - - - org.codehaus.sonar.sslr - sslr-testing-harness - ${sslr.version} - - - org.codehaus.sonar.sslr-squid-bridge - sslr-squid-bridge - 2.4 - - - ant - ant - 1.6 - - - - junit - junit - 4.10 - - - org.mockito - mockito-all - 1.9.0 - - - org.hamcrest - hamcrest-all - 1.1 - - - org.easytesting - fest-assert - 1.4 - - - ch.qos.logback - logback-classic - 0.9.30 - - - org.codehaus.sonar.plugins - sonar-surefire-plugin - 2.7 - - - - + + + + org.codehaus.sonar + sonar-plugin-api + ${sonar.version} + provided + + + org.sonarsource.sslr + sslr-core + ${sslr.version} + + + org.sonarsource.sslr + sslr-xpath + ${sslr.version} + + + org.sonarsource.sslr + sslr-toolkit + ${sslr.version} + + + org.sonarsource.sslr-squid-bridge + sslr-squid-bridge + 2.6.1 + + + com.googlecode.plist + dd-plist + 1.16 + + + + org.codehaus.sonar + sonar-testing-harness + ${sonar.version} + test + + + org.sonarsource.sslr + sslr-testing-harness + ${sslr.version} + test + + + junit + junit + 4.12 + test + + + org.easytesting + fest-assert + 1.4 + test + + + ch.qos.logback + logback-classic + 1.1.3 + test + + + diff --git a/sample/screen shot SonarQube dashboard.png b/sample/screen shot SonarQube dashboard.png deleted file mode 100644 index c2b72a7c..00000000 Binary files a/sample/screen shot SonarQube dashboard.png and /dev/null differ diff --git a/sample/sonar-project.properties b/sample/sonar-project.properties deleted file mode 100644 index 41ed559f..00000000 --- a/sample/sonar-project.properties +++ /dev/null @@ -1,58 +0,0 @@ -########################## -# Required configuration # -########################## - -sonar.projectKey=my-project -sonar.projectName=My project -sonar.projectVersion=1.0 -sonar.language=objc - -# Project description -sonar.projectDescription=Fake description - -# Path to source directories -sonar.sources=srcDir1,srcDir2 -# Path to test directories (comment if no test) -sonar.tests=testSrcDir - - -# Xcode project configuration (.xcodeproj or .xcworkspace) -# -> If you have a project: configure only sonar.objectivec.project -# -> If you have a workspace: configure sonar.objectivec.workspace and sonar.objectivec.project -# and use the later to specify which project(s) to include in the analysis (comma separated list) -sonar.objectivec.project=myApplication.xcodeproj -# sonar.objectivec.workspace=myApplication.xcworkspace - -# Scheme to build your application -sonar.objectivec.appScheme=myApplication -# Scheme to build and run your tests (comment following line of you don't have any tests) -sonar.objectivec.testScheme=myApplicationTests - -########################## -# Optional configuration # -########################## - -# Encoding of the source code -sonar.sourceEncoding=UTF-8 - -# JUnit report generated by run-sonar.sh is stored in sonar-reports/TEST-report.xml -# Change it only if you generate the file on your own -# The XML files have to be prefixed by TEST- otherwise they are not processed -# sonar.junit.reportsPath=sonar-reports/ - -# Cobertura report generated by run-sonar.sh is stored in sonar-reports/coverage.xml -# Change it only if you generate the file on your own -# sonar.objectivec.coverage.reportPattern=sonar-reports/coverage*.xml - -# OCLint report generated by run-sonar.sh is stored in sonar-reports/oclint.xml -# Change it only if you generate the file on your own -# sonar.objectivec.oclint.report=sonar-reports/oclint.xml - -# Paths to exclude from coverage report (tests, 3rd party libraries etc.) -# sonar.objectivec.excludedPathsFromCoverage=pattern1,pattern2 -sonar.objectivec.excludedPathsFromCoverage=.*Tests.* - -# Project SCM settings -# sonar.scm.enabled=true -# sonar.scm.url=scm:git:https://... - diff --git a/sonar-objective-c-plugin/pom.xml b/sonar-objective-c-plugin/pom.xml new file mode 100644 index 00000000..7063dc7e --- /dev/null +++ b/sonar-objective-c-plugin/pom.xml @@ -0,0 +1,63 @@ + + 4.0.0 + + + org.sonarqubecommunity.objectivec + objective-c + 0.5.0-SNAPSHOT + + + sonar-objective-c-plugin + sonar-plugin + + SonarQube Objective-C (Community) Plugin + Enable analysis and reporting on Objective-C projects. + https://github.com/mjdetullio/sonar-objective-c + + + true + + + org.sonar.plugins.objectivec.ObjectiveCPlugin + Objective-C (Community) + + + + + org.codehaus.sonar + sonar-plugin-api + provided + + + ${project.groupId} + objective-c-squid + ${project.version} + + + com.googlecode.plist + dd-plist + + + + org.codehaus.sonar + sonar-testing-harness + test + + + junit + junit + test + + + org.easytesting + fest-assert + test + + + ch.qos.logback + logback-classic + test + + + diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/ObjectiveCPlugin.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/ObjectiveCPlugin.java new file mode 100644 index 00000000..6d4820e9 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/ObjectiveCPlugin.java @@ -0,0 +1,113 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec; + +import org.sonar.api.SonarPlugin; +import org.sonar.api.config.PropertyDefinition; +import org.sonar.api.resources.Qualifiers; +import org.sonar.plugins.objectivec.api.ObjectiveC; +import org.sonar.plugins.objectivec.clang.ClangProfile; +import org.sonar.plugins.objectivec.clang.ClangProfileImporter; +import org.sonar.plugins.objectivec.clang.ClangRulesDefinition; +import org.sonar.plugins.objectivec.clang.ClangSensor; +import org.sonar.plugins.objectivec.cobertura.CoberturaSensor; +import org.sonar.plugins.objectivec.cpd.ObjectiveCCpdMapping; +import org.sonar.plugins.objectivec.lizard.LizardRulesDefinition; +import org.sonar.plugins.objectivec.lizard.LizardSensor; +import org.sonar.plugins.objectivec.oclint.OCLintProfile; +import org.sonar.plugins.objectivec.oclint.OCLintProfileImporter; +import org.sonar.plugins.objectivec.oclint.OCLintRulesDefinition; +import org.sonar.plugins.objectivec.oclint.OCLintSensor; +import org.sonar.plugins.objectivec.surefire.SurefireSensor; + +import java.util.ArrayList; +import java.util.List; + +public class ObjectiveCPlugin extends SonarPlugin { + @Override + public List getExtensions() { + List extensions = new ArrayList<>(); + + extensions.add(ObjectiveC.class); + extensions.add(PropertyDefinition.builder(ObjectiveC.FILE_SUFFIXES_KEY) + .defaultValue(ObjectiveC.DEFAULT_FILE_SUFFIXES) + .name("File suffixes") + .description("Comma-separated list of suffixes for files to analyze. To not filter, leave the list empty.") + .onQualifiers(Qualifiers.PROJECT) + .build()); + + extensions.add(ObjectiveCCpdMapping.class); + + extensions.add(ObjectiveCSquidSensor.class); + extensions.add(ObjectiveCProfile.class); + + extensions.add(ClangRulesDefinition.class); + extensions.add(ClangSensor.class); + extensions.add(ClangProfile.class); + extensions.add(ClangProfileImporter.class); + extensions.add(PropertyDefinition.builder(ClangSensor.REPORTS_PATH_KEY) + .name("Clang Static Analyzer Reports") + .description("Path to the directory containing all the *.plist Clang report files. The path may be absolute or relative to the project base directory.") + .subCategory("Clang") + .onQualifiers(Qualifiers.PROJECT) + .build()); + + extensions.add(CoberturaSensor.class); + extensions.add(PropertyDefinition.builder(CoberturaSensor.REPORT_PATH_KEY) + .name("Report path") + .description("Path (absolute or relative) to Cobertura XML report file.") + .subCategory("Cobertura") + .onQualifiers(Qualifiers.PROJECT) + .build()); + + extensions.add(LizardSensor.class); + extensions.add(LizardRulesDefinition.class); + extensions.add(PropertyDefinition.builder(LizardSensor.REPORT_PATH_KEY) + .name("Report path") + .description("Path (absolute or relative) to Lizard XML report file.") + .subCategory("Complexity") + .onQualifiers(Qualifiers.PROJECT) + .build()); + + extensions.add(OCLintRulesDefinition.class); + extensions.add(OCLintSensor.class); + extensions.add(OCLintProfile.class); + extensions.add(OCLintProfileImporter.class); + extensions.add(PropertyDefinition.builder(OCLintSensor.REPORT_PATH_KEY) + .name("Report path") + .description("Path (absolute or relative) to OCLint PMD formatted XML report file.") + .subCategory("OCLint") + .onQualifiers(Qualifiers.PROJECT) + .build()); + + extensions.add(SurefireSensor.class); + extensions.add(PropertyDefinition.builder(SurefireSensor.REPORTS_PATH_KEY) + .name("JUnit Reports") + .description("Path to the directory containing all the *.xml JUnit report files. The path may be absolute or relative to the project base directory.

" + + "Extra logic has been added to search your test sources for each classname that is defined in the JUnit report.

" + + "Classes will attempt to match the pattern: **/${classname}.m") + .subCategory("JUnit") + .onQualifiers(Qualifiers.PROJECT) + .build()); + + return extensions; + } + +} diff --git a/src/main/java/org/sonar/plugins/objectivec/ObjectiveCProfile.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/ObjectiveCProfile.java similarity index 79% rename from src/main/java/org/sonar/plugins/objectivec/ObjectiveCProfile.java rename to sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/ObjectiveCProfile.java index e223a48c..376eb542 100644 --- a/src/main/java/org/sonar/plugins/objectivec/ObjectiveCProfile.java +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/ObjectiveCProfile.java @@ -1,7 +1,7 @@ /* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,9 +13,9 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plugins.objectivec; @@ -24,7 +24,7 @@ import org.sonar.api.profiles.RulesProfile; import org.sonar.api.utils.ValidationMessages; import org.sonar.objectivec.checks.CheckList; -import org.sonar.plugins.objectivec.core.ObjectiveC; +import org.sonar.plugins.objectivec.api.ObjectiveC; public class ObjectiveCProfile extends ProfileDefinition { diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/ObjectiveCSquidSensor.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/ObjectiveCSquidSensor.java new file mode 100644 index 00000000..d9c03ee8 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/ObjectiveCSquidSensor.java @@ -0,0 +1,179 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; +import com.sonar.sslr.api.Grammar; +import org.sonar.api.batch.Sensor; +import org.sonar.api.batch.SensorContext; +import org.sonar.api.batch.fs.FilePredicate; +import org.sonar.api.batch.fs.FileSystem; +import org.sonar.api.batch.fs.InputFile; +import org.sonar.api.batch.rule.CheckFactory; +import org.sonar.api.batch.rule.Checks; +import org.sonar.api.component.ResourcePerspectives; +import org.sonar.api.issue.Issuable; +import org.sonar.api.issue.Issuable.IssueBuilder; +import org.sonar.api.measures.CoreMetrics; +import org.sonar.api.resources.Project; +import org.sonar.api.resources.Resource; +import org.sonar.api.rule.RuleKey; +import org.sonar.api.scan.filesystem.PathResolver; +import org.sonar.objectivec.ObjectiveCAstScanner; +import org.sonar.objectivec.ObjectiveCConfiguration; +import org.sonar.objectivec.api.ObjectiveCMetric; +import org.sonar.objectivec.checks.CheckList; +import org.sonar.objectivec.highlighter.SonarComponents; +import org.sonar.plugins.objectivec.api.ObjectiveC; +import org.sonar.squidbridge.AstScanner; +import org.sonar.squidbridge.SquidAstVisitor; +import org.sonar.squidbridge.api.CheckMessage; +import org.sonar.squidbridge.api.SourceCode; +import org.sonar.squidbridge.api.SourceFile; +import org.sonar.squidbridge.checks.SquidCheck; +import org.sonar.squidbridge.indexer.QueryByType; + +import javax.annotation.Nullable; +import java.io.File; +import java.util.Collection; +import java.util.List; +import java.util.Locale; + + +public class ObjectiveCSquidSensor implements Sensor { + private SensorContext context; + + private final Checks> checks; + private final FileSystem fileSystem; + private final FilePredicate mainFilePredicates; + private final PathResolver pathResolver; + private final ResourcePerspectives resourcePerspectives; + + public ObjectiveCSquidSensor(CheckFactory checkFactory, FileSystem fileSystem, + ResourcePerspectives resourcePerspectives, PathResolver pathResolver) { + this.checks = checkFactory + .>create(CheckList.REPOSITORY_KEY) + .addAnnotatedChecks(CheckList.getChecks()); + this.fileSystem = fileSystem; + this.mainFilePredicates = fileSystem.predicates().and( + fileSystem.predicates().hasLanguage(ObjectiveC.KEY), + fileSystem.predicates().hasType(InputFile.Type.MAIN)); + this.pathResolver = pathResolver; + this.resourcePerspectives = resourcePerspectives; + } + + @Override + public boolean shouldExecuteOnProject(Project project) { + return project.isRoot() && fileSystem.hasFiles(fileSystem.predicates().hasLanguage(ObjectiveC.KEY)); + } + + @Override + public void analyse(Project project, SensorContext context) { + this.context = context; + + List> visitors = Lists.>newArrayList(checks.all()); + + @SuppressWarnings("unchecked") AstScanner scanner = ObjectiveCAstScanner.create( + createConfiguration(), new SonarComponents(resourcePerspectives, fileSystem), + visitors.toArray(new SquidAstVisitor[visitors.size()])); + + scanner.scanFiles(ImmutableList.copyOf(fileSystem.files(mainFilePredicates))); + + Collection squidSourceFiles = scanner.getIndex().search(new QueryByType(SourceFile.class)); + save(squidSourceFiles); + } + + private ObjectiveCConfiguration createConfiguration() { + return new ObjectiveCConfiguration(fileSystem.encoding()); + } + + private void save(Collection squidSourceFiles) { + for (SourceCode squidSourceFile : squidSourceFiles) { + SourceFile squidFile = (SourceFile) squidSourceFile; + + String relativePath = pathResolver.relativePath(fileSystem.baseDir(), new File(squidFile.getKey())); + InputFile inputFile = fileSystem.inputFile(fileSystem.predicates().hasRelativePath(relativePath)); + + /* + * Distribution is saved in the Lizard sensor and therefore it is not possible to save the complexity + * distribution here. The functionality has been moved to LizardParser. + */ + //saveFilesComplexityDistribution(sonarFile, squidFile); + //saveFunctionsComplexityDistribution(sonarFile, squidFile); + saveMeasures(inputFile, squidFile); + saveViolations(inputFile, squidFile); + } + } + + private void saveMeasures(InputFile inputFile, SourceFile squidFile) { + context.saveMeasure(inputFile, CoreMetrics.FILES, squidFile.getDouble(ObjectiveCMetric.FILES)); + context.saveMeasure(inputFile, CoreMetrics.LINES, squidFile.getDouble(ObjectiveCMetric.LINES)); + context.saveMeasure(inputFile, CoreMetrics.NCLOC, squidFile.getDouble(ObjectiveCMetric.LINES_OF_CODE)); + context.saveMeasure(inputFile, CoreMetrics.COMMENT_LINES, squidFile.getDouble(ObjectiveCMetric.COMMENT_LINES)); + /* + * Not implemented + */ + //context.saveMeasure(inputFile, CoreMetrics.CLASSES, squidFile.getDouble(ObjectiveCMetric.CLASSES)); + //context.saveMeasure(inputFile, CoreMetrics.STATEMENTS, squidFile.getDouble(ObjectiveCMetric.STATEMENTS)); + /* + * Saving the same measure more than once per file throws exception. That is why + * CoreMetrics.FUNCTIONS and CoreMetrics.COMPLEXITY are not allowed to be saved here. In order for the + * LizardSensor to be able to to its job and save the values for those metrics the functionality has been + * moved to Lizard classes. + */ + //context.saveMeasure(inputFile, CoreMetrics.FUNCTIONS, squidFile.getDouble(ObjectiveCMetric.FUNCTIONS)); + //context.saveMeasure(inputFile, CoreMetrics.COMPLEXITY, squidFile.getDouble(ObjectiveCMetric.COMPLEXITY)); + } + + private void saveViolations(@Nullable InputFile inputFile, SourceFile squidFile) { + Collection messages = squidFile.getCheckMessages(); + + final Resource resource = inputFile == null ? null : context.getResource(inputFile); + + if (messages != null && resource != null) { + for (CheckMessage message : messages) { + @SuppressWarnings("unchecked") RuleKey ruleKey = + checks.ruleKey((SquidCheck) message.getCheck()); + + Issuable issuable = resourcePerspectives.as(Issuable.class, resource); + + if (issuable != null) { + IssueBuilder issueBuilder = issuable.newIssueBuilder() + .ruleKey(ruleKey) + .line(message.getLine()) + .message(message.getText(Locale.ENGLISH)); + + if (message.getCost() != null) { + issueBuilder.effortToFix(message.getCost()); + } + + issuable.addIssue(issueBuilder.build()); + } + } + } + } + + @Override + public String toString() { + return "Objective-C Squid Sensor"; + } + +} diff --git a/src/main/java/org/sonar/plugins/objectivec/core/ObjectiveC.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/api/ObjectiveC.java similarity index 51% rename from src/main/java/org/sonar/plugins/objectivec/core/ObjectiveC.java rename to sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/api/ObjectiveC.java index 25e3904d..08c8cea2 100644 --- a/src/main/java/org/sonar/plugins/objectivec/core/ObjectiveC.java +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/api/ObjectiveC.java @@ -1,7 +1,7 @@ /* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,37 +13,58 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -package org.sonar.plugins.objectivec.core; - -import java.util.List; +package org.sonar.plugins.objectivec.api; +import com.google.common.collect.Lists; import org.apache.commons.lang.StringUtils; import org.sonar.api.config.Settings; import org.sonar.api.resources.AbstractLanguage; -import org.sonar.plugins.objectivec.ObjectiveCPlugin; -import com.google.common.collect.Lists; +import java.util.List; public class ObjectiveC extends AbstractLanguage { - public static final String KEY = "objc"; + /** + * Objective-C key + */ + public static final String KEY = "objectivec"; + + /** + * Objective-C name + */ + public static final String NAME = "Objective-C (Community)"; + + /** + * Key of the file suffix parameter + */ + public static final String FILE_SUFFIXES_KEY = "sonar.objectivec.file.suffixes"; + + /** + * Default Java files knows suffixes + */ + public static final String DEFAULT_FILE_SUFFIXES = ".h,.m"; private Settings settings; + /** + * Default constructor + * + * @param settings Injected project batch and global server settings + */ public ObjectiveC(Settings settings) { - - super(KEY, "Objective-C"); + super(KEY, NAME); this.settings = settings; } + @Override public String[] getFileSuffixes() { - String[] suffixes = filterEmptyStrings(settings.getStringArray(ObjectiveCPlugin.FILE_SUFFIXES_KEY)); - if (suffixes == null || suffixes.length == 0) { - suffixes = StringUtils.split(ObjectiveCPlugin.FILE_SUFFIXES_DEFVALUE, ","); + String[] suffixes = filterEmptyStrings(settings.getStringArray(ObjectiveC.FILE_SUFFIXES_KEY)); + if (suffixes.length == 0) { + suffixes = StringUtils.split(ObjectiveC.DEFAULT_FILE_SUFFIXES, ","); } return suffixes; } @@ -51,10 +72,10 @@ public String[] getFileSuffixes() { private String[] filterEmptyStrings(String[] stringArray) { List nonEmptyStrings = Lists.newArrayList(); for (String string : stringArray) { - if (StringUtils.isNotBlank(string.trim())) { - nonEmptyStrings.add(string.trim()); - } + if (StringUtils.isNotBlank(string.trim())) { + nonEmptyStrings.add(string.trim()); + } } return nonEmptyStrings.toArray(new String[nonEmptyStrings.size()]); - } + } } diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/clang/ClangPlistParser.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/clang/ClangPlistParser.java new file mode 100644 index 00000000..05dbbd55 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/clang/ClangPlistParser.java @@ -0,0 +1,118 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec.clang; + +import com.dd.plist.PropertyListFormatException; +import com.dd.plist.XMLPropertyListParser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sonar.api.utils.XmlParserException; +import org.xml.sax.SAXException; + +import javax.xml.parsers.ParserConfigurationException; +import java.io.File; +import java.io.FilenameFilter; +import java.io.IOException; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * @author Matthew DeTullio + */ +public final class ClangPlistParser { + private static final Logger LOGGER = LoggerFactory.getLogger(ClangPlistParser.class); + + private ClangPlistParser() { + // Prevents outside instantiation + } + + public static List parse(final File reportsDir) { + List result = new ArrayList<>(); + + File[] reports = getReports(reportsDir); + + for (File report : reports) { + try { + result.addAll(parsePlist(report)); + } catch (Exception e) { + throw new XmlParserException("Unable to parse Clang reports", e); + } + } + + return result; + } + + private static File[] getReports(final File reportsDir) { + if (!reportsDir.isDirectory() || !reportsDir.exists()) { + return new File[0]; + } + + return reportsDir.listFiles(new FilenameFilter() { + @Override + public boolean accept(File dir, String name) { + return name.endsWith(".plist"); + } + }); + } + + @SuppressWarnings("unchecked") + private static List parsePlist(final File file) { + List result = new ArrayList<>(); + + try { + // Clang report is NSDictionary, which converts to a Map + Map report = + (Map) XMLPropertyListParser.parse(file).toJavaObject(); + + // Files reported on in this report + List files = new ArrayList<>(); + for (Object obj : (Object[]) report.get("files")) { + files.add((String) obj); + } + + // Diagnostics which contain the warning and the execution path + // (we're only interested in the final location) + List> diagnostics = new ArrayList<>(); + for (Object obj : (Object[]) report.get("diagnostics")) { + diagnostics.add((Map) obj); + } + + // Extract warning type, line number, and file, then add to results + for (Map diagnostic : diagnostics) { + Map location = (Map) diagnostic.get("location"); + + ClangWarning clangWarning = new ClangWarning(); + clangWarning.setCategory((String) diagnostic.get("category")); + // file is an integer representing the index of the file in the files array + clangWarning.setFile(new File(files.get((Integer) location.get("file")))); + clangWarning.setLine((Integer) location.get("line")); + clangWarning.setType((String) diagnostic.get("type")); + + result.add(clangWarning); + } + } catch (final IOException | ParserConfigurationException | ParseException | SAXException | PropertyListFormatException e) { + LOGGER.error("Error processing file named {}", file, e); + } + + return result; + } +} diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/clang/ClangProfile.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/clang/ClangProfile.java new file mode 100644 index 00000000..3070c262 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/clang/ClangProfile.java @@ -0,0 +1,58 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec.clang; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sonar.api.profiles.ProfileDefinition; +import org.sonar.api.profiles.RulesProfile; +import org.sonar.api.utils.ValidationMessages; +import org.sonar.plugins.objectivec.api.ObjectiveC; + +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; + +public final class ClangProfile extends ProfileDefinition { + private static final Logger LOGGER = LoggerFactory.getLogger(ClangProfile.class); + + private final ClangProfileImporter importer; + + public ClangProfile(final ClangProfileImporter importer) { + this.importer = importer; + } + + @Override + public RulesProfile createProfile(final ValidationMessages messages) { + LOGGER.info("Creating Clang Profile"); + + try (Reader profileXmlReader = new InputStreamReader(ClangProfile.class.getResourceAsStream( + "/org/sonar/plugins/objectivec/profile-clang.xml"))) { + + RulesProfile profile = importer.importProfile(profileXmlReader, messages); + profile.setLanguage(ObjectiveC.KEY); + profile.setName(ClangRulesDefinition.REPOSITORY_NAME); + + return profile; + } catch (IOException e) { + throw new IllegalStateException("Unable to read profile XML", e); + } + } +} diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/clang/ClangProfileImporter.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/clang/ClangProfileImporter.java new file mode 100644 index 00000000..1fde82c3 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/clang/ClangProfileImporter.java @@ -0,0 +1,56 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec.clang; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sonar.api.profiles.ProfileImporter; +import org.sonar.api.profiles.RulesProfile; +import org.sonar.api.profiles.XMLProfileParser; +import org.sonar.api.utils.ValidationMessages; +import org.sonar.plugins.objectivec.api.ObjectiveC; + +import java.io.Reader; + +public final class ClangProfileImporter extends ProfileImporter { + private static final Logger LOGGER = LoggerFactory.getLogger(ClangProfileImporter.class); + private static final String UNABLE_TO_LOAD_DEFAULT_PROFILE = "Unable to load default Clang profile"; + + private final XMLProfileParser profileParser; + + public ClangProfileImporter(final XMLProfileParser xmlProfileParser) { + super(ClangRulesDefinition.REPOSITORY_KEY, ClangRulesDefinition.REPOSITORY_NAME); + setSupportedLanguages(ObjectiveC.KEY); + profileParser = xmlProfileParser; + } + + @Override + public RulesProfile importProfile(final Reader reader, + final ValidationMessages messages) { + final RulesProfile profile = profileParser.parse(reader, messages); + + if (null == profile) { + messages.addErrorText(UNABLE_TO_LOAD_DEFAULT_PROFILE); + LOGGER.error(UNABLE_TO_LOAD_DEFAULT_PROFILE); + } + + return profile; + } +} diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/clang/ClangRulesDefinition.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/clang/ClangRulesDefinition.java new file mode 100644 index 00000000..c225089c --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/clang/ClangRulesDefinition.java @@ -0,0 +1,72 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec.clang; + +import com.google.common.collect.ImmutableMap; +import org.sonar.api.server.rule.RulesDefinition; +import org.sonar.api.server.rule.RulesDefinitionXmlLoader; +import org.sonar.plugins.objectivec.api.ObjectiveC; +import org.sonar.squidbridge.rules.SqaleXmlLoader; + +import java.util.Map; + +/** + * @author Matthew DeTullio + */ +public final class ClangRulesDefinition implements RulesDefinition { + public static final String REPOSITORY_KEY = "clang"; + public static final String REPOSITORY_NAME = "Clang"; + + /** + * Map of Clang plist report types to their corresponding rules. Multiple types can map to a single + * rule. + */ + public static final Map REPORT_TYPE_TO_RULE_MAP = ImmutableMap.builder() + .put("Assigned value is garbage or undefined", "core.uninitialized.Assign") // Logic error + .put("Bad return type when passing NSError**", "osx.cocoa.NSError") // Coding conventions (Apple) + .put("Branch condition evaluates to a garbage value", "core.uninitialized.Branch") // Logic error + .put("Dead assignment", "deadcode.DeadStores") // Dead store + .put("Dead increment", "deadcode.DeadStores") // Dead store + .put("Dead initialization", "deadcode.DeadStores") // Dead store + .put("Garbage return value", "core.uninitialized.UndefReturn") // Logic error + .put("Leak", "osx.cocoa.RetainCount") // Memory (Core Foundation/Objective-C) + .put("Missing call to superclass", "osx.cocoa.MissingSuperCall") // Core Foundation/Objective-C + .put("Nil value used as mutex for @synchronized() (no synchronization will occur)", "osx.cocoa.AtSync") // Logic error + .put("Result of operation is garbage or undefined", "core.UndefinedBinaryOperatorResult") // Logic error + .put("Uninitialized argument value", "core.CallAndMessage") // Logic error + .build(); + + @Override + public void define(Context context) { + NewRepository repository = context + .createRepository(REPOSITORY_KEY, ObjectiveC.KEY) + .setName(REPOSITORY_NAME); + + RulesDefinitionXmlLoader ruleLoader = new RulesDefinitionXmlLoader(); + ruleLoader.load( + repository, + ClangRulesDefinition.class.getResourceAsStream("/org/sonar/plugins/objectivec/rules-clang.xml"), + "UTF-8"); + + SqaleXmlLoader.load(repository, "/com/sonar/sqale/clang-model.xml"); + + repository.done(); + } +} diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/clang/ClangSensor.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/clang/ClangSensor.java new file mode 100644 index 00000000..f97f9322 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/clang/ClangSensor.java @@ -0,0 +1,123 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec.clang; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sonar.api.batch.Sensor; +import org.sonar.api.batch.SensorContext; +import org.sonar.api.batch.fs.FileSystem; +import org.sonar.api.batch.fs.InputFile; +import org.sonar.api.component.ResourcePerspectives; +import org.sonar.api.config.Settings; +import org.sonar.api.issue.Issuable; +import org.sonar.api.issue.Issue; +import org.sonar.api.resources.Project; +import org.sonar.api.resources.Resource; +import org.sonar.api.rule.RuleKey; +import org.sonar.api.scan.filesystem.PathResolver; + +import java.io.File; +import java.util.List; + +/** + * @author Matthew DeTullio + */ +public final class ClangSensor implements Sensor { + private static final Logger LOGGER = LoggerFactory.getLogger(ClangSensor.class.getName()); + + public static final String REPORTS_PATH_KEY = "sonar.objectivec.clang.reportsPath"; + + private final FileSystem fileSystem; + private final PathResolver pathResolver; + private final ResourcePerspectives resourcePerspectives; + private final Settings settings; + + public ClangSensor(final FileSystem fileSystem, final PathResolver pathResolver, + final ResourcePerspectives resourcePerspectives, final Settings settings) { + this.fileSystem = fileSystem; + this.pathResolver = pathResolver; + this.resourcePerspectives = resourcePerspectives; + this.settings = settings; + } + + @Override + public boolean shouldExecuteOnProject(Project project) { + return StringUtils.isNotEmpty(settings.getString(REPORTS_PATH_KEY)); + } + + @Override + public void analyse(Project project, SensorContext context) { + String path = settings.getString(REPORTS_PATH_KEY); + File reportsDir = pathResolver.relativeFile(fileSystem.baseDir(), path); + + if (!reportsDir.isDirectory()) { + LOGGER.warn("Clang report directory not found at {}", reportsDir); + return; + } + + collect(context, reportsDir); + } + + protected void collect(SensorContext context, File reportsDir) { + LOGGER.info("parsing {}", reportsDir); + + List clangWarnings = ClangPlistParser.parse(reportsDir); + + for (ClangWarning clangWarning : clangWarnings) { + String type = clangWarning.getType(); + String ruleKeyName; + + if (ClangRulesDefinition.REPORT_TYPE_TO_RULE_MAP.containsKey(type)) { + ruleKeyName = ClangRulesDefinition.REPORT_TYPE_TO_RULE_MAP.get(type); + } else { + ruleKeyName = "other"; + LOGGER.debug("Type '{}' is not mapped to a rule -- using default rule '{}'", type, ruleKeyName); + } + + final InputFile inputFile = + fileSystem.inputFile(fileSystem.predicates().hasPath(clangWarning.getFile().getPath())); + final Resource resource = inputFile == null ? null : context.getResource(inputFile); + + if (resource == null) { + LOGGER.debug("Skipping file (not found in index): {}", clangWarning.getFile().getPath()); + continue; + } + + Issuable issuable = resourcePerspectives.as(Issuable.class, resource); + + if (issuable != null) { + Issue issue = issuable.newIssueBuilder() + .ruleKey(RuleKey.of(ClangRulesDefinition.REPOSITORY_KEY, ruleKeyName)) + .message(String.format("%s - %s", clangWarning.getCategory(), type)) + .line(clangWarning.getLine()) + .build(); + + issuable.addIssue(issue); + } + } + } + + @Override + public String toString() { + return "Objective-C Clang Sensor"; + } +} diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/clang/ClangWarning.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/clang/ClangWarning.java new file mode 100644 index 00000000..df13099f --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/clang/ClangWarning.java @@ -0,0 +1,64 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec.clang; + +import java.io.File; + +/** + * @author Matthew DeTullio + */ +public class ClangWarning { + private String category; + private File file; + private Integer line; + private String type; + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public File getFile() { + return file; + } + + public void setFile(File file) { + this.file = file; + } + + public Integer getLine() { + return line; + } + + public void setLine(Integer line) { + this.line = line; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/clang/package-info.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/clang/package-info.java new file mode 100644 index 00000000..a125f638 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/clang/package-info.java @@ -0,0 +1,23 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +@ParametersAreNonnullByDefault +package org.sonar.plugins.objectivec.clang; + +import javax.annotation.ParametersAreNonnullByDefault; \ No newline at end of file diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/cobertura/CoberturaReportParser.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/cobertura/CoberturaReportParser.java new file mode 100644 index 00000000..48dee6a2 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/cobertura/CoberturaReportParser.java @@ -0,0 +1,126 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec.cobertura; + +import com.google.common.collect.Maps; +import org.apache.commons.lang.StringUtils; +import org.codehaus.staxmate.in.SMHierarchicCursor; +import org.codehaus.staxmate.in.SMInputCursor; +import org.sonar.api.batch.SensorContext; +import org.sonar.api.batch.fs.FileSystem; +import org.sonar.api.batch.fs.InputFile; +import org.sonar.api.measures.CoverageMeasuresBuilder; +import org.sonar.api.measures.Measure; +import org.sonar.api.resources.Resource; +import org.sonar.api.utils.ParsingUtils; +import org.sonar.api.utils.StaxParser; +import org.sonar.api.utils.XmlParserException; + +import javax.xml.stream.XMLStreamException; +import java.io.File; +import java.text.ParseException; +import java.util.Locale; +import java.util.Map; + +final class CoberturaReportParser { + private final FileSystem fileSystem; + private final SensorContext context; + + private CoberturaReportParser(FileSystem fileSystem, SensorContext context) { + this.fileSystem = fileSystem; + this.context = context; + } + + /** + * Parse a Cobertura xml report and create measures accordingly + */ + public static void parseReport(File xmlFile, FileSystem fileSystem, SensorContext context) { + new CoberturaReportParser(fileSystem, context).parse(xmlFile); + } + + private void parse(File xmlFile) { + try { + StaxParser parser = new StaxParser(new StaxParser.XmlStreamHandler() { + @Override + public void stream(SMHierarchicCursor rootCursor) throws XMLStreamException { + rootCursor.advance(); + collectPackageMeasures(rootCursor.descendantElementCursor("package")); + } + }); + parser.parse(xmlFile); + } catch (XMLStreamException e) { + throw new XmlParserException(e); + } + } + + private void collectPackageMeasures(SMInputCursor pack) throws XMLStreamException { + while (pack.getNext() != null) { + Map builderByFilename = Maps.newHashMap(); + collectFileMeasures(pack.descendantElementCursor("class"), builderByFilename); + + for (Map.Entry entry : builderByFilename.entrySet()) { + String filePath = entry.getKey(); + final InputFile inputFile = fileSystem.inputFile(fileSystem.predicates().hasPath(filePath)); + final Resource resource = inputFile == null ? null : context.getResource(inputFile); + + if (resource != null) { + for (Measure measure : entry.getValue().createMeasures()) { + context.saveMeasure(resource, measure); + } + } + } + } + } + + private static void collectFileMeasures(SMInputCursor clazz, + Map builderByFilename) throws XMLStreamException { + while (clazz.getNext() != null) { + String fileName = clazz.getAttrValue("filename"); + CoverageMeasuresBuilder builder = builderByFilename.get(fileName); + + if (builder == null) { + builder = CoverageMeasuresBuilder.create(); + builderByFilename.put(fileName, builder); + } + + collectFileData(clazz, builder); + } + } + + private static void collectFileData(SMInputCursor clazz, + CoverageMeasuresBuilder builder) throws XMLStreamException { + SMInputCursor line = clazz.childElementCursor("lines").advance().childElementCursor("line"); + while (line.getNext() != null) { + int lineId = Integer.parseInt(line.getAttrValue("number")); + try { + builder.setHits(lineId, (int) ParsingUtils.parseNumber(line.getAttrValue("hits"), Locale.ENGLISH)); + } catch (ParseException e) { + throw new XmlParserException(e); + } + + String isBranch = line.getAttrValue("branch"); + String text = line.getAttrValue("condition-coverage"); + if (StringUtils.equals(isBranch, "true") && StringUtils.isNotBlank(text)) { + String[] conditions = StringUtils.split(StringUtils.substringBetween(text, "(", ")"), "/"); + builder.setConditions(lineId, Integer.parseInt(conditions[1]), Integer.parseInt(conditions[0])); + } + } + } +} diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/cobertura/CoberturaSensor.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/cobertura/CoberturaSensor.java new file mode 100644 index 00000000..33de51a7 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/cobertura/CoberturaSensor.java @@ -0,0 +1,74 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec.cobertura; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sonar.api.batch.CoverageExtension; +import org.sonar.api.batch.Sensor; +import org.sonar.api.batch.SensorContext; +import org.sonar.api.batch.fs.FileSystem; +import org.sonar.api.config.Settings; +import org.sonar.api.resources.Project; +import org.sonar.api.scan.filesystem.PathResolver; + +import java.io.File; + + +public final class CoberturaSensor implements Sensor, CoverageExtension { + private static final Logger LOGGER = LoggerFactory.getLogger(CoberturaSensor.class); + + public static final String REPORT_PATH_KEY = "sonar.objectivec.cobertura.reportPath"; + + private final FileSystem fileSystem; + private final PathResolver pathResolver; + private final Settings settings; + + public CoberturaSensor(final FileSystem fileSystem, final PathResolver pathResolver, final Settings settings) { + this.fileSystem = fileSystem; + this.pathResolver = pathResolver; + this.settings = settings; + } + + @Override + public boolean shouldExecuteOnProject(Project project) { + return StringUtils.isNotEmpty(settings.getString(REPORT_PATH_KEY)); + } + + @Override + public void analyse(Project project, SensorContext context) { + String path = settings.getString(REPORT_PATH_KEY); + File report = pathResolver.relativeFile(fileSystem.baseDir(), path); + + if (!report.isFile()) { + LOGGER.warn("Cobertura report not found at {}", report); + return; + } + + LOGGER.info("parsing {}", report); + CoberturaReportParser.parseReport(report, fileSystem, context); + } + + @Override + public String toString() { + return "Objective-C Cobertura Sensor"; + } +} diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/cobertura/package-info.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/cobertura/package-info.java new file mode 100644 index 00000000..011b64a3 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/cobertura/package-info.java @@ -0,0 +1,23 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +@ParametersAreNonnullByDefault +package org.sonar.plugins.objectivec.cobertura; + +import javax.annotation.ParametersAreNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/org/sonar/plugins/objectivec/cpd/ObjectiveCCpdMapping.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/cpd/ObjectiveCCpdMapping.java similarity index 67% rename from src/main/java/org/sonar/plugins/objectivec/cpd/ObjectiveCCpdMapping.java rename to sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/cpd/ObjectiveCCpdMapping.java index 4cf0fc5b..aadc15a3 100644 --- a/src/main/java/org/sonar/plugins/objectivec/cpd/ObjectiveCCpdMapping.java +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/cpd/ObjectiveCCpdMapping.java @@ -1,7 +1,7 @@ /* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,37 +13,36 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plugins.objectivec.cpd; -import java.nio.charset.Charset; - import net.sourceforge.pmd.cpd.Tokenizer; - import org.sonar.api.batch.AbstractCpdMapping; +import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.resources.Language; -import org.sonar.api.resources.ProjectFileSystem; -import org.sonar.plugins.objectivec.core.ObjectiveC; +import org.sonar.plugins.objectivec.api.ObjectiveC; -public class ObjectiveCCpdMapping extends AbstractCpdMapping { +import java.nio.charset.Charset; +public class ObjectiveCCpdMapping extends AbstractCpdMapping { private final ObjectiveC language; private final Charset charset; - public ObjectiveCCpdMapping(ObjectiveC language, ProjectFileSystem fs) { + public ObjectiveCCpdMapping(ObjectiveC language, FileSystem fileSystem) { this.language = language; - this.charset = fs.getSourceCharset(); + this.charset = fileSystem.encoding(); } + @Override public Tokenizer getTokenizer() { return new ObjectiveCTokenizer(charset); } + @Override public Language getLanguage() { return language; } - } diff --git a/src/main/java/org/sonar/plugins/objectivec/cpd/ObjectiveCTokenizer.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/cpd/ObjectiveCTokenizer.java similarity index 85% rename from src/main/java/org/sonar/plugins/objectivec/cpd/ObjectiveCTokenizer.java rename to sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/cpd/ObjectiveCTokenizer.java index bf180f7c..b2565310 100644 --- a/src/main/java/org/sonar/plugins/objectivec/cpd/ObjectiveCTokenizer.java +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/cpd/ObjectiveCTokenizer.java @@ -1,7 +1,7 @@ /* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,27 +13,25 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plugins.objectivec.cpd; -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.List; - +import com.sonar.sslr.api.Token; +import com.sonar.sslr.impl.Lexer; import net.sourceforge.pmd.cpd.SourceCode; import net.sourceforge.pmd.cpd.TokenEntry; import net.sourceforge.pmd.cpd.Tokenizer; import net.sourceforge.pmd.cpd.Tokens; - import org.sonar.objectivec.ObjectiveCConfiguration; import org.sonar.objectivec.lexer.ObjectiveCLexer; -import com.sonar.sslr.api.Token; -import com.sonar.sslr.impl.Lexer; +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.List; public class ObjectiveCTokenizer implements Tokenizer { @@ -43,6 +41,7 @@ public ObjectiveCTokenizer(Charset charset) { this.charset = charset; } + @Override public void tokenize(SourceCode source, Tokens cpdTokens) throws IOException { Lexer lexer = ObjectiveCLexer.create(new ObjectiveCConfiguration(charset)); String fileName = source.getFileName(); diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/lizard/LizardReportParser.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/lizard/LizardReportParser.java new file mode 100644 index 00000000..ea5afc44 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/lizard/LizardReportParser.java @@ -0,0 +1,363 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec.lizard; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sonar.api.batch.SensorContext; +import org.sonar.api.batch.fs.FileSystem; +import org.sonar.api.batch.fs.InputFile; +import org.sonar.api.component.ResourcePerspectives; +import org.sonar.api.issue.Issuable; +import org.sonar.api.issue.Issue; +import org.sonar.api.measures.CoreMetrics; +import org.sonar.api.measures.Measure; +import org.sonar.api.measures.PersistenceMode; +import org.sonar.api.measures.RangeDistributionBuilder; +import org.sonar.api.profiles.RulesProfile; +import org.sonar.api.resources.Resource; +import org.sonar.api.rule.RuleKey; +import org.sonar.api.rules.ActiveRule; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +import javax.annotation.CheckForNull; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * This class parses xml Reports form the tool Lizard in order to extract this measures: + * COMPLEXITY, FUNCTIONS, FUNCTION_COMPLEXITY, FUNCTION_COMPLEXITY_DISTRIBUTION, + * FILE_COMPLEXITY, FUNCTION_COMPLEXITY_DISTRIBUTION, COMPLEXITY_IN_FUNCTIONS + * + * @author Andres Gil Herrera + * @since 28/05/15 + */ +public final class LizardReportParser { + private static final Logger LOGGER = LoggerFactory.getLogger(LizardReportParser.class); + + private static final String MEASURE = "measure"; + private static final String MEASURE_TYPE = "type"; + private static final String MEASURE_ITEM = "item"; + private static final String FILE_MEASURE = "file"; + private static final String FUNCTION_MEASURE = "Function"; + private static final String NAME = "name"; + private static final String VALUE = "value"; + private static final int CYCLOMATIC_COMPLEXITY_INDEX = 2; + private static final int FUNCTIONS_INDEX = 3; + + private static final Number[] FUNCTIONS_DISTRIB_BOTTOM_LIMITS = {1, 2, 4, 6, 8, 10, 12, 20, 30}; + private static final Number[] FILES_DISTRIB_BOTTOM_LIMITS = {0, 5, 10, 20, 30, 60, 90}; + + private final FileSystem fileSystem; + private final ResourcePerspectives resourcePerspectives; + private final RulesProfile rulesProfile; + private final SensorContext sensorContext; + + private LizardReportParser(final FileSystem fileSystem, final ResourcePerspectives resourcePerspectives, + final RulesProfile rulesProfile, final SensorContext sensorContext) { + this.fileSystem = fileSystem; + this.resourcePerspectives = resourcePerspectives; + this.rulesProfile = rulesProfile; + this.sensorContext = sensorContext; + } + + /** + * @param xmlFile lizard xml report + * @return Map containing as key the name of the file and as value a list containing the measures for that file + */ + @CheckForNull + public static Map> parseReport(final FileSystem fileSystem, + final ResourcePerspectives resourcePerspectives, final RulesProfile rulesProfile, + final SensorContext sensorContext, final File xmlFile) { + Map> result = null; + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + + try { + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.parse(xmlFile); + result = new LizardReportParser(fileSystem, resourcePerspectives, rulesProfile, sensorContext).parseFile(document); + } catch (final FileNotFoundException e) { + LOGGER.error("Lizard Report not found {}", xmlFile, e); + } catch (final IOException | ParserConfigurationException | SAXException e) { + LOGGER.error("Error parsing file named {}", xmlFile, e); + } + + return result; + } + + /** + * @param document Document object representing the lizard report + * @return Map containing as key the name of the file and as value a list containing the measures for that file + */ + private Map> parseFile(Document document) { + final Map> reportMeasures = new HashMap<>(); + final List functions = new ArrayList<>(); + + NodeList nodeList = document.getElementsByTagName(MEASURE); + + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element element = (Element) node; + if (element.getAttribute(MEASURE_TYPE).equalsIgnoreCase(FILE_MEASURE)) { + NodeList itemList = element.getElementsByTagName(MEASURE_ITEM); + addComplexityFileMeasures(itemList, reportMeasures); + } else if (element.getAttribute(MEASURE_TYPE).equalsIgnoreCase(FUNCTION_MEASURE)) { + NodeList itemList = element.getElementsByTagName(MEASURE_ITEM); + collectFunctions(itemList, functions); + } + } + } + + addComplexityFunctionMeasures(reportMeasures, functions); + + return reportMeasures; + } + + /** + * This method extracts the values for COMPLEXITY, FUNCTIONS, FILE_COMPLEXITY + * + * @param itemList list of all items from a + * @param reportMeasures map to save the measures for each file + */ + private void addComplexityFileMeasures(NodeList itemList, Map> reportMeasures) { + for (int i = 0; i < itemList.getLength(); i++) { + Node item = itemList.item(i); + + if (item.getNodeType() == Node.ELEMENT_NODE) { + Element itemElement = (Element) item; + String fileName = itemElement.getAttribute(NAME); + NodeList values = itemElement.getElementsByTagName(VALUE); + int complexity = Integer.parseInt(values.item(CYCLOMATIC_COMPLEXITY_INDEX).getTextContent()); + double fileComplexity = Double.parseDouble(values.item(CYCLOMATIC_COMPLEXITY_INDEX).getTextContent()); + int numberOfFunctions = Integer.parseInt(values.item(FUNCTIONS_INDEX).getTextContent()); + + reportMeasures.put(fileName, buildMeasureList(complexity, fileComplexity, numberOfFunctions)); + } + } + } + + /** + * @param complexity overall complexity of the file + * @param fileComplexity file complexity + * @param numberOfFunctions number of functions in the file + * @return returns a list of tree measures COMPLEXITY, FUNCTIONS, FILE_COMPLEXITY with the values specified + */ + private List buildMeasureList(int complexity, double fileComplexity, int numberOfFunctions) { + List list = new ArrayList<>(); + list.add(new Measure(CoreMetrics.COMPLEXITY).setIntValue(complexity)); + list.add(new Measure(CoreMetrics.FUNCTIONS).setIntValue(numberOfFunctions)); + list.add(new Measure(CoreMetrics.FILE_COMPLEXITY, fileComplexity)); + RangeDistributionBuilder complexityDistribution = new RangeDistributionBuilder(CoreMetrics.FILE_COMPLEXITY_DISTRIBUTION, FILES_DISTRIB_BOTTOM_LIMITS); + complexityDistribution.add(fileComplexity); + list.add(complexityDistribution.build().setPersistenceMode(PersistenceMode.MEMORY)); + return list; + } + + /** + * @param itemList NodeList of all items in a tag + * @param functions list to save the functions in the NodeList as ObjCFunction objects. + */ + private void collectFunctions(NodeList itemList, List functions) { + for (int i = 0; i < itemList.getLength(); i++) { + Node item = itemList.item(i); + if (item.getNodeType() == Node.ELEMENT_NODE) { + Element itemElement = (Element) item; + String name = itemElement.getAttribute(NAME); + String measure = itemElement.getElementsByTagName(VALUE).item(CYCLOMATIC_COMPLEXITY_INDEX).getTextContent(); + functions.add(new ObjCFunction(name, Integer.parseInt(measure))); + } + } + } + + /** + * @param reportMeasures map to save the measures for the different files + * @param functions list of ObjCFunction to extract the information needed to create + * FUNCTION_COMPLEXITY_DISTRIBUTION, FUNCTION_COMPLEXITY, COMPLEXITY_IN_FUNCTIONS + */ + private void addComplexityFunctionMeasures(Map> reportMeasures, + List functions) { + for (Map.Entry> entry : reportMeasures.entrySet()) { + + RangeDistributionBuilder complexityDistribution = new RangeDistributionBuilder(CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION, FUNCTIONS_DISTRIB_BOTTOM_LIMITS); + int count = 0; + int complexityInFunctions = 0; + + for (ObjCFunction func : functions) { + if (func.getName().contains(entry.getKey())) { + complexityDistribution.add(func.getCyclomaticComplexity()); + count++; + complexityInFunctions += func.getCyclomaticComplexity(); + createFunctionComplexityIssue(entry.getKey(), func); + } + } + + if (count != 0) { + double complex = 0; + for (Measure m : entry.getValue()) { + if (m.getMetric().getKey().equalsIgnoreCase(CoreMetrics.FILE_COMPLEXITY.getKey())) { + complex = m.getValue(); + createFileComplexityIssue(entry.getKey(), (int) complex); + break; + } + } + + double complexMean = complex / (double) count; + entry.getValue().addAll(buildFunctionMeasuresList(complexMean, complexityInFunctions, complexityDistribution)); + } + } + } + + private void createFileComplexityIssue(String fileName, int complexity) { + ActiveRule activeRule = rulesProfile.getActiveRule( + LizardRulesDefinition.REPOSITORY_KEY, + LizardRulesDefinition.FILE_CYCLOMATIC_COMPLEXITY_RULE_KEY); + + if (activeRule == null) { + // Rule is not active + return; + } + + int threshold = Integer.parseInt(activeRule.getParameter(LizardRulesDefinition.FILE_CYCLOMATIC_COMPLEXITY_PARAM_KEY)); + + if (complexity <= threshold) { + // Complexity is lower or equal to the defined threshold + return; + } + + final InputFile inputFile = fileSystem.inputFile(fileSystem.predicates().hasPath(fileName)); + final Resource resource = inputFile == null ? null : sensorContext.getResource(inputFile); + + if (resource == null) { + LOGGER.debug("Skipping file (not found in index): {}", fileName); + return; + } + + Issuable issuable = resourcePerspectives.as(Issuable.class, resource); + + if (issuable != null) { + Issue issue = issuable.newIssueBuilder() + .ruleKey(RuleKey.of(LizardRulesDefinition.REPOSITORY_KEY, LizardRulesDefinition.FILE_CYCLOMATIC_COMPLEXITY_RULE_KEY)) + .message(String.format("The Cyclomatic Complexity of this file \"%s\" is %d which is greater than %d authorized.", fileName, complexity, threshold)) + .effortToFix((double) (complexity - threshold)) + .build(); + + issuable.addIssue(issue); + } + } + + private void createFunctionComplexityIssue(String fileName, ObjCFunction func) { + ActiveRule activeRule = rulesProfile.getActiveRule( + LizardRulesDefinition.REPOSITORY_KEY, + LizardRulesDefinition.FUNCTION_CYCLOMATIC_COMPLEXITY_RULE_KEY); + + if (activeRule == null) { + // Rule is not active + return; + } + + int complexity = func.getCyclomaticComplexity(); + int threshold = Integer.parseInt(activeRule.getParameter(LizardRulesDefinition.FUNCTION_CYCLOMATIC_COMPLEXITY_PARAM_KEY)); + + if (complexity <= threshold) { + // Complexity is lower or equal to the defined threshold + return; + } + + final InputFile inputFile = fileSystem.inputFile(fileSystem.predicates().hasPath(fileName)); + final Resource resource = inputFile == null ? null : sensorContext.getResource(inputFile); + + if (resource == null) { + LOGGER.debug("Skipping file (not found in index): {}", fileName); + return; + } + + Issuable issuable = resourcePerspectives.as(Issuable.class, resource); + + if (issuable != null) { + String name = func.getName(); + + int lastColonIndex = name.lastIndexOf(':'); + Integer lineNumber = lastColonIndex == -1 ? null : Integer.valueOf(name.substring(lastColonIndex + 1)); + + int atIndex = name.indexOf(" at "); + String functionName = atIndex == -1 ? name : name.substring(0, atIndex); + + Issue issue = issuable.newIssueBuilder() + .ruleKey(RuleKey.of(LizardRulesDefinition.REPOSITORY_KEY, LizardRulesDefinition.FUNCTION_CYCLOMATIC_COMPLEXITY_RULE_KEY)) + .message(String.format("The Cyclomatic Complexity of this function \"%s\" is %d which is greater than %d authorized.", functionName, complexity, threshold)) + .line(lineNumber) + .effortToFix((double) (complexity - threshold)) + .build(); + + issuable.addIssue(issue); + } + } + + /** + * @param complexMean average complexity per function in a file + * @param complexityInFunctions Entire complexity in functions + * @param builder Builder ready to build FUNCTION_COMPLEXITY_DISTRIBUTION + * @return list of Measures containing FUNCTION_COMPLEXITY_DISTRIBUTION, FUNCTION_COMPLEXITY and COMPLEXITY_IN_FUNCTIONS + */ + public List buildFunctionMeasuresList(double complexMean, int complexityInFunctions, + RangeDistributionBuilder builder) { + List list = new ArrayList<>(); + list.add(new Measure(CoreMetrics.FUNCTION_COMPLEXITY, complexMean)); + list.add(new Measure(CoreMetrics.COMPLEXITY_IN_FUNCTIONS).setIntValue(complexityInFunctions)); + list.add(builder.build().setPersistenceMode(PersistenceMode.MEMORY)); + return list; + } + + /** + * helper class to process the information the functions contained in a Lizard report + */ + private class ObjCFunction { + private String name; + private int cyclomaticComplexity; + + public ObjCFunction(String name, int cyclomaticComplexity) { + this.name = name; + this.cyclomaticComplexity = cyclomaticComplexity; + } + + public String getName() { + return name; + } + + public int getCyclomaticComplexity() { + return cyclomaticComplexity; + } + + } +} diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/lizard/LizardRulesDefinition.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/lizard/LizardRulesDefinition.java new file mode 100644 index 00000000..732eaaaa --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/lizard/LizardRulesDefinition.java @@ -0,0 +1,84 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec.lizard; + +import org.sonar.api.rule.Severity; +import org.sonar.api.server.rule.RuleParamType; +import org.sonar.api.server.rule.RulesDefinition; +import org.sonar.plugins.objectivec.api.ObjectiveC; + +public final class LizardRulesDefinition implements RulesDefinition { + public static final String REPOSITORY_KEY = "lizard"; + public static final String REPOSITORY_NAME = "Lizard"; + + private static final String THRESHOLD = "Threshold"; + + public static final String FILE_CYCLOMATIC_COMPLEXITY_RULE_KEY = "FileCyclomaticComplexity"; + public static final String FILE_CYCLOMATIC_COMPLEXITY_PARAM_KEY = THRESHOLD; + + public static final String FUNCTION_CYCLOMATIC_COMPLEXITY_RULE_KEY = "FunctionCyclomaticComplexity"; + public static final String FUNCTION_CYCLOMATIC_COMPLEXITY_PARAM_KEY = THRESHOLD; + + @Override + public void define(Context context) { + NewRepository repository = context + .createRepository(REPOSITORY_KEY, ObjectiveC.KEY) + .setName(REPOSITORY_NAME); + + NewRule fileCyclomaticComplexityRule = repository + .createRule(FILE_CYCLOMATIC_COMPLEXITY_RULE_KEY) + .setName("Files should not be too complex") + .setHtmlDescription("Most of the time, a very complex file breaks the Single Responsibility " + + "Principle and should be re-factored into several different files.") + .setTags("brain-overload") + .setSeverity(Severity.MAJOR); + fileCyclomaticComplexityRule + .setDebtSubCharacteristic(SubCharacteristics.UNIT_TESTABILITY) + .setDebtRemediationFunction( + fileCyclomaticComplexityRule.debtRemediationFunctions().linearWithOffset("1min", "30min")) + .setEffortToFixDescription("per complexity point above the threshold"); + fileCyclomaticComplexityRule + .createParam(FILE_CYCLOMATIC_COMPLEXITY_PARAM_KEY) + .setDefaultValue("80") + .setType(RuleParamType.INTEGER) + .setDescription("Maximum complexity allowed."); + + NewRule functionCyclomaticComplexityRule = repository + .createRule(FUNCTION_CYCLOMATIC_COMPLEXITY_RULE_KEY) + .setName("Functions should not be too complex") + .setHtmlDescription("The cyclomatic complexity of functions should not exceed a defined threshold. " + + "Complex code can perform poorly and will in any case be difficult to understand and " + + "therefore to maintain.") + .setTags("brain-overload") + .setSeverity(Severity.MAJOR); + functionCyclomaticComplexityRule + .setDebtSubCharacteristic(SubCharacteristics.UNIT_TESTABILITY) + .setDebtRemediationFunction( + functionCyclomaticComplexityRule.debtRemediationFunctions().linearWithOffset("1min", "10min")) + .setEffortToFixDescription("per complexity point above the threshold"); + functionCyclomaticComplexityRule + .createParam(FUNCTION_CYCLOMATIC_COMPLEXITY_PARAM_KEY) + .setDefaultValue("10") + .setType(RuleParamType.INTEGER) + .setDescription("Maximum complexity allowed."); + + repository.done(); + } +} diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/lizard/LizardSensor.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/lizard/LizardSensor.java new file mode 100644 index 00000000..b6a1de2b --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/lizard/LizardSensor.java @@ -0,0 +1,115 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec.lizard; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sonar.api.batch.Sensor; +import org.sonar.api.batch.SensorContext; +import org.sonar.api.batch.fs.FileSystem; +import org.sonar.api.batch.fs.InputFile; +import org.sonar.api.component.ResourcePerspectives; +import org.sonar.api.config.Settings; +import org.sonar.api.measures.Measure; +import org.sonar.api.profiles.RulesProfile; +import org.sonar.api.resources.Project; +import org.sonar.api.resources.Resource; +import org.sonar.api.scan.filesystem.PathResolver; +import org.sonar.plugins.objectivec.api.ObjectiveC; + +import java.io.File; +import java.util.List; +import java.util.Map; + +/** + * This sensor searches for the report generated from the tool Lizard + * in order to save complexity metrics. + * + * @author Andres Gil Herrera + * @since 28/05/15 + */ +public final class LizardSensor implements Sensor { + private static final Logger LOGGER = LoggerFactory.getLogger(LizardSensor.class); + + public static final String REPORT_PATH_KEY = "sonar.objectivec.lizard.reportPath"; + + private final FileSystem fileSystem; + private final PathResolver pathResolver; + private final ResourcePerspectives resourcePerspectives; + private final RulesProfile rulesProfile; + private final Settings settings; + + public LizardSensor(final FileSystem fileSystem, final PathResolver pathResolver, + final ResourcePerspectives resourcePerspectives, final RulesProfile rulesProfile, final Settings settings) { + this.fileSystem = fileSystem; + this.pathResolver = pathResolver; + this.resourcePerspectives = resourcePerspectives; + this.rulesProfile = rulesProfile; + this.settings = settings; + } + + @Override + public boolean shouldExecuteOnProject(Project project) { + return StringUtils.isNotEmpty(settings.getString(REPORT_PATH_KEY)) + && fileSystem.languages().contains(ObjectiveC.KEY); + } + + @Override + public void analyse(Project project, SensorContext context) { + String path = settings.getString(REPORT_PATH_KEY); + File report = pathResolver.relativeFile(fileSystem.baseDir(), path); + + if (!report.isFile()) { + LOGGER.warn("Lizard report not found at {}", report); + return; + } + + LOGGER.info("parsing {}", report); + Map> measures = LizardReportParser.parseReport(fileSystem, resourcePerspectives, + rulesProfile, context, report); + + if (measures == null) { + return; + } + + LOGGER.info("Saving results of complexity analysis"); + saveMeasures(context, measures); + } + + private void saveMeasures(SensorContext context, final Map> measures) { + for (Map.Entry> entry : measures.entrySet()) { + final InputFile inputFile = fileSystem.inputFile(fileSystem.predicates().hasPath(entry.getKey())); + final Resource resource = inputFile == null ? null : context.getResource(inputFile); + + if (resource != null) { + for (Measure measure : entry.getValue()) { + LOGGER.debug("Save measure {} for file {}", measure.getMetric().getName(), resource.getPath()); + context.saveMeasure(resource, measure); + } + } + } + } + + @Override + public String toString() { + return "Objective-C Lizard Sensor"; + } +} diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/lizard/package-info.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/lizard/package-info.java new file mode 100644 index 00000000..56353b31 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/lizard/package-info.java @@ -0,0 +1,23 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +@ParametersAreNonnullByDefault +package org.sonar.plugins.objectivec.lizard; + +import javax.annotation.ParametersAreNonnullByDefault; \ No newline at end of file diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/oclint/OCLintParser.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/oclint/OCLintParser.java new file mode 100644 index 00000000..b2e4c4e0 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/oclint/OCLintParser.java @@ -0,0 +1,111 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec.oclint; + +import org.codehaus.staxmate.in.SMHierarchicCursor; +import org.codehaus.staxmate.in.SMInputCursor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sonar.api.batch.SensorContext; +import org.sonar.api.batch.fs.FileSystem; +import org.sonar.api.batch.fs.InputFile; +import org.sonar.api.component.ResourcePerspectives; +import org.sonar.api.issue.Issuable; +import org.sonar.api.issue.Issue; +import org.sonar.api.resources.Resource; +import org.sonar.api.rule.RuleKey; +import org.sonar.api.utils.StaxParser; +import org.sonar.api.utils.XmlParserException; + +import javax.xml.stream.XMLStreamException; +import java.io.File; + +final class OCLintParser { + private static final Logger LOGGER = LoggerFactory.getLogger(OCLintParser.class); + + private final FileSystem fileSystem; + private final SensorContext context; + private final ResourcePerspectives resourcePerspectives; + + private OCLintParser(final FileSystem fileSystem, final SensorContext context, + final ResourcePerspectives resourcePerspectives) { + this.fileSystem = fileSystem; + this.context = context; + this.resourcePerspectives = resourcePerspectives; + } + + public static void parseReport(File xmlFile, FileSystem fileSystem, SensorContext context, + ResourcePerspectives resourcePerspectives) { + new OCLintParser(fileSystem, context, resourcePerspectives).parse(xmlFile); + } + + + private void parse(File xmlFile) { + try { + StaxParser parser = new StaxParser(new StaxParser.XmlStreamHandler() { + @Override + public void stream(SMHierarchicCursor rootCursor) throws XMLStreamException { + rootCursor.advance(); + collectFiles(rootCursor.childElementCursor("file")); + } + }); + parser.parse(xmlFile); + } catch (XMLStreamException e) { + throw new XmlParserException(e); + } + } + + private void collectFiles(final SMInputCursor file) throws XMLStreamException { + while (null != file.getNext()) { + final String filePath = file.getAttrValue("name"); + LOGGER.debug("Collecting issues for {}", filePath); + + final InputFile inputFile = fileSystem.inputFile(fileSystem.predicates().hasPath(filePath)); + final Resource resource = inputFile == null ? null : context.getResource(inputFile); + + if (resource != null) { + LOGGER.debug("File {} was found in the project.", filePath); + collectFileIssues(resource, file); + } + } + } + + private void collectFileIssues(final Resource resource, final SMInputCursor file) throws XMLStreamException { + final SMInputCursor line = file.childElementCursor("violation"); + + while (line.getNext() != null) { + recordIssue(resource, line); + } + } + + private void recordIssue(final Resource resource, final SMInputCursor line) throws XMLStreamException { + Issuable issuable = resourcePerspectives.as(Issuable.class, resource); + + if (issuable != null) { + Issue issue = issuable.newIssueBuilder() + .ruleKey(RuleKey.of(OCLintRulesDefinition.REPOSITORY_KEY, line.getAttrValue("rule"))) + .line(Integer.valueOf(line.getAttrValue("beginline"))) + .message(line.getElemStringValue()) + .build(); + + issuable.addIssue(issue); + } + } +} diff --git a/src/main/java/org/sonar/plugins/objectivec/violations/OCLintProfile.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/oclint/OCLintProfile.java similarity index 51% rename from src/main/java/org/sonar/plugins/objectivec/violations/OCLintProfile.java rename to sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/oclint/OCLintProfile.java index 1e5684d8..a5f11733 100644 --- a/src/main/java/org/sonar/plugins/objectivec/violations/OCLintProfile.java +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/oclint/OCLintProfile.java @@ -1,7 +1,7 @@ /* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,49 +13,47 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -package org.sonar.plugins.objectivec.violations; - -import java.io.InputStreamReader; -import java.io.Reader; +package org.sonar.plugins.objectivec.oclint; +import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.profiles.ProfileDefinition; import org.sonar.api.profiles.RulesProfile; import org.sonar.api.utils.ValidationMessages; -import org.sonar.plugins.objectivec.core.ObjectiveC; +import org.sonar.plugins.objectivec.api.ObjectiveC; -import com.google.common.io.Closeables; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; public final class OCLintProfile extends ProfileDefinition { + private static final Logger LOGGER = LoggerFactory.getLogger(OCLintProfile.class); - private static final String DEFAULT_PROFILE = "/org/sonar/plugins/oclint/profile-oclint.xml"; - private final OCLintProfileImporter profileImporter; + private final OCLintProfileImporter importer; public OCLintProfile(final OCLintProfileImporter importer) { - profileImporter = importer; + this.importer = importer; } @Override public RulesProfile createProfile(final ValidationMessages messages) { - LoggerFactory.getLogger(getClass()).info("Creating OCLint Profile"); - Reader config = null; - - try { - config = new InputStreamReader(getClass().getResourceAsStream( - DEFAULT_PROFILE)); - final RulesProfile profile = profileImporter.importProfile(config, - messages); - profile.setName(OCLintRuleRepository.REPOSITORY_KEY); + LOGGER.info("Creating OCLint Profile"); + + try (Reader profileXmlReader = new InputStreamReader(OCLintProfile.class.getResourceAsStream( + "/org/sonar/plugins/objectivec/profile-oclint.xml"))) { + + RulesProfile profile = importer.importProfile(profileXmlReader, messages); profile.setLanguage(ObjectiveC.KEY); + profile.setName(OCLintRulesDefinition.REPOSITORY_NAME); profile.setDefaultProfile(true); return profile; - } finally { - Closeables.closeQuietly(config); + } catch (IOException e) { + throw new IllegalStateException("Unable to read profile XML", e); } } } diff --git a/src/main/java/org/sonar/plugins/objectivec/violations/OCLintProfileImporter.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/oclint/OCLintProfileImporter.java similarity index 69% rename from src/main/java/org/sonar/plugins/objectivec/violations/OCLintProfileImporter.java rename to sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/oclint/OCLintProfileImporter.java index ba174e58..205ff16a 100644 --- a/src/main/java/org/sonar/plugins/objectivec/violations/OCLintProfileImporter.java +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/oclint/OCLintProfileImporter.java @@ -1,7 +1,7 @@ /* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -13,28 +13,30 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -package org.sonar.plugins.objectivec.violations; - -import java.io.Reader; +package org.sonar.plugins.objectivec.oclint; +import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.profiles.ProfileImporter; import org.sonar.api.profiles.RulesProfile; import org.sonar.api.profiles.XMLProfileParser; import org.sonar.api.utils.ValidationMessages; -import org.sonar.plugins.objectivec.core.ObjectiveC; +import org.sonar.plugins.objectivec.api.ObjectiveC; + +import java.io.Reader; public final class OCLintProfileImporter extends ProfileImporter { + private static final Logger LOGGER = LoggerFactory.getLogger(OCLintProfileImporter.class); private static final String UNABLE_TO_LOAD_DEFAULT_PROFILE = "Unable to load default OCLint profile"; + private final XMLProfileParser profileParser; public OCLintProfileImporter(final XMLProfileParser xmlProfileParser) { - super(OCLintRuleRepository.REPOSITORY_KEY, - OCLintRuleRepository.REPOSITORY_KEY); + super(OCLintRulesDefinition.REPOSITORY_KEY, OCLintRulesDefinition.REPOSITORY_NAME); setSupportedLanguages(ObjectiveC.KEY); profileParser = xmlProfileParser; } @@ -46,8 +48,7 @@ public RulesProfile importProfile(final Reader reader, if (null == profile) { messages.addErrorText(UNABLE_TO_LOAD_DEFAULT_PROFILE); - LoggerFactory.getLogger(OCLintProfileImporter.class).error( - UNABLE_TO_LOAD_DEFAULT_PROFILE); + LOGGER.error(UNABLE_TO_LOAD_DEFAULT_PROFILE); } return profile; diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/oclint/OCLintRulesDefinition.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/oclint/OCLintRulesDefinition.java new file mode 100644 index 00000000..cb80925b --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/oclint/OCLintRulesDefinition.java @@ -0,0 +1,47 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec.oclint; + +import org.sonar.api.server.rule.RulesDefinition; +import org.sonar.api.server.rule.RulesDefinitionXmlLoader; +import org.sonar.plugins.objectivec.api.ObjectiveC; +import org.sonar.squidbridge.rules.SqaleXmlLoader; + +public final class OCLintRulesDefinition implements RulesDefinition { + public static final String REPOSITORY_KEY = "OCLint"; + public static final String REPOSITORY_NAME = REPOSITORY_KEY; + + @Override + public void define(Context context) { + NewRepository repository = context + .createRepository(REPOSITORY_KEY, ObjectiveC.KEY) + .setName(REPOSITORY_NAME); + + RulesDefinitionXmlLoader ruleLoader = new RulesDefinitionXmlLoader(); + ruleLoader.load( + repository, + OCLintRulesDefinition.class.getResourceAsStream("/org/sonar/plugins/objectivec/rules-oclint.xml"), + "UTF-8"); + + SqaleXmlLoader.load(repository, "/com/sonar/sqale/oclint-model.xml"); + + repository.done(); + } +} diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/oclint/OCLintSensor.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/oclint/OCLintSensor.java new file mode 100644 index 00000000..ec807ff3 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/oclint/OCLintSensor.java @@ -0,0 +1,76 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec.oclint; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sonar.api.batch.Sensor; +import org.sonar.api.batch.SensorContext; +import org.sonar.api.batch.fs.FileSystem; +import org.sonar.api.component.ResourcePerspectives; +import org.sonar.api.config.Settings; +import org.sonar.api.resources.Project; +import org.sonar.api.scan.filesystem.PathResolver; + +import java.io.File; + +public final class OCLintSensor implements Sensor { + private static final Logger LOGGER = LoggerFactory.getLogger(OCLintSensor.class); + + public static final String REPORT_PATH_KEY = "sonar.objectivec.oclint.reportPath"; + + private final FileSystem fileSystem; + private final PathResolver pathResolver; + private final ResourcePerspectives resourcePerspectives; + private final Settings settings; + + public OCLintSensor(final FileSystem fileSystem, final PathResolver pathResolver, + final ResourcePerspectives resourcePerspectives, final Settings settings) { + this.fileSystem = fileSystem; + this.pathResolver = pathResolver; + this.resourcePerspectives = resourcePerspectives; + this.settings = settings; + } + + @Override + public boolean shouldExecuteOnProject(final Project project) { + return StringUtils.isNotEmpty(settings.getString(REPORT_PATH_KEY)); + } + + @Override + public void analyse(final Project project, final SensorContext context) { + String path = settings.getString(REPORT_PATH_KEY); + File report = pathResolver.relativeFile(fileSystem.baseDir(), path); + + if (!report.isFile()) { + LOGGER.warn("OCLint report not found at {}", report); + return; + } + + LOGGER.info("parsing {}", report); + OCLintParser.parseReport(report, fileSystem, context, resourcePerspectives); + } + + @Override + public String toString() { + return "Objective-C OCLint Sensor"; + } +} diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/oclint/package-info.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/oclint/package-info.java new file mode 100644 index 00000000..bd75b693 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/oclint/package-info.java @@ -0,0 +1,23 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +@ParametersAreNonnullByDefault +package org.sonar.plugins.objectivec.oclint; + +import javax.annotation.ParametersAreNonnullByDefault; \ No newline at end of file diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/package-info.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/package-info.java new file mode 100644 index 00000000..63e03fd3 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/package-info.java @@ -0,0 +1,23 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +@ParametersAreNonnullByDefault +package org.sonar.plugins.objectivec; + +import javax.annotation.ParametersAreNonnullByDefault; \ No newline at end of file diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/SurefireParser.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/SurefireParser.java new file mode 100644 index 00000000..460c026c --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/SurefireParser.java @@ -0,0 +1,199 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec.surefire; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sonar.api.batch.SensorContext; +import org.sonar.api.batch.fs.FileSystem; +import org.sonar.api.batch.fs.InputFile; +import org.sonar.api.component.ResourcePerspectives; +import org.sonar.api.measures.CoreMetrics; +import org.sonar.api.measures.Metric; +import org.sonar.api.resources.Resource; +import org.sonar.api.test.MutableTestPlan; +import org.sonar.api.test.TestCase; +import org.sonar.api.utils.ParsingUtils; +import org.sonar.api.utils.StaxParser; +import org.sonar.plugins.objectivec.surefire.data.SurefireStaxHandler; +import org.sonar.plugins.objectivec.surefire.data.UnitTestClassReport; +import org.sonar.plugins.objectivec.surefire.data.UnitTestIndex; +import org.sonar.plugins.objectivec.surefire.data.UnitTestResult; + +import javax.xml.stream.XMLStreamException; +import java.io.File; +import java.io.FilenameFilter; +import java.util.List; +import java.util.Map; + +public final class SurefireParser { + private static final Logger LOGGER = LoggerFactory.getLogger(SurefireParser.class); + + private final FileSystem fileSystem; + private final SensorContext context; + private final ResourcePerspectives perspectives; + + public SurefireParser(FileSystem fileSystem, ResourcePerspectives perspectives, + SensorContext context) { + this.fileSystem = fileSystem; + this.perspectives = perspectives; + this.context = context; + } + + public void collect(File reportsDir) { + File[] xmlFiles = getReports(reportsDir); + + if (xmlFiles.length == 0) { + insertZeroWhenNoReports(); + } else { + parseFiles(xmlFiles); + } + } + + private File[] getReports(File dir) { + if (!dir.isDirectory() || !dir.exists()) { + return new File[0]; + } + + return dir.listFiles(new FilenameFilter() { + @Override + public boolean accept(File dir, String name) { + return name.startsWith("TEST") && name.endsWith(".xml"); + } + }); + } + + private void insertZeroWhenNoReports() { + context.saveMeasure(CoreMetrics.TESTS, 0.0); + } + + private void parseFiles(File[] reports) { + UnitTestIndex index = new UnitTestIndex(); + parseFiles(reports, index); + sanitize(index); + save(index); + } + + private static void parseFiles(File[] reports, UnitTestIndex index) { + SurefireStaxHandler staxParser = new SurefireStaxHandler(index); + StaxParser parser = new StaxParser(staxParser, false); + for (File report : reports) { + try { + parser.parse(report); + } catch (XMLStreamException e) { + throw new IllegalStateException("Fail to parse the Surefire report: " + report, e); + } + } + } + + private static void sanitize(UnitTestIndex index) { + for (String classname : index.getClassnames()) { + if (StringUtils.contains(classname, "$")) { + // Surefire reports classes whereas sonar supports files + String parentClassName = StringUtils.substringBefore(classname, "$"); + index.merge(classname, parentClassName); + } + } + } + + private void save(UnitTestIndex index) { + long negativeTimeTestNumber = 0; + for (Map.Entry entry : index.getIndexByClassname().entrySet()) { + UnitTestClassReport report = entry.getValue(); + if (report.getTests() > 0) { + negativeTimeTestNumber += report.getNegativeTimeTestNumber(); + Resource resource = getUnitTestResource(entry.getKey()); + if (resource != null) { + save(report, resource); + } else { + LOGGER.warn("Resource not found: {}", entry.getKey()); + } + } + } + if (negativeTimeTestNumber > 0) { + LOGGER.warn("There is {} test(s) reported with negative time by surefire, total duration may not be accurate.", negativeTimeTestNumber); + } + } + + private void save(UnitTestClassReport report, Resource resource) { + double testsCount = report.getTests() - report.getSkipped(); + saveMeasure(resource, CoreMetrics.SKIPPED_TESTS, report.getSkipped()); + saveMeasure(resource, CoreMetrics.TESTS, testsCount); + saveMeasure(resource, CoreMetrics.TEST_ERRORS, report.getErrors()); + saveMeasure(resource, CoreMetrics.TEST_FAILURES, report.getFailures()); + saveMeasure(resource, CoreMetrics.TEST_EXECUTION_TIME, report.getDurationMilliseconds()); + double passedTests = testsCount - report.getErrors() - report.getFailures(); + if (testsCount > 0) { + double percentage = passedTests * 100d / testsCount; + saveMeasure(resource, CoreMetrics.TEST_SUCCESS_DENSITY, ParsingUtils.scaleValue(percentage)); + } + saveResults(resource, report); + } + + protected void saveResults(Resource testFile, UnitTestClassReport report) { + for (UnitTestResult unitTestResult : report.getResults()) { + MutableTestPlan testPlan = perspectives.as(MutableTestPlan.class, testFile); + if (testPlan != null) { + testPlan.addTestCase(unitTestResult.getName()) + .setDurationInMs(Math.max(unitTestResult.getDurationMilliseconds(), 0)) + .setStatus(TestCase.Status.of(unitTestResult.getStatus())) + .setMessage(unitTestResult.getMessage()) + .setType(TestCase.TYPE_UNIT) + .setStackTrace(unitTestResult.getStackTrace()); + } + } + } + + public Resource getUnitTestResource(String classname) { + String fileName = classname.replace('.', '/') + ".m"; + + InputFile inputFile = fileSystem.inputFile(fileSystem.predicates().hasPath(fileName)); + + /* + * Most xcodebuild JUnit parsers don't include the path to the class in the class field, so search for it if it + * wasn't found in the root. + */ + if (inputFile == null) { + List files = ImmutableList.copyOf(fileSystem.inputFiles(fileSystem.predicates().and( + fileSystem.predicates().hasType(InputFile.Type.TEST), + fileSystem.predicates().matchesPathPattern("**/" + fileName)))); + + if (files.isEmpty()) { + LOGGER.info("Unable to locate test source file {}", fileName); + } else { + /* + * Lazily get the first file, since we wouldn't be able to determine the correct one from just the + * test class name in the event that there are multiple matches. + */ + inputFile = files.get(0); + } + } + + return inputFile == null ? null : context.getResource(inputFile); + } + + private void saveMeasure(Resource resource, Metric metric, double value) { + if (!Double.isNaN(value)) { + context.saveMeasure(resource, metric, value); + } + } +} diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/SurefireSensor.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/SurefireSensor.java new file mode 100644 index 00000000..fb3331d7 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/SurefireSensor.java @@ -0,0 +1,80 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec.surefire; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sonar.api.batch.Sensor; +import org.sonar.api.batch.SensorContext; +import org.sonar.api.batch.fs.FileSystem; +import org.sonar.api.component.ResourcePerspectives; +import org.sonar.api.config.Settings; +import org.sonar.api.resources.Project; +import org.sonar.api.scan.filesystem.PathResolver; + +import java.io.File; + +public final class SurefireSensor implements Sensor { + private static final Logger LOGGER = LoggerFactory.getLogger(SurefireSensor.class); + + public static final String REPORTS_PATH_KEY = "sonar.objectivec.junit.reportsPath"; + + private final FileSystem fileSystem; + private final PathResolver pathResolver; + private final ResourcePerspectives resourcePerspectives; + private final Settings settings; + + public SurefireSensor(FileSystem fileSystem, PathResolver pathResolver, ResourcePerspectives resourcePerspectives, + Settings settings) { + this.fileSystem = fileSystem; + this.pathResolver = pathResolver; + this.resourcePerspectives = resourcePerspectives; + this.settings = settings; + } + + @Override + public boolean shouldExecuteOnProject(Project project) { + return StringUtils.isNotEmpty(settings.getString(REPORTS_PATH_KEY)); + } + + @Override + public void analyse(Project project, SensorContext context) { + String path = settings.getString(REPORTS_PATH_KEY); + File reportsDir = pathResolver.relativeFile(fileSystem.baseDir(), path); + + if (!reportsDir.isDirectory()) { + LOGGER.warn("JUnit report directory not found at {}", reportsDir); + return; + } + + collect(context, reportsDir); + } + + protected void collect(SensorContext context, File reportsDir) { + LOGGER.info("parsing {}", reportsDir); + new SurefireParser(fileSystem, resourcePerspectives, context).collect(reportsDir); + } + + @Override + public String toString() { + return "Objective-C Surefire Sensor"; + } +} \ No newline at end of file diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/data/SurefireStaxHandler.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/data/SurefireStaxHandler.java new file mode 100644 index 00000000..468f06ac --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/data/SurefireStaxHandler.java @@ -0,0 +1,142 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec.surefire.data; + +import org.apache.commons.lang.StringUtils; +import org.codehaus.staxmate.in.ElementFilter; +import org.codehaus.staxmate.in.SMEvent; +import org.codehaus.staxmate.in.SMHierarchicCursor; +import org.codehaus.staxmate.in.SMInputCursor; +import org.sonar.api.utils.ParsingUtils; +import org.sonar.api.utils.StaxParser.XmlStreamHandler; + +import javax.xml.stream.XMLStreamException; +import java.text.ParseException; +import java.util.Locale; + +public class SurefireStaxHandler implements XmlStreamHandler { + + private final UnitTestIndex index; + + public SurefireStaxHandler(UnitTestIndex index) { + this.index = index; + } + + @Override + public void stream(SMHierarchicCursor rootCursor) throws XMLStreamException { + SMInputCursor testSuite = rootCursor.constructDescendantCursor(new ElementFilter("testsuite")); + SMEvent testSuiteEvent; + for (testSuiteEvent = testSuite.getNext(); testSuiteEvent != null; testSuiteEvent = testSuite.getNext()) { + if (testSuiteEvent.compareTo(SMEvent.START_ELEMENT) == 0) { + String testSuiteClassName = testSuite.getAttrValue("name"); + if (StringUtils.contains(testSuiteClassName, "$")) { + // test suites for inner classes are ignored + return; + } + SMInputCursor testCase = testSuite.childCursor(new ElementFilter("testcase")); + SMEvent event; + for (event = testCase.getNext(); event != null; event = testCase.getNext()) { + if (event.compareTo(SMEvent.START_ELEMENT) == 0) { + String testClassName = getClassname(testCase, testSuiteClassName); + UnitTestClassReport classReport = index.index(testClassName); + parseTestCase(testCase, classReport); + } + } + } + } + } + + private static String getClassname(SMInputCursor testCaseCursor, + String defaultClassname) throws XMLStreamException { + String testClassName = testCaseCursor.getAttrValue("classname"); + if (StringUtils.isNotBlank(testClassName) && testClassName.endsWith(")")) { + testClassName = testClassName.substring(0, testClassName.indexOf("(")); + } + return StringUtils.defaultIfBlank(testClassName, defaultClassname); + } + + private static void parseTestCase(SMInputCursor testCaseCursor, + UnitTestClassReport report) throws XMLStreamException { + report.add(parseTestResult(testCaseCursor)); + } + + private static void setStackAndMessage(UnitTestResult result, + SMInputCursor stackAndMessageCursor) throws XMLStreamException { + result.setMessage(stackAndMessageCursor.getAttrValue("message")); + String stack = stackAndMessageCursor.collectDescendantText(); + result.setStackTrace(stack); + } + + private static UnitTestResult parseTestResult(SMInputCursor testCaseCursor) throws XMLStreamException { + UnitTestResult detail = new UnitTestResult(); + String name = getTestCaseName(testCaseCursor); + detail.setName(name); + + String status = UnitTestResult.STATUS_OK; + String time = testCaseCursor.getAttrValue("time"); + Long duration = null; + + SMInputCursor childNode = testCaseCursor.descendantElementCursor(); + if (childNode.getNext() != null) { + String elementName = childNode.getLocalName(); + if ("skipped".equals(elementName)) { + status = UnitTestResult.STATUS_SKIPPED; + // bug with surefire reporting wrong time for skipped tests + duration = 0L; + + } else if ("failure".equals(elementName)) { + status = UnitTestResult.STATUS_FAILURE; + setStackAndMessage(detail, childNode); + + } else if ("error".equals(elementName)) { + status = UnitTestResult.STATUS_ERROR; + setStackAndMessage(detail, childNode); + } + } + while (childNode.getNext() != null) { + // make sure we loop till the end of the elements cursor + } + if (duration == null) { + duration = getTimeAttributeInMS(time); + } + detail.setDurationMilliseconds(duration); + detail.setStatus(status); + return detail; + } + + private static long getTimeAttributeInMS(String value) throws XMLStreamException { + // hardcoded to Locale.ENGLISH see http://jira.codehaus.org/browse/SONAR-602 + try { + Double time = ParsingUtils.parseNumber(value, Locale.ENGLISH); + return !Double.isNaN(time) ? (long) ParsingUtils.scaleValue(time * 1000, 3) : 0L; + } catch (ParseException e) { + throw new XMLStreamException(e); + } + } + + private static String getTestCaseName(SMInputCursor testCaseCursor) throws XMLStreamException { + String classname = testCaseCursor.getAttrValue("classname"); + String name = testCaseCursor.getAttrValue("name"); + if (StringUtils.contains(classname, "$")) { + return StringUtils.substringAfter(classname, "$") + "/" + name; + } + return name; + } +} diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/data/UnitTestClassReport.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/data/UnitTestClassReport.java new file mode 100644 index 00000000..67ef222e --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/data/UnitTestClassReport.java @@ -0,0 +1,102 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec.surefire.data; + +import com.google.common.collect.Lists; + +import java.util.Collections; +import java.util.List; + +public final class UnitTestClassReport { + private long errors = 0L; + private long failures = 0L; + private long skipped = 0L; + private long tests = 0L; + private long durationMilliseconds = 0L; + + + private long negativeTimeTestNumber = 0L; + private List results = null; + + public UnitTestClassReport add(UnitTestClassReport other) { + for (UnitTestResult otherResult : other.getResults()) { + add(otherResult); + } + return this; + } + + public UnitTestClassReport add(UnitTestResult result) { + initResults(); + results.add(result); + if (result.getStatus().equals(UnitTestResult.STATUS_SKIPPED)) { + skipped += 1; + + } else if (result.getStatus().equals(UnitTestResult.STATUS_FAILURE)) { + failures += 1; + + } else if (result.getStatus().equals(UnitTestResult.STATUS_ERROR)) { + errors += 1; + } + tests += 1; + if (result.getDurationMilliseconds() < 0) { + negativeTimeTestNumber += 1; + } else { + durationMilliseconds += result.getDurationMilliseconds(); + } + return this; + } + + private void initResults() { + if (results == null) { + results = Lists.newArrayList(); + } + } + + public long getErrors() { + return errors; + } + + public long getFailures() { + return failures; + } + + public long getSkipped() { + return skipped; + } + + public long getTests() { + return tests; + } + + public long getDurationMilliseconds() { + return durationMilliseconds; + } + + public long getNegativeTimeTestNumber() { + return negativeTimeTestNumber; + } + + public List getResults() { + if (results == null) { + return Collections.emptyList(); + } + return results; + } +} diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/data/UnitTestIndex.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/data/UnitTestIndex.java new file mode 100644 index 00000000..038cdc18 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/data/UnitTestIndex.java @@ -0,0 +1,80 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec.surefire.data; + +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; + +import java.util.Map; +import java.util.Set; + +/** + * @since 2.8 + */ +public class UnitTestIndex { + + private Map indexByClassname; + + public UnitTestIndex() { + this.indexByClassname = Maps.newHashMap(); + } + + public UnitTestClassReport index(String classname) { + UnitTestClassReport classReport = indexByClassname.get(classname); + if (classReport == null) { + classReport = new UnitTestClassReport(); + indexByClassname.put(classname, classReport); + } + return classReport; + } + + public UnitTestClassReport get(String classname) { + return indexByClassname.get(classname); + } + + public Set getClassnames() { + return Sets.newHashSet(indexByClassname.keySet()); + } + + public Map getIndexByClassname() { + return indexByClassname; + } + + public int size() { + return indexByClassname.size(); + } + + public UnitTestClassReport merge(String classname, String intoClassname) { + UnitTestClassReport from = indexByClassname.get(classname); + if (from!=null) { + UnitTestClassReport to = index(intoClassname); + to.add(from); + indexByClassname.remove(classname); + return to; + } + return null; + } + + public void remove(String classname) { + indexByClassname.remove(classname); + } + + +} \ No newline at end of file diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/data/UnitTestResult.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/data/UnitTestResult.java new file mode 100644 index 00000000..c50a3af7 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/data/UnitTestResult.java @@ -0,0 +1,86 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec.surefire.data; + +public final class UnitTestResult { + public static final String STATUS_OK = "ok"; + public static final String STATUS_ERROR = "error"; + public static final String STATUS_FAILURE = "failure"; + public static final String STATUS_SKIPPED = "skipped"; + + private String name; + private String status; + private String stackTrace; + private String message; + private long durationMilliseconds = 0L; + + public String getName() { + return name; + } + + public UnitTestResult setName(String name) { + this.name = name; + return this; + } + + public String getStatus() { + return status; + } + + public UnitTestResult setStatus(String status) { + this.status = status; + return this; + } + + public String getStackTrace() { + return stackTrace; + } + + public UnitTestResult setStackTrace(String stackTrace) { + this.stackTrace = stackTrace; + return this; + } + + public String getMessage() { + return message; + } + + public UnitTestResult setMessage(String message) { + this.message = message; + return this; + } + + public long getDurationMilliseconds() { + return durationMilliseconds; + } + + public UnitTestResult setDurationMilliseconds(long l) { + this.durationMilliseconds = l; + return this; + } + + public boolean isErrorOrFailure() { + return STATUS_ERROR.equals(status) || STATUS_FAILURE.equals(status); + } + + public boolean isError() { + return STATUS_ERROR.equals(status); + } +} diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/data/package-info.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/data/package-info.java new file mode 100644 index 00000000..1d8c4969 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/data/package-info.java @@ -0,0 +1,23 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +@ParametersAreNonnullByDefault +package org.sonar.plugins.objectivec.surefire.data; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/package-info.java b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/package-info.java new file mode 100644 index 00000000..2050a09d --- /dev/null +++ b/sonar-objective-c-plugin/src/main/java/org/sonar/plugins/objectivec/surefire/package-info.java @@ -0,0 +1,23 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +@ParametersAreNonnullByDefault +package org.sonar.plugins.objectivec.surefire; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sonar-objective-c-plugin/src/main/resources/com/sonar/sqale/clang-model.xml b/sonar-objective-c-plugin/src/main/resources/com/sonar/sqale/clang-model.xml new file mode 100644 index 00000000..ba8c52e7 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/resources/com/sonar/sqale/clang-model.xml @@ -0,0 +1,334 @@ + + + REUSABILITY + Reusability + + MODULARITY + Modularity + + + TRANSPORTABILITY + Transportability + + + + PORTABILITY + Portability + + COMPILER_RELATED_PORTABILITY + Compiler + + + HARDWARE_RELATED_PORTABILITY + Hardware + + + LANGUAGE_RELATED_PORTABILITY + Language + + + OS_RELATED_PORTABILITY + OS + + + SOFTWARE_RELATED_PORTABILITY + Software + + + TIME_ZONE_RELATED_PORTABILITY + Time zone + + + + MAINTAINABILITY + Maintainability + + READABILITY + Readability + + + UNDERSTANDABILITY + Understandability + + + + SECURITY + Security + + API_ABUSE + API abuse + + + ERRORS + Errors + + + INPUT_VALIDATION_AND_REPRESENTATION + Input validation and representation + + + SECURITY_FEATURES + Security features + + + + EFFICIENCY + Efficiency + + MEMORY_EFFICIENCY + Memory use + + clang + osx.cocoa.RetainCount + + remediationFunction + CONSTANT_ISSUE + + + remediationFactor + 0.0 + d + + + offset + 30.0 + mn + + + + + CPU_EFFICIENCY + Processor use + + + + CHANGEABILITY + Changeability + + ARCHITECTURE_CHANGEABILITY + Architecture + + + DATA_CHANGEABILITY + Data + + + LOGIC_CHANGEABILITY + Logic + + + + RELIABILITY + Reliability + + ARCHITECTURE_RELIABILITY + Architecture + + clang + osx.cocoa.NSError + + remediationFunction + CONSTANT_ISSUE + + + remediationFactor + 0.0 + d + + + offset + 30.0 + mn + + + + clang + osx.cocoa.MissingSuperCall + + remediationFunction + CONSTANT_ISSUE + + + remediationFactor + 0.0 + d + + + offset + 30.0 + mn + + + + + DATA_RELIABILITY + Data + + clang + core.UndefinedBinaryOperatorResult + + remediationFunction + CONSTANT_ISSUE + + + remediationFactor + 0.0 + d + + + offset + 30.0 + mn + + + + clang + core.uninitialized.Assign + + remediationFunction + CONSTANT_ISSUE + + + remediationFactor + 0.0 + d + + + offset + 30.0 + mn + + + + clang + core.uninitialized.Branch + + remediationFunction + CONSTANT_ISSUE + + + remediationFactor + 0.0 + d + + + offset + 30.0 + mn + + + + clang + core.uninitialized.UndefReturn + + remediationFunction + CONSTANT_ISSUE + + + remediationFactor + 0.0 + d + + + offset + 30.0 + mn + + + + clang + deadcode.DeadStores + + remediationFunction + CONSTANT_ISSUE + + + remediationFactor + 0.0 + d + + + offset + 30.0 + mn + + + + + EXCEPTION_HANDLING + Exception handling + + + FAULT_TOLERANCE + Fault tolerance + + + INSTRUCTION_RELIABILITY + Instruction + + + LOGIC_RELIABILITY + Logic + + clang + other + + remediationFunction + CONSTANT_ISSUE + + + remediationFactor + 0.0 + d + + + offset + 30.0 + mn + + + + + RESOURCE_RELIABILITY + Resource + + + SYNCHRONIZATION_RELIABILITY + Synchronization + + clang + osx.cocoa.AtSync + + remediationFunction + CONSTANT_ISSUE + + + remediationFactor + 0.0 + d + + + offset + 30.0 + mn + + + + + UNIT_TESTS + Unit tests coverage + + + + TESTABILITY + Testability + + INTEGRATION_TESTABILITY + Integration level + + + UNIT_TESTABILITY + Unit level + + + diff --git a/src/main/resources/com/sonar/sqale/objectivec-model.xml b/sonar-objective-c-plugin/src/main/resources/com/sonar/sqale/oclint-model.xml similarity index 93% rename from src/main/resources/com/sonar/sqale/objectivec-model.xml rename to sonar-objective-c-plugin/src/main/resources/com/sonar/sqale/oclint-model.xml index 42c209fb..b64f6550 100644 --- a/src/main/resources/com/sonar/sqale/objectivec-model.xml +++ b/sonar-objective-c-plugin/src/main/resources/com/sonar/sqale/oclint-model.xml @@ -50,17 +50,17 @@ unused method parameter remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -68,17 +68,17 @@ unused local variable remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -86,17 +86,17 @@ replace with number literal remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -104,17 +104,17 @@ replace with boxed expression remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -122,17 +122,17 @@ unnecessary else statement remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -140,17 +140,17 @@ redundant local variable remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -158,17 +158,17 @@ redundant if statement remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -176,17 +176,17 @@ redundant conditional operator remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -194,17 +194,17 @@ replace with container literal remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -212,17 +212,17 @@ long line remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -230,17 +230,17 @@ long method remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 30 - mn + 0.0 + d offset - 0.0 - d + 30 + mn @@ -248,17 +248,17 @@ for loop should be while loop remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -266,17 +266,17 @@ too many methods remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 1 - h + 0.0 + d offset - 0.0 - d + 1 + h @@ -284,17 +284,17 @@ long class remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 1 - h + 0.0 + d offset - 0.0 - d + 1 + h @@ -302,17 +302,17 @@ too many fields remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 1 - h + 0.0 + d offset - 0.0 - d + 1 + h @@ -320,17 +320,17 @@ collapsible if statements remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 30 - mn + 0.0 + d offset - 0.0 - d + 30 + mn @@ -338,17 +338,17 @@ deep nested block remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 30 - mn + 0.0 + d offset - 0.0 - d + 30 + mn @@ -356,17 +356,17 @@ high cyclomatic complexity remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 30 - mn + 0.0 + d offset - 0.0 - d + 30 + mn @@ -374,17 +374,17 @@ too few branches in switch statement remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -392,17 +392,17 @@ non case label in switch statement remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -410,17 +410,17 @@ short variable name remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -428,17 +428,17 @@ long variable name remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -446,17 +446,17 @@ default label not last in switch statement remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -464,17 +464,17 @@ replace with object subscripting remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -486,17 +486,17 @@ useless parentheses remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -504,17 +504,17 @@ use early exits and continue remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -522,17 +522,17 @@ high npath complexity remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 30 - mn + 0.0 + d offset - 0.0 - d + 30 + mn @@ -540,17 +540,17 @@ inverted logic remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -558,17 +558,17 @@ multiple unary operator remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -576,17 +576,17 @@ redundant nil check remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -594,17 +594,17 @@ high ncss method remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -612,17 +612,17 @@ dead code remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -630,17 +630,17 @@ double negative remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -648,17 +648,17 @@ bitwise operator in conditional remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -666,17 +666,17 @@ empty if statement remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -684,17 +684,17 @@ empty while statement remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -702,17 +702,17 @@ empty else block remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -720,17 +720,17 @@ empty for statement remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -738,17 +738,17 @@ empty do/while statement remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -756,17 +756,17 @@ empty switch statement remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -774,17 +774,17 @@ too many parameters remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 30 - mn + 0.0 + d offset - 0.0 - d + 30 + mn @@ -792,17 +792,17 @@ switch statements don't need default when fully covered remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -874,17 +874,17 @@ empty finally statement remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -892,17 +892,17 @@ return from finally block remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -910,17 +910,17 @@ empty catch statement remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -928,17 +928,17 @@ empty try statement remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -946,17 +946,17 @@ throw exception from finally block remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -972,17 +972,17 @@ must override hash with isEqual remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -990,17 +990,17 @@ parameter reassignment remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 30 - mn + 0.0 + d offset - 0.0 - d + 30 + mn @@ -1008,17 +1008,17 @@ ivar assignment outside accessors or init remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -1030,17 +1030,17 @@ missing break in switch statement remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -1048,17 +1048,17 @@ avoid branching statement as last in loop remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 30 - mn + 0.0 + d offset - 0.0 - d + 30 + mn @@ -1066,17 +1066,17 @@ switch statements should have default remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -1084,17 +1084,17 @@ jumbled incrementer remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -1102,17 +1102,17 @@ broken null check remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -1120,17 +1120,17 @@ broken nil check remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -1138,17 +1138,17 @@ broken oddness check remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -1156,17 +1156,17 @@ misplaced nil check remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -1174,17 +1174,17 @@ misplaced null check remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -1192,17 +1192,17 @@ goto statement remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 30 - mn + 0.0 + d offset - 0.0 - d + 30 + mn @@ -1210,17 +1210,17 @@ goto statement remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 30 - mn + 0.0 + d offset - 0.0 - d + 30 + mn @@ -1228,17 +1228,17 @@ constant if expression remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn @@ -1246,17 +1246,17 @@ constant conditional operator remediationFunction - linear + CONSTANT_ISSUE remediationFactor - 10 - mn + 0.0 + d offset - 0.0 - d + 10 + mn diff --git a/sonar-objective-c-plugin/src/main/resources/org/sonar/plugins/objectivec/profile-clang.xml b/sonar-objective-c-plugin/src/main/resources/org/sonar/plugins/objectivec/profile-clang.xml new file mode 100644 index 00000000..d5368d41 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/resources/org/sonar/plugins/objectivec/profile-clang.xml @@ -0,0 +1,50 @@ + + Clang + objectivec + + + clang + core.CallAndMessage + + + clang + core.UndefinedBinaryOperatorResult + + + clang + core.uninitialized.Assign + + + clang + core.uninitialized.Branch + + + clang + core.uninitialized.UndefReturn + + + clang + deadcode.DeadStores + + + clang + osx.cocoa.AtSync + + + clang + osx.cocoa.MissingSuperCall + + + clang + osx.cocoa.NSError + + + clang + osx.cocoa.RetainCount + + + clang + other + + + diff --git a/sonar-objective-c-plugin/src/main/resources/org/sonar/plugins/objectivec/profile-oclint.xml b/sonar-objective-c-plugin/src/main/resources/org/sonar/plugins/objectivec/profile-oclint.xml new file mode 100644 index 00000000..078e7679 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/resources/org/sonar/plugins/objectivec/profile-oclint.xml @@ -0,0 +1,258 @@ + + OCLint + objectivec + + + OCLint + bitwise operator in conditional + + + OCLint + broken nil check + + + OCLint + broken null check + + + OCLint + broken oddness check + + + OCLint + collapsible if statements + + + OCLint + constant conditional operator + + + OCLint + constant if expression + + + OCLint + dead code + + + OCLint + double negative + + + OCLint + for loop should be while loop + + + OCLint + goto statement + + + OCLint + misplaced nil check + + + OCLint + misplaced null check + + + OCLint + multiple unary operator + + + OCLint + return from finally block + + + OCLint + throw exception from finally block + + + OCLint + avoid branching statement as last in loop + + + OCLint + default label not last in switch statement + + + OCLint + inverted logic + + + OCLint + non case label in switch statement + + + OCLint + parameter reassignment + + + OCLint + switch statements should have default + + + OCLint + too few branches in switch statement + + + OCLint + empty catch statement + + + OCLint + empty do/while statement + + + OCLint + empty else block + + + OCLint + empty finally statement + + + OCLint + empty for statement + + + OCLint + empty if statement + + + OCLint + empty switch statement + + + OCLint + empty try statement + + + OCLint + empty while statement + + + OCLint + replace with boxed expression + + + OCLint + replace with container literal + + + OCLint + replace with number literal + + + OCLint + replace with object subscripting + + + OCLint + long variable name + + + OCLint + short variable name + + + OCLint + redundant conditional operator + + + OCLint + redundant if statement + + + OCLint + redundant local variable + + + OCLint + redundant nil check + + + OCLint + unnecessary else statement + + + OCLint + useless parentheses + + + OCLint + high cyclomatic complexity + + + OCLint + long class + + + OCLint + long line + + + OCLint + long method + + + OCLint + high ncss method + + + OCLint + deep nested block + + + OCLint + high npath complexity + + + OCLint + too many fields + + + OCLint + too many methods + + + OCLint + too many parameters + + + OCLint + unused local variable + + + OCLint + unused method parameter + + + OCLint + feature envy + + + OCLint + ivar assignment outside accessors or init + + + OCLint + jumbled incrementer + + + OCLint + missing break in switch statement + + + OCLint + must override hash with isEqual + + + OCLint + switch statements don't need default when fully covered + + + OCLint + use early exits and continue + + + diff --git a/sonar-objective-c-plugin/src/main/resources/org/sonar/plugins/objectivec/rules-clang.xml b/sonar-objective-c-plugin/src/main/resources/org/sonar/plugins/objectivec/rules-clang.xml new file mode 100644 index 00000000..aebc0c83 --- /dev/null +++ b/sonar-objective-c-plugin/src/main/resources/org/sonar/plugins/objectivec/rules-clang.xml @@ -0,0 +1,68 @@ + + + core.CallAndMessage + Check for logical errors for function calls and Objective-C message expressions (e.g., uninitialized arguments, null function pointers) + CRITICAL + Check for logical errors for function calls and Objective-C message expressions (e.g., uninitialized arguments, null function pointers) + + + core.UndefinedBinaryOperatorResult + Check for undefined results of binary operators + MAJOR + Check for undefined results of binary operators + + + core.uninitialized.Assign + Check for assigning uninitialized values + MAJOR + Check for assigning uninitialized values + + + core.uninitialized.Branch + Check for uninitialized values used as branch conditions + MAJOR + Check for uninitialized values used as branch conditions + + + core.uninitialized.UndefReturn + Check for uninitialized values being returned to the caller + MAJOR + Check for uninitialized values being returned to the caller + + + deadcode.DeadStores + Check for values stored to variables that are never read afterwards + MAJOR + Check for values stored to variables that are never read afterwards + + + osx.cocoa.AtSync + Check for nil pointers used as mutexes for @synchronized + MAJOR + Check for nil pointers used as mutexes for @synchronized + + + osx.cocoa.MissingSuperCall + Warn about Objective-C methods that lack a necessary call to super + MAJOR + Warn about Objective-C methods that lack a necessary call to super + + + osx.cocoa.NSError + Check usage of NSError** parameters + MAJOR + Check usage of NSError** parameters + + + osx.cocoa.RetainCount + Check for leaks and violations of the Cocoa Memory Management rules + CRITICAL + Check for leaks and violations of the Cocoa Memory Management rules + + + other + All other Clang Static Analyzer warnings + MAJOR + Warning reported by Clang Static Analyzer (uncategorized). + + diff --git a/sonar-objective-c-plugin/src/main/resources/org/sonar/plugins/objectivec/rules-oclint.xml b/sonar-objective-c-plugin/src/main/resources/org/sonar/plugins/objectivec/rules-oclint.xml new file mode 100644 index 00000000..90a612ef --- /dev/null +++ b/sonar-objective-c-plugin/src/main/resources/org/sonar/plugins/objectivec/rules-oclint.xml @@ -0,0 +1,380 @@ + + + bitwise operator in conditional + Bitwise operator in conditional + CRITICAL + Checks for bitwise operations in conditionals. Although being written on purpose in some rare cases, bitwise operations are considered to be too “smart”. Smart code is not easy to understand. + + + broken nil check + Broken nil check + CRITICAL + The broken nil check in Objective-C in some cases returns just the opposite result. + + + broken null check + Broken null check + CRITICAL + The broken null check itself will crash the program. + + + broken oddness check + Broken oddness check + CRITICAL + Checking oddness by x%2==1 won’t work for negative numbers. Use x&1==1, or x%2!=0 instead. + + + collapsible if statements + Collapsible if statements + CRITICAL + This rule detects instances where the conditions of two consecutive if statements can combined into one in order to increase code cleanness and readability. + + + constant conditional operator + Constant conditional operator + CRITICAL + conditionaloperator whose conditionals are always true or always false are confusing. + + + constant if expression + Constant if expression + CRITICAL + if statements whose conditionals are always true or always false are confusing. + + + dead code + Dead code + CRITICAL + Code after return, break, continue, and throw statements are unreachable and will never be executed. + + + double negative + Double negative + CRITICAL + There is no point in using a double negative, it is always positive. + + + for loop should be while loop + For loop should be while loop + CRITICAL + Under certain circumstances, some for loops can be simplified to while loops to make code more concise. + + + goto statement + Goto statement + CRITICAL + “Go To Statement Considered Harmful” + + + misplaced nil check + Misplaced nil check + CRITICAL + The nil check is misplaced. In Objective-C, sending a message to a nil pointer simply does nothing. But code readers may be confused about the misplaced nil check. + + + misplaced null check + Misplaced null check + CRITICAL + The null check is misplaced. In C and C++, sending a message to a null pointer could crash the app. When null is misplaced, either the check is useless or it’s incorrect. + + + multiple unary operator + Multiple unary operator + CRITICAL + Multiple unary operator can always be confusing and should be simplified. + + + return from finally block + Return from finally block + CRITICAL + Returning from a finally block is not recommended. + + + throw exception from finally block + Throw exception from finally block + CRITICAL + Throwing exceptions within a finally block may mask other exceptions or code defects. + + + avoid branching statement as last in loop + Avoid branching statement as last in loop + MAJOR + Having branching statement as the last statement inside a loop is very confusing, and could largely be forgetting of something and turning into a bug. + + + default label not last in switch statement + Default label not last in switch statement + MAJOR + It is very confusing when default label is not the last label in a switch statement. + + + inverted logic + Inverted logic + MAJOR + An inverted logic is hard to understand. + + + non case label in switch statement + Non case label in switch statement + MAJOR + It is very confusing when default label is not the last label in a switch statement. + + + parameter reassignment + Parameter reassignment + MAJOR + Reassigning values to parameters is very problematic in most cases. + + + switch statements should have default + Switch statements should have default + MAJOR + Switch statements should a default statement. + + + too few branches in switch statement + Too few branches in switch statement + MAJOR + To increase code readability, when a switch consists of only a few branches, it’s much better to use if statement. + + + empty catch statement + Empty catch statement + CRITICAL + This rule detects instances where an exception is caught, but nothing is done about it. + + + empty do/while statement + Empty do while statement + CRITICAL + This rule detects instances where a do-while statement does nothing. + + + empty else block + Empty else block + CRITICAL + This rule detects instances where a else statement does nothing. + + + empty finally statement + Empty finally statement + CRITICAL + This rule detects instances where a finally statement does nothing. + + + empty for statement + Empty for statement + CRITICAL + This rule detects instances where a for statement does nothing. + + + empty if statement + Empty if statement + CRITICAL + This rule detects instances where a condition is checked, but nothing is done about it. + + + empty switch statement + Empty switch statement + CRITICAL + This rule detects instances where a switch statement does nothing. + + + empty try statement + Empty try statement + CRITICAL + This rule detects instances where a try statement is empty. + + + empty while statement + Empty while statement + CRITICAL + This rule detects instances where a while statement does nothing. + + + replace with boxed expression + Obj c boxed expressions + MINOR + This rule locates the places that can be migrated to the new Objective-C literals with boxed expressions. + + + replace with container literal + Obj c container literals + MINOR + This rule locates the places that can be migrated to the new Objective-C literals with container literals. + + + replace with number literal + Obj cns number literals + MINOR + This rule locates the places that can be migrated to the new Objective-C literals with number literals. + + + replace with object subscripting + Obj c object subscripting + MINOR + This rule locates the places that can be migrated to the new Objective-C literals with object subscripting. + + + long variable name + Long variable name + MAJOR + Variables with long names harm readability. + + + short variable name + Short variable name + MAJOR + Variable with a short name is hard to understand what it stands for. Variable with name, but the name has number of characters less than the threshold will be emitted. + + + redundant conditional operator + Redundant conditional operator + MINOR + This rule detects three types of redundant conditional operators: + + + redundant if statement + Redundant if statement + MINOR + This rule detects unnecessary if statements. + + + redundant local variable + Redundant local variable + MINOR + This rule detects cases where a variable declaration immediately followed by a return of that variable. + + + redundant nil check + Redundant nil check + MINOR + C/C++-style null check in Objective-C like foo!=nil&&[foobar] is redundant, since sending a message to a nil object in this case simply return a false-y value. + + + unnecessary else statement + Unnecessary else statement + MINOR + When an if statement block ends with a return statement, or all branches in the if statement block end with return statements, then the else statement is unnecessary. The code in the else statement can be run without being in the block. + + + useless parentheses + Useless parentheses + MINOR + This rule detects useless parentheses. + + + high cyclomatic complexity + Cyclomatic complexity + CRITICAL + Cyclomatic complexity is determined by the number of linearly independent paths through a program’s source code. In other words, cyclomatic complexity of a method is measured by the number of decision points, like if, while, and for statements, plus one for the method entry. + + + long class + Long class + MAJOR + Long class generally indicates that this class tries to so many things. Each class should do one thing and one thing well. + + + long line + Long line + MINOR + When number of characters for one line of code is very long, it largely harm the readability. Break long line of code into multiple lines. + + + long method + Long method + MAJOR + Long method generally indicates that this method tries to so many things. Each method should do one thing and one thing well. + + + high ncss method + Ncss method count + CRITICAL + This rule counts number of lines for a method by counting Non Commenting Source Statements (NCSS). NCSS only takes actual statements into consideration, in other words, ignores empty statements, empty blocks, closing brackets or semicolons after closing brackets. Meanwhile, statement that is break into multiple lines contribute only one count. + + + deep nested block + Nested block depth + CRITICAL + This rule indicates blocks nested more deeply than the upper limit. + + + high npath complexity + N path complexity + CRITICAL + NPath complexity is determined by the number of execution paths through that method. Compared to cyclomatic complexity, NPath complexity has two outstanding characteristics: first, it distinguish between different kinds of control flow structures; second, it takes the various type of acyclic paths in a flow graph into consideration. + + + too many fields + Too many fields + CRITICAL + A class with too many fields indicates it does too many things and is lack of proper abstraction. It can be resigned to have fewer fields. + + + too many methods + Too many methods + CRITICAL + A class with too many methods indicates it does too many things and hard to read and understand. It usually contains complicated code, and should be refactored. + + + too many parameters + Too many parameters + CRITICAL + Methods with too many parameters are hard to understand and maintain, and are thirsty for refactorings, like Replace Parameter With method, Introduce Parameter Object, or Preserve Whole Object. + + + unused local variable + Unused local variable + INFO + This rule detects local variables that are declared, but not used. + + + unused method parameter + Unused method parameter + INFO + This rule detects parameters that are not used in the method. + + + feature envy + Feature envy + CRITICAL + Feature envy + + + ivar assignment outside accessors or init + Ivar assignment outside accessors or init + MAJOR + Ivar assignment outside accessors or init + + + jumbled incrementer + Jumbled incrementer + MAJOR + Jumbled incrementer + + + missing break in switch statement + Missing break in switch statement + MAJOR + Missing break in switch statement + + + must override hash with isEqual + Must override hash with isEqual + MINOR + Must override hash with isEqual + + + switch statements don't need default when fully covered + Switch statements don't need default when fully covered + MAJOR + Switch statements don't need default when fully covered + + + use early exits and continue + Use early exits and continue + MAJOR + Use early exits and continue + + diff --git a/sonar-objective-c-plugin/src/test/java/org/sonar/plugins/objectivec/lizard/LizardReportParserTest.java b/sonar-objective-c-plugin/src/test/java/org/sonar/plugins/objectivec/lizard/LizardReportParserTest.java new file mode 100644 index 00000000..a8707d62 --- /dev/null +++ b/sonar-objective-c-plugin/src/test/java/org/sonar/plugins/objectivec/lizard/LizardReportParserTest.java @@ -0,0 +1,220 @@ +/* + * SonarQube Objective-C (Community) Plugin + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.plugins.objectivec.lizard; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.Mockito; +import org.sonar.api.batch.SensorContext; +import org.sonar.api.batch.fs.FileSystem; +import org.sonar.api.component.ResourcePerspectives; +import org.sonar.api.measures.CoreMetrics; +import org.sonar.api.measures.Measure; +import org.sonar.api.profiles.RulesProfile; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; + +/** + * @author Andres Gil Herrera + * @since 03/06/15. + */ +public class LizardReportParserTest { + + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + private File correctFile; + private File incorrectFile; + + @Before + public void setup() throws IOException { + correctFile = createCorrectFile(); + incorrectFile = createIncorrectFile(); + } + + /** + * + * @return dummy lizard xml report to test the parser + * @throws IOException + */ + public File createCorrectFile() throws IOException { + File xmlFile = folder.newFile("correctFile.xml"); + BufferedWriter out = new BufferedWriter(new FileWriter(xmlFile)); + //header + out.write(""); + out.write(""); + //root object and measure + out.write(""); + //items for function + out.write(""); + out.write("2151"); + out.write(""); + out.write("3205"); + //average and close funciton measure + out.write(""); + out.write(""); + out.write(""); + //open file measure and add the labels + out.write(""); + //items for file + out.write(""); + out.write("1200"); + out.write(""); + out.write("286862"); + //add averages + out.write(""); + //add sum + out.write(""); + //close measures and root object + out.write(""); + + out.close(); + + return xmlFile; + } + + /** + * + * @return corrupted dummy lizard report to test the parser + * @throws IOException + */ + public File createIncorrectFile() throws IOException { + File xmlFile = folder.newFile("incorrectFile.xml"); + BufferedWriter out = new BufferedWriter(new FileWriter(xmlFile)); + //header + out.write(""); + out.write(""); + //root object and measure + out.write(""); + //items for function + out.write(""); + out.write("2151"); + out.write(""); + out.write("3205"); + //average and close funciton measure + out.write(""); + out.write(""); + out.write(""); + //open file measure and add the labels + out.write(""); + //items for file 3th value tag has no closing tag + out.write(""); + out.write("1200"); + out.write(""); + out.write("286862"); + //add averages + out.write(""); + //add sum + out.write(""); + //close measures and root object no close tag for measure + out.write(""); + + out.close(); + + return xmlFile; + } + + /** + * this test case test that the parser extract all measures right + */ + @Test + public void parseReportShouldReturnMapWhenXMLFileIsCorrect() { + assertNotNull("correct file is null", correctFile); + + FileSystem fileSystem = mock(FileSystem.class); + ResourcePerspectives resourcePerspectives = mock(ResourcePerspectives.class); + RulesProfile rulesProfile = mock(RulesProfile.class); + SensorContext sensorContext = mock(SensorContext.class); + + Map> report = LizardReportParser.parseReport(fileSystem, resourcePerspectives, + rulesProfile, sensorContext, correctFile); + + assertNotNull("report is null", report); + + assertTrue("Key is not there", report.containsKey("App/Controller/Accelerate/AccelerationViewController.h")); + List list1 = report.get("App/Controller/Accelerate/AccelerationViewController.h"); + assertEquals(4, list1.size()); + + for (Measure measure : list1) { + String s = measure.getMetric().getKey(); + + if (s.equals(CoreMetrics.FUNCTIONS_KEY)) { + assertEquals("Header Functions has a wrong value", 0, measure.getIntValue().intValue()); + } else if (s.equals(CoreMetrics.COMPLEXITY_KEY)) { + assertEquals("Header Complexity has a wrong value", 0, measure.getIntValue().intValue()); + } else if (s.equals(CoreMetrics.FILE_COMPLEXITY_KEY)) { + assertEquals("Header File Complexity has a wrong value", 0.0d, measure.getValue().doubleValue(), 0.0d); + } else if (s.equals(CoreMetrics.COMPLEXITY_IN_FUNCTIONS_KEY)) { + assertEquals("Header Complexity in Functions has a wrong value", 0, measure.getIntValue().intValue()); + } else if (s.equals(CoreMetrics.FUNCTION_COMPLEXITY_KEY)) { + assertEquals("Header Functions Complexity has a wrong value", 0.0d, measure.getValue().doubleValue(), 0.0d); + } + } + + assertTrue("Key is not there", report.containsKey("App/Controller/Accelerate/AccelerationViewController.m")); + + List list2 = report.get("App/Controller/Accelerate/AccelerationViewController.m"); + assertEquals(7, list2.size()); + for (Measure measure : list2) { + String s = measure.getMetric().getKey(); + + if (s.equals(CoreMetrics.FUNCTIONS_KEY)) { + assertEquals("MFile Functions has a wrong value", 2, measure.getIntValue().intValue()); + } else if (s.equals(CoreMetrics.COMPLEXITY_KEY)) { + assertEquals("MFile Complexity has a wrong value", 6, measure.getIntValue().intValue()); + } else if (s.equals(CoreMetrics.FILE_COMPLEXITY_KEY)) { + assertEquals("MFile File Complexity has a wrong value", 6.0d, measure.getValue().doubleValue(), 0.0d); + } else if (s.equals(CoreMetrics.COMPLEXITY_IN_FUNCTIONS_KEY)) { + assertEquals("MFile Complexity in Functions has a wrong value", 6, measure.getIntValue().intValue()); + } else if (s.equals(CoreMetrics.FUNCTION_COMPLEXITY_KEY)) { + assertEquals("MFile Functions Complexity has a wrong value", 3.0d, measure.getValue().doubleValue(), 0.0d); + } + } + } + + /** + * this method test that the parser shoud not return anything if the xml report is corrupted + */ + @Test + public void parseReportShouldReturnNullWhenXMLFileIsIncorrect() { + assertNotNull("correct file is null", incorrectFile); + + FileSystem fileSystem = mock(FileSystem.class); + ResourcePerspectives resourcePerspectives = mock(ResourcePerspectives.class); + RulesProfile rulesProfile = mock(RulesProfile.class); + SensorContext sensorContext = mock(SensorContext.class); + + Map> report = LizardReportParser.parseReport(fileSystem, resourcePerspectives, + rulesProfile, sensorContext, incorrectFile); + assertNull("report is not null", report); + + } + +} diff --git a/sonar-objective-c-plugin/updateRules.groovy b/sonar-objective-c-plugin/updateRules.groovy new file mode 100644 index 00000000..7edc532e --- /dev/null +++ b/sonar-objective-c-plugin/updateRules.groovy @@ -0,0 +1,130 @@ +// Update rules.txt and profile-clint.xml from OCLint documentation +// Priority is determined from the category + +@Grab(group='org.codehaus.groovy.modules.http-builder', + module='http-builder', version='0.7') + +import groovyx.net.http.* +import groovy.util.XmlParser +import groovy.xml.MarkupBuilder + +// Files +def rulesXml() { + new File('src/main/resources/org/sonar/plugins/objectivec/rules-oclint.xml') +} +def profileXml() { + new File('src/main/resources/org/sonar/plugins/objectivec/profile-oclint.xml') +} + +def splitCamelCase(value) { + value.replaceAll( + String.format("%s|%s|%s", + "(?<=[A-Z])(?=[A-Z][a-z])", + "(?<=[^A-Z])(?=[A-Z])", + "(?<=[A-Za-z])(?=[^A-Za-z])" + ), + " " + ).toLowerCase() +} + + +def parseCategory(url, name, priority) { + def rules = new XmlParser().parse(rulesXml()) + + def http = new HTTPBuilder(url) + def html = http.get([:]) + + def root = html.'**'.find { it.@id.toString().contains(name) } + root.'DIV'.each { rule -> + def ruleName = splitCamelCase(rule.H2.text() - '¶').capitalize() + + // Original name + def nameInSource = null + try { + def sourceUrl = rule."**".find { it.name() == 'A' && it.text().contains('oclint-rules/rules') }.@href.toString() + + // Fixes busted URLs in docs + sourceUrl = sourceUrl.replace('EmptyElseStatementRule.cpp', 'EmptyElseBlockRule.cpp') + sourceUrl = sourceUrl.replace('RedundantNilCheck.cpp', 'RedundantNilCheckRule.cpp') + + def sourceHttp = new HTTPBuilder(sourceUrl) + def sourceHtml = sourceHttp.get[:] + + def found = sourceHtml."**".find {it.name() == 'TR' && it.text().contains("return\"")}.text() + def match = found =~ /"([^"]*)"/ + nameInSource = match[0][1] + + } catch (Exception e) { + + } + + if (nameInSource != null) { + + // Overrides for key not being properly detected in source + if (ruleName == "Broken nil check") { + nameInSource = "broken nil check" + } + if (ruleName == "Misplaced nil check") { + nameInSource = "misplaced nil check" + } + + def existingRule = rules.rule.find { it.key.text() == nameInSource } + + if (existingRule) { + existingRule.name[0].value = ruleName + existingRule.description[0].value = rule.P[1].text() + // Keep existing priority + } else { + def newRule = rules.appendNode('rule') + newRule.appendNode('key').value = nameInSource + newRule.appendNode('name').value = ruleName + newRule.appendNode('priority').value = priority + newRule.appendNode('description').value = rule.P[1].text() + } + + println "Retrieved rule ${nameInSource}" + } else { + println "Unable to retrieve rule with name ${ruleName}" + } + } + + def writer = new StringWriter() + def printer = new groovy.util.XmlNodePrinter(new IndentPrinter(writer, " ")) + printer.setPreserveWhitespace true + printer.print(rules) + rulesXml().text = writer.toString() +} + +def writeProfileOCLint() { + def rulesXml = new XmlParser().parse(rulesXml()) + + def writer = new StringWriter() + MarkupBuilder xml = new MarkupBuilder(new IndentPrinter(writer, " ")) + xml.profile() { + name "OCLint" + language "objectivec" + rules { + rulesXml.rule.each { rl -> + rule { + repositoryKey "OCLint" + key rl.key.text() + } + } + } + } + + profileXml().text = writer.toString() +} + + +// Parse OCLint online documentation +parseCategory("http://docs.oclint.org/en/dev/rules/basic.html", "basic", "CRITICAL") +parseCategory("http://docs.oclint.org/en/dev/rules/convention.html", "convention", "MAJOR") +parseCategory("http://docs.oclint.org/en/dev/rules/empty.html", "empty", "CRITICAL") +parseCategory("http://docs.oclint.org/en/dev/rules/migration.html", "migration", "MINOR") +parseCategory("http://docs.oclint.org/en/dev/rules/naming.html", "naming", "MAJOR") +parseCategory("http://docs.oclint.org/en/dev/rules/redundant.html", "redundant", "MINOR") +parseCategory("http://docs.oclint.org/en/dev/rules/size.html", "size", "CRITICAL") +parseCategory("http://docs.oclint.org/en/dev/rules/unused.html", "unused", "INFO") + +writeProfileOCLint() \ No newline at end of file diff --git a/src/main/java/org/sonar/objectivec/api/ObjectiveCGrammar.java b/src/main/java/org/sonar/objectivec/api/ObjectiveCGrammar.java deleted file mode 100644 index f582eea1..00000000 --- a/src/main/java/org/sonar/objectivec/api/ObjectiveCGrammar.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.objectivec.api; - -import com.sonar.sslr.api.Grammar; -import com.sonar.sslr.api.Rule; - -public class ObjectiveCGrammar extends Grammar { - - public Rule identifierName; - - // A.1 Lexical - - public Rule literal; - public Rule nullLiteral; - public Rule booleanLiteral; - public Rule stringLiteral; - - public Rule program; - - public Rule sourceElements; - public Rule sourceElement; - - @Override - public Rule getRootRule() { - return program; - } - -} diff --git a/src/main/java/org/sonar/objectivec/lexer/ObjectiveCLexer.java b/src/main/java/org/sonar/objectivec/lexer/ObjectiveCLexer.java deleted file mode 100644 index c0f72700..00000000 --- a/src/main/java/org/sonar/objectivec/lexer/ObjectiveCLexer.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.objectivec.lexer; - -import static com.sonar.sslr.api.GenericTokenType.LITERAL; -import static com.sonar.sslr.impl.channel.RegexpChannelBuilder.commentRegexp; -import static com.sonar.sslr.impl.channel.RegexpChannelBuilder.regexp; - -import org.sonar.objectivec.ObjectiveCConfiguration; - -import com.sonar.sslr.impl.Lexer; -import com.sonar.sslr.impl.channel.BlackHoleChannel; - -public class ObjectiveCLexer { - - private ObjectiveCLexer() { - } - - public static Lexer create() { - return create(new ObjectiveCConfiguration()); - } - - public static Lexer create(ObjectiveCConfiguration conf) { - return Lexer.builder() - .withCharset(conf.getCharset()) - - .withFailIfNoChannelToConsumeOneCharacter(false) - - // Comments - .withChannel(commentRegexp("//[^\\n\\r]*+")) - .withChannel(commentRegexp("/\\*[\\s\\S]*?\\*/")) - - // All other tokens - .withChannel(regexp(LITERAL, "[^\r\n\\s/]+")) - - .withChannel(new BlackHoleChannel("[\\s]")) - - .build(); - } - -} diff --git a/src/main/java/org/sonar/plugins/objectivec/ObjectiveCPlugin.java b/src/main/java/org/sonar/plugins/objectivec/ObjectiveCPlugin.java deleted file mode 100644 index 8fa3b673..00000000 --- a/src/main/java/org/sonar/plugins/objectivec/ObjectiveCPlugin.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec; - -import java.util.List; - -import org.sonar.api.Extension; -import org.sonar.api.Properties; -import org.sonar.api.Property; -import org.sonar.api.SonarPlugin; -import org.sonar.plugins.objectivec.coverage.CoberturaSensor; -import org.sonar.plugins.objectivec.colorizer.ObjectiveCColorizerFormat; -import org.sonar.plugins.objectivec.core.ObjectiveC; -import org.sonar.plugins.objectivec.core.ObjectiveCSourceImporter; -import org.sonar.plugins.objectivec.cpd.ObjectiveCCpdMapping; - -import com.google.common.collect.ImmutableList; - -import org.sonar.plugins.objectivec.tests.SurefireSensor; -import org.sonar.plugins.objectivec.violations.OCLintProfile; -import org.sonar.plugins.objectivec.violations.OCLintProfileImporter; -import org.sonar.plugins.objectivec.violations.OCLintRuleRepository; -import org.sonar.plugins.objectivec.violations.OCLintSensor; - -@Properties({ - @Property(key = CoberturaSensor.REPORT_PATTERN_KEY, defaultValue = CoberturaSensor.DEFAULT_REPORT_PATTERN, name = "Path to unit test coverage report(s)", description = "Relative to projects' root. Ant patterns are accepted", global = false, project = true), - @Property(key = OCLintSensor.REPORT_PATH_KEY, defaultValue = OCLintSensor.DEFAULT_REPORT_PATH, name = "Path to oclint pmd formatted report", description = "Relative to projects' root.", global = false, project = true) -}) -public class ObjectiveCPlugin extends SonarPlugin { - - public List> getExtensions() { - return ImmutableList.of(ObjectiveC.class, - ObjectiveCSourceImporter.class, - ObjectiveCColorizerFormat.class, - ObjectiveCCpdMapping.class, - - ObjectiveCSquidSensor.class, - ObjectiveCProfile.class, - SurefireSensor.class, - CoberturaSensor.class, - OCLintRuleRepository.class, - OCLintSensor.class, OCLintProfile.class, - OCLintProfileImporter.class - ); - } - - // Global Objective C constants - public static final String FALSE = "false"; - - public static final String FILE_SUFFIXES_KEY = "sonar.objectivec.file.suffixes"; - public static final String FILE_SUFFIXES_DEFVALUE = "h,m"; - - public static final String PROPERTY_PREFIX = "sonar.objectivec"; - - public static final String TEST_FRAMEWORK_KEY = PROPERTY_PREFIX - + ".testframework"; - public static final String TEST_FRAMEWORK_DEFAULT = "ghunit"; - -} diff --git a/src/main/java/org/sonar/plugins/objectivec/ObjectiveCSquidSensor.java b/src/main/java/org/sonar/plugins/objectivec/ObjectiveCSquidSensor.java deleted file mode 100644 index 43bbb5e9..00000000 --- a/src/main/java/org/sonar/plugins/objectivec/ObjectiveCSquidSensor.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec; - -import java.util.Collection; -import java.util.Locale; - -import org.sonar.api.batch.Sensor; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.checks.AnnotationCheckFactory; -import org.sonar.api.measures.CoreMetrics; -import org.sonar.api.measures.PersistenceMode; -import org.sonar.api.measures.RangeDistributionBuilder; -import org.sonar.api.profiles.RulesProfile; -import org.sonar.api.resources.File; -import org.sonar.api.resources.InputFileUtils; -import org.sonar.api.resources.Project; -import org.sonar.api.rules.Violation; -import org.sonar.objectivec.ObjectiveCAstScanner; -import org.sonar.objectivec.ObjectiveCConfiguration; -import org.sonar.objectivec.api.ObjectiveCGrammar; -import org.sonar.objectivec.api.ObjectiveCMetric; -import org.sonar.objectivec.checks.CheckList; -import org.sonar.plugins.objectivec.core.ObjectiveC; -import org.sonar.squidbridge.AstScanner; -import org.sonar.squidbridge.api.CheckMessage; -import org.sonar.squidbridge.api.SourceCode; -import org.sonar.squidbridge.api.SourceFile; -import org.sonar.squidbridge.api.SourceFunction; -import org.sonar.squidbridge.checks.SquidCheck; -import org.sonar.squidbridge.indexer.QueryByParent; -import org.sonar.squidbridge.indexer.QueryByType; -import org.sonar.squidbridge.measures.Metric; - - -public class ObjectiveCSquidSensor implements Sensor { - - private final Number[] FUNCTIONS_DISTRIB_BOTTOM_LIMITS = {1, 2, 4, 6, 8, 10, 12, 20, 30}; - private final Number[] FILES_DISTRIB_BOTTOM_LIMITS = {0, 5, 10, 20, 30, 60, 90}; - - private final AnnotationCheckFactory annotationCheckFactory; - - private Project project; - private SensorContext context; - private AstScanner scanner; - - public ObjectiveCSquidSensor(RulesProfile profile) { - this.annotationCheckFactory = AnnotationCheckFactory.create(profile, CheckList.REPOSITORY_KEY, CheckList.getChecks()); - } - - public boolean shouldExecuteOnProject(Project project) { - return ObjectiveC.KEY.equals(project.getLanguageKey()); - } - - public void analyse(Project project, SensorContext context) { - this.project = project; - this.context = context; - - Collection squidChecks = annotationCheckFactory.getChecks(); - this.scanner = ObjectiveCAstScanner.create(createConfiguration(project), squidChecks.toArray(new SquidCheck[squidChecks.size()])); - scanner.scanFiles(InputFileUtils.toFiles(project.getFileSystem().mainFiles(ObjectiveC.KEY))); - - Collection squidSourceFiles = scanner.getIndex().search(new QueryByType(SourceFile.class)); - save(squidSourceFiles); - } - - private ObjectiveCConfiguration createConfiguration(Project project) { - return new ObjectiveCConfiguration(project.getFileSystem().getSourceCharset()); - } - - private void save(Collection squidSourceFiles) { - for (SourceCode squidSourceFile : squidSourceFiles) { - SourceFile squidFile = (SourceFile) squidSourceFile; - - File sonarFile = File.fromIOFile(new java.io.File(squidFile.getKey()), project); - - saveFilesComplexityDistribution(sonarFile, squidFile); - saveFunctionsComplexityDistribution(sonarFile, squidFile); - saveMeasures(sonarFile, squidFile); - saveViolations(sonarFile, squidFile); - } - } - - private void saveMeasures(File sonarFile, SourceFile squidFile) { - context.saveMeasure(sonarFile, CoreMetrics.FILES, squidFile.getDouble(ObjectiveCMetric.FILES)); - context.saveMeasure(sonarFile, CoreMetrics.LINES, squidFile.getDouble(ObjectiveCMetric.LINES)); - context.saveMeasure(sonarFile, CoreMetrics.NCLOC, squidFile.getDouble(ObjectiveCMetric.LINES_OF_CODE)); - context.saveMeasure(sonarFile, CoreMetrics.FUNCTIONS, squidFile.getDouble(ObjectiveCMetric.FUNCTIONS)); - context.saveMeasure(sonarFile, CoreMetrics.STATEMENTS, squidFile.getDouble(ObjectiveCMetric.STATEMENTS)); - context.saveMeasure(sonarFile, CoreMetrics.COMPLEXITY, squidFile.getDouble(ObjectiveCMetric.COMPLEXITY)); - context.saveMeasure(sonarFile, CoreMetrics.COMMENT_LINES, squidFile.getDouble(ObjectiveCMetric.COMMENT_LINES)); - } - - private void saveFunctionsComplexityDistribution(File sonarFile, SourceFile squidFile) { - Collection squidFunctionsInFile = scanner.getIndex().search(new QueryByParent(squidFile), new QueryByType(SourceFunction.class)); - RangeDistributionBuilder complexityDistribution = new RangeDistributionBuilder(CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION, FUNCTIONS_DISTRIB_BOTTOM_LIMITS); - for (SourceCode squidFunction : squidFunctionsInFile) { - complexityDistribution.add(squidFunction.getDouble(ObjectiveCMetric.COMPLEXITY)); - } - context.saveMeasure(sonarFile, complexityDistribution.build().setPersistenceMode(PersistenceMode.MEMORY)); - } - - private void saveFilesComplexityDistribution(File sonarFile, SourceFile squidFile) { - RangeDistributionBuilder complexityDistribution = new RangeDistributionBuilder(CoreMetrics.FILE_COMPLEXITY_DISTRIBUTION, FILES_DISTRIB_BOTTOM_LIMITS); - complexityDistribution.add(squidFile.getDouble(ObjectiveCMetric.COMPLEXITY)); - context.saveMeasure(sonarFile, complexityDistribution.build().setPersistenceMode(PersistenceMode.MEMORY)); - } - - private void saveViolations(File sonarFile, SourceFile squidFile) { - Collection messages = squidFile.getCheckMessages(); - if (messages != null) { - for (CheckMessage message : messages) { - Violation violation = Violation.create(annotationCheckFactory.getActiveRule(message.getChecker()), sonarFile) - .setLineId(message.getLine()) - .setMessage(message.getText(Locale.ENGLISH)); - context.saveViolation(violation); - } - } - } - - @Override - public String toString() { - return getClass().getSimpleName(); - } - -} diff --git a/src/main/java/org/sonar/plugins/objectivec/colorizer/ObjectiveCColorizerFormat.java b/src/main/java/org/sonar/plugins/objectivec/colorizer/ObjectiveCColorizerFormat.java deleted file mode 100644 index 3f5ea9f8..00000000 --- a/src/main/java/org/sonar/plugins/objectivec/colorizer/ObjectiveCColorizerFormat.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec.colorizer; - -import java.util.List; - -import org.sonar.api.web.CodeColorizerFormat; -import org.sonar.colorizer.CDocTokenizer; -import org.sonar.colorizer.CppDocTokenizer; -import org.sonar.colorizer.JavadocTokenizer; -import org.sonar.colorizer.KeywordsTokenizer; -import org.sonar.colorizer.StringTokenizer; -import org.sonar.colorizer.Tokenizer; -import org.sonar.objectivec.api.ObjectiveCKeyword; -import org.sonar.plugins.objectivec.core.ObjectiveC; - -import com.google.common.collect.ImmutableList; - -public class ObjectiveCColorizerFormat extends CodeColorizerFormat { - - public ObjectiveCColorizerFormat() { - super(ObjectiveC.KEY); - } - - @Override - public List getTokenizers() { - return ImmutableList.of( - new StringTokenizer("", ""), - new CDocTokenizer("", ""), - new JavadocTokenizer("", ""), - new CppDocTokenizer("", ""), - new KeywordsTokenizer("", "", ObjectiveCKeyword.keywordValues())); - } - -} diff --git a/src/main/java/org/sonar/plugins/objectivec/core/ObjectiveCSourceImporter.java b/src/main/java/org/sonar/plugins/objectivec/core/ObjectiveCSourceImporter.java deleted file mode 100644 index f8776a20..00000000 --- a/src/main/java/org/sonar/plugins/objectivec/core/ObjectiveCSourceImporter.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec.core; - -import org.sonar.api.batch.AbstractSourceImporter; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.resources.InputFileUtils; -import org.sonar.api.resources.ProjectFileSystem; - -public class ObjectiveCSourceImporter extends AbstractSourceImporter { - - public ObjectiveCSourceImporter(ObjectiveC objectivec) { - super(objectivec); - } - - protected void analyse(ProjectFileSystem fileSystem, SensorContext context) { - parseDirs(context, InputFileUtils.toFiles(fileSystem.mainFiles(ObjectiveC.KEY)), fileSystem.getSourceDirs(), false, fileSystem.getSourceCharset()); - } - - @Override - public String toString() { - return getClass().getSimpleName(); - } -} diff --git a/src/main/java/org/sonar/plugins/objectivec/coverage/CoberturaParser.java b/src/main/java/org/sonar/plugins/objectivec/coverage/CoberturaParser.java deleted file mode 100644 index cd333d32..00000000 --- a/src/main/java/org/sonar/plugins/objectivec/coverage/CoberturaParser.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec.coverage; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; - -import javax.xml.stream.XMLStreamException; - -import org.slf4j.LoggerFactory; -import org.sonar.api.measures.CoverageMeasuresBuilder; -import org.sonar.api.utils.StaxParser; - -final class CoberturaParser { - public Map parseReport(final File xmlFile) { - Map result = null; - try { - final InputStream reportStream = new FileInputStream(xmlFile); - result = parseReport(reportStream); - reportStream.close(); - } catch (final IOException e) { - LoggerFactory.getLogger(getClass()).error( - "Error processing file named {}", xmlFile, e); - result = new HashMap(); - } - return result; - } - - public Map parseReport( - final InputStream xmlFile) { - - final Map measuresForReport = new HashMap(); - try { - final StaxParser parser = new StaxParser( - new CoberturaXMLStreamHandler(measuresForReport)); - parser.parse(xmlFile); - } catch (final XMLStreamException e) { - LoggerFactory.getLogger(getClass()).error( - "Error while parsing XML stream.", e); - } - return measuresForReport; - } - - @Override - public String toString() { - return getClass().getSimpleName(); - } -} diff --git a/src/main/java/org/sonar/plugins/objectivec/coverage/CoberturaSensor.java b/src/main/java/org/sonar/plugins/objectivec/coverage/CoberturaSensor.java deleted file mode 100644 index 0a900b2b..00000000 --- a/src/main/java/org/sonar/plugins/objectivec/coverage/CoberturaSensor.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec.coverage; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; - -import org.slf4j.LoggerFactory; -import org.sonar.api.batch.Sensor; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.batch.fs.FileSystem; -import org.sonar.api.config.Settings; -import org.sonar.api.measures.CoverageMeasuresBuilder; -import org.sonar.api.resources.Project; -import org.sonar.plugins.objectivec.ObjectiveCPlugin; -import org.sonar.plugins.objectivec.core.ObjectiveC; - - -public final class CoberturaSensor implements Sensor { - - public static final String REPORT_PATTERN_KEY = ObjectiveCPlugin.PROPERTY_PREFIX - + ".coverage.reportPattern"; - public static final String DEFAULT_REPORT_PATTERN = "sonar-reports/coverage*.xml"; - - private final ReportFilesFinder reportFilesFinder; - private final CoberturaParser parser = new CoberturaParser(); - - private final Settings conf; - private final FileSystem fileSystem; - - public CoberturaSensor(final FileSystem fileSystem, final Settings config) { - - this.conf = config; - this.fileSystem = fileSystem; - - reportFilesFinder = new ReportFilesFinder(config, REPORT_PATTERN_KEY, DEFAULT_REPORT_PATTERN); - } - - public boolean shouldExecuteOnProject(final Project project) { - - return project.isRoot() && fileSystem.languages().contains(ObjectiveC.KEY); - } - - public void analyse(final Project project, final SensorContext context) { - final CoverageMeasuresPersistor measuresPersistor = new CoverageMeasuresPersistor( - project, context); - final String projectBaseDir = project.getFileSystem().getBasedir() - .getPath(); - - measuresPersistor.saveMeasures(parseReportsIn(projectBaseDir)); - } - - private Map parseReportsIn( - final String baseDir) { - final Map measuresTotal = new HashMap(); - - for (final File report : reportFilesFinder.reportsIn(baseDir)) { - LoggerFactory.getLogger(getClass()).info( - "Processing coverage report {}", report); - measuresTotal.putAll(parser.parseReport(report)); - } - - return measuresTotal; - } - -} diff --git a/src/main/java/org/sonar/plugins/objectivec/coverage/CoberturaSensor.old b/src/main/java/org/sonar/plugins/objectivec/coverage/CoberturaSensor.old deleted file mode 100644 index 1cdb1303..00000000 --- a/src/main/java/org/sonar/plugins/objectivec/coverage/CoberturaSensor.old +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ - -package org.sonar.plugins.objectivec.coverage; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.sonar.api.batch.AbstractCoverageExtension; -import org.sonar.api.batch.CoverageExtension; -import org.sonar.api.batch.Sensor; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.resources.Project; -import org.sonar.api.resources.Resource; -import org.sonar.plugins.cobertura.api.AbstractCoberturaParser; -import org.sonar.plugins.cobertura.api.CoberturaUtils; -import org.sonar.plugins.objectivec.core.ObjectiveC; - -import java.io.File; - -public class CoberturaSensor implements Sensor { - - private static final Logger LOG = LoggerFactory.getLogger(CoberturaSensor.class); - - public CoberturaSensor() { - } - - public boolean shouldExecuteOnProject(Project project) { - return ObjectiveC.KEY.equals(project.getLanguageKey()); - } - - public void analyse(Project project, SensorContext context) { - File report = CoberturaUtils.getReport(project); - if (report != null) { - parseReport(report, context); - } - } - - protected void parseReport(File xmlFile, final SensorContext context) { - LOG.info("parsing {}", xmlFile); - COBERTURA_PARSER.parseReport(xmlFile, context); - } - - private static final AbstractCoberturaParser COBERTURA_PARSER = new AbstractCoberturaParser() { - @Override - protected Resource getResource(String fileName) { - LOG.info("Analyzing {}", fileName); - fileName = fileName.replace(".", "/") + ".m"; - return new org.sonar.api.resources.File(fileName); - } - }; - - @Override - public String toString() { - return "Objective-C CoberturaSensor"; - } - -} \ No newline at end of file diff --git a/src/main/java/org/sonar/plugins/objectivec/coverage/CoberturaXMLStreamHandler.java b/src/main/java/org/sonar/plugins/objectivec/coverage/CoberturaXMLStreamHandler.java deleted file mode 100644 index 44501a4c..00000000 --- a/src/main/java/org/sonar/plugins/objectivec/coverage/CoberturaXMLStreamHandler.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec.coverage; - -import java.util.Map; - -import javax.xml.stream.XMLStreamException; - -import org.apache.commons.lang.StringUtils; -import org.codehaus.staxmate.in.SMHierarchicCursor; -import org.codehaus.staxmate.in.SMInputCursor; -import org.sonar.api.measures.CoverageMeasuresBuilder; -import org.sonar.api.utils.StaxParser; - -class CoberturaXMLStreamHandler implements StaxParser.XmlStreamHandler { - private final Map measuresForReport; - - public CoberturaXMLStreamHandler( - final Map data) { - measuresForReport = data; - } - - public void stream(final SMHierarchicCursor rootCursor) - throws XMLStreamException { - rootCursor.advance(); - collectPackageMeasures(rootCursor.descendantElementCursor("package")); - } - - private void collectPackageMeasures(final SMInputCursor pack) - throws XMLStreamException { - while (pack.getNext() != null) { - collectFileMeasures(pack.descendantElementCursor("class")); - } - } - - private void collectFileMeasures(final SMInputCursor clazz) - throws XMLStreamException { - while (clazz.getNext() != null) { - collectFileData(clazz); - } - } - - private void collectFileData(final SMInputCursor clazz) - throws XMLStreamException { - final CoverageMeasuresBuilder builder = builderFor(clazz); - final SMInputCursor line = clazz.childElementCursor("lines").advance() - .childElementCursor("line"); - - while (null != line.getNext()) { - recordCoverageFor(line, builder); - } - } - - private void recordCoverageFor(final SMInputCursor line, - final CoverageMeasuresBuilder builder) throws XMLStreamException { - final int lineId = Integer.parseInt(line.getAttrValue("number")); - final int noHits = (int) Math.min( - Long.parseLong(line.getAttrValue("hits")), Integer.MAX_VALUE); - final String isBranch = line.getAttrValue("branch"); - final String conditionText = line.getAttrValue("condition-coverage"); - - builder.setHits(lineId, noHits); - - if (StringUtils.equals(isBranch, "true") - && StringUtils.isNotBlank(conditionText)) { - final String[] conditions = StringUtils.split( - StringUtils.substringBetween(conditionText, "(", ")"), "/"); - builder.setConditions(lineId, Integer.parseInt(conditions[1]), - Integer.parseInt(conditions[0])); - } - } - - private CoverageMeasuresBuilder builderFor(final SMInputCursor clazz) - throws XMLStreamException { - final String fileName = clazz.getAttrValue("filename"); - CoverageMeasuresBuilder builder = measuresForReport.get(fileName); - if (builder == null) { - builder = CoverageMeasuresBuilder.create(); - measuresForReport.put(fileName, builder); - } - return builder; - } -} \ No newline at end of file diff --git a/src/main/java/org/sonar/plugins/objectivec/coverage/CoverageMeasuresPersistor.java b/src/main/java/org/sonar/plugins/objectivec/coverage/CoverageMeasuresPersistor.java deleted file mode 100644 index d46ee0fa..00000000 --- a/src/main/java/org/sonar/plugins/objectivec/coverage/CoverageMeasuresPersistor.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec.coverage; - -import java.io.File; -import java.util.List; -import java.util.Map; - -import com.google.common.base.Joiner; -import com.google.common.collect.Lists; -import org.slf4j.LoggerFactory; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.measures.CoverageMeasuresBuilder; -import org.sonar.api.measures.Measure; -import org.sonar.api.resources.Project; -import org.sonar.api.scan.filesystem.PathResolver; -import org.sonar.api.utils.PathUtils; - -final class CoverageMeasuresPersistor { - private final Project project; - private final SensorContext context; - - public CoverageMeasuresPersistor(final Project p, final SensorContext c) { - project = p; - context = c; - } - - public void saveMeasures(final Map coverageMeasures) { - - for (final Map.Entry entry : coverageMeasures.entrySet()) { - saveMeasuresForFile(entry.getValue(), entry.getKey()); - } - } - - private void saveMeasuresForFile(final CoverageMeasuresBuilder measureBuilder, final String filePath) { - - LoggerFactory.getLogger(getClass()).debug("Saving measures for {}", filePath); - final org.sonar.api.resources.File objcfile = org.sonar.api.resources.File.fromIOFile(new File(project.getFileSystem().getBasedir(), filePath), project); - - if (fileExists(context, objcfile)) { - LoggerFactory.getLogger(getClass()).debug( - "File {} was found in the project.", filePath); - saveMeasures(measureBuilder, objcfile); - } - } - - private void saveMeasures(final CoverageMeasuresBuilder measureBuilder, - final org.sonar.api.resources.File objcfile) { - for (final Measure measure : measureBuilder.createMeasures()) { - LoggerFactory.getLogger(getClass()).debug("Measure {}", - measure.getMetric().getName()); - context.saveMeasure(objcfile, measure); - } - } - - private boolean fileExists(final SensorContext context, - final org.sonar.api.resources.File file) { - return context.getResource(file) != null; - } -} diff --git a/src/main/java/org/sonar/plugins/objectivec/coverage/ReportFilesFinder.java b/src/main/java/org/sonar/plugins/objectivec/coverage/ReportFilesFinder.java deleted file mode 100644 index 831327a9..00000000 --- a/src/main/java/org/sonar/plugins/objectivec/coverage/ReportFilesFinder.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec.coverage; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import org.apache.tools.ant.DirectoryScanner; -import org.sonar.api.config.Settings; - -final class ReportFilesFinder { - private final Settings conf; - private final String settingsKey; - private final String settingsDefault; - - public ReportFilesFinder(final Settings settings, final String key, - final String defaultValue) { - conf = settings; - settingsKey = key; - settingsDefault = defaultValue; - } - - public List reportsIn(final String baseDirPath) { - final String[] relPaths = filesMathingPattern(baseDirPath, - reportPattern()); - - final List reports = new ArrayList(); - for (final String relPath : relPaths) { - reports.add(new File(baseDirPath, relPath)); - } - - return reports; - } - - private String[] filesMathingPattern(final String baseDirPath, - final String reportPath) { - final DirectoryScanner scanner = new DirectoryScanner(); - scanner.setIncludes(new String[] { reportPath }); - scanner.setBasedir(new File(baseDirPath)); - scanner.scan(); - return scanner.getIncludedFiles(); - } - - private String reportPattern() { - String reportPath = conf.getString(settingsKey); - if (reportPath == null) { - reportPath = settingsDefault; - } - return reportPath; - } - -} \ No newline at end of file diff --git a/src/main/java/org/sonar/plugins/objectivec/tests/SurefireParser.java b/src/main/java/org/sonar/plugins/objectivec/tests/SurefireParser.java deleted file mode 100644 index b566a92a..00000000 --- a/src/main/java/org/sonar/plugins/objectivec/tests/SurefireParser.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ - -package org.sonar.plugins.objectivec.tests; - -import com.sun.swing.internal.plaf.metal.resources.metal_sv; -import org.apache.commons.lang.StringEscapeUtils; -import org.apache.commons.lang.StringUtils; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.measures.CoreMetrics; -import org.sonar.api.measures.Measure; -import org.sonar.api.measures.Metric; -import org.sonar.api.resources.Project; -import org.sonar.api.resources.Qualifiers; -import org.sonar.api.resources.Resource; -import org.sonar.api.utils.ParsingUtils; -import org.sonar.api.utils.StaxParser; -import org.sonar.api.utils.XmlParserException; -import org.sonar.plugins.surefire.TestCaseDetails; -import org.sonar.plugins.surefire.TestSuiteParser; -import org.sonar.plugins.surefire.TestSuiteReport; - -import javax.xml.transform.TransformerException; -import java.io.File; -import java.io.FilenameFilter; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * Created by gillesgrousset on 06/01/15. - */ -public class SurefireParser { - - public void collect(Project project, SensorContext context, File reportsDir) { - File[] xmlFiles = getReports(reportsDir); - - if (xmlFiles.length == 0) { - insertZeroWhenNoReports(project, context); - } else { - parseFiles(context, xmlFiles); - } - } - - private File[] getReports(File dir) { - if (dir == null || !dir.isDirectory() || !dir.exists()) { - return new File[0]; - } - - File[] list = dir.listFiles(new FilenameFilter() { - public boolean accept(File dir, String name) { - return name.startsWith("TEST") && name.endsWith(".xml"); - } - }); - - return dir.listFiles(new FilenameFilter() { - public boolean accept(File dir, String name) { - return name.startsWith("TEST") && name.endsWith(".xml"); - } - }); - } - - private void insertZeroWhenNoReports(Project pom, SensorContext context) { - if ( !StringUtils.equalsIgnoreCase("pom", pom.getPackaging())) { - context.saveMeasure(CoreMetrics.TESTS, 0.0); - } - } - - private void parseFiles(SensorContext context, File[] reports) { - Set analyzedReports = new HashSet(); - try { - for (File report : reports) { - TestSuiteParser parserHandler = new TestSuiteParser(); - StaxParser parser = new StaxParser(parserHandler, false); - parser.parse(report); - - for (TestSuiteReport fileReport : parserHandler.getParsedReports()) { - if ( !fileReport.isValid() || analyzedReports.contains(fileReport)) { - continue; - } - if (fileReport.getTests() > 0) { - double testsCount = fileReport.getTests() - fileReport.getSkipped(); - saveClassMeasure(context, fileReport, CoreMetrics.SKIPPED_TESTS, fileReport.getSkipped()); - saveClassMeasure(context, fileReport, CoreMetrics.TESTS, testsCount); - saveClassMeasure(context, fileReport, CoreMetrics.TEST_ERRORS, fileReport.getErrors()); - saveClassMeasure(context, fileReport, CoreMetrics.TEST_FAILURES, fileReport.getFailures()); - saveClassMeasure(context, fileReport, CoreMetrics.TEST_EXECUTION_TIME, fileReport.getTimeMS()); - double passedTests = testsCount - fileReport.getErrors() - fileReport.getFailures(); - if (testsCount > 0) { - double percentage = passedTests * 100d / testsCount; - saveClassMeasure(context, fileReport, CoreMetrics.TEST_SUCCESS_DENSITY, ParsingUtils.scaleValue(percentage)); - } - saveTestsDetails(context, fileReport); - analyzedReports.add(fileReport); - } - } - } - - } catch (Exception e) { - throw new XmlParserException("Can not parse surefire reports", e); - } - } - - private void saveTestsDetails(SensorContext context, TestSuiteReport fileReport) throws TransformerException { - StringBuilder testCaseDetails = new StringBuilder(256); - testCaseDetails.append(""); - List details = fileReport.getDetails(); - for (TestCaseDetails detail : details) { - testCaseDetails.append("") - .append(isError ? "") - .append("") - .append(isError ? "" : "").append(""); - } else { - testCaseDetails.append("/>"); - } - } - testCaseDetails.append(""); - context.saveMeasure(getUnitTestResource(fileReport.getClassKey()), new Measure(CoreMetrics.TEST_DATA, testCaseDetails.toString())); - } - - private void saveClassMeasure(SensorContext context, TestSuiteReport fileReport, Metric metric, double value) { - if ( !Double.isNaN(value)) { - - String basename = fileReport.getClassKey().replace('.', '/'); - - // .m file - context.saveMeasure(getUnitTestResource(basename + ".m"), metric, value); - - // Try .m file with + in name - try { - context.saveMeasure(getUnitTestResource(basename.replace('_', '+') + ".m"), metric, value); - } catch (Exception e) { - // Nothing : File was probably already registered successfully - } - } - } - - public Resource getUnitTestResource(String filename) { - - org.sonar.api.resources.File sonarFile = new org.sonar.api.resources.File(filename); - sonarFile.setQualifier(Qualifiers.UNIT_TEST_FILE); - return sonarFile; - } -} diff --git a/src/main/java/org/sonar/plugins/objectivec/tests/SurefireSensor.java b/src/main/java/org/sonar/plugins/objectivec/tests/SurefireSensor.java deleted file mode 100644 index 207a430f..00000000 --- a/src/main/java/org/sonar/plugins/objectivec/tests/SurefireSensor.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ - -package org.sonar.plugins.objectivec.tests; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.sonar.api.batch.CoverageExtension; -import org.sonar.api.batch.DependsUpon; -import org.sonar.api.batch.Sensor; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.config.Settings; -import org.sonar.api.resources.Project; -import org.sonar.plugins.objectivec.core.ObjectiveC; - -import java.io.File; - -public class SurefireSensor implements Sensor { - - private static final Logger LOG = LoggerFactory.getLogger(SurefireSensor.class); - public static final String REPORT_PATH_KEY = "sonar.junit.reportsPath"; - public static final String DEFAULT_REPORT_PATH = "sonar-reports/"; - private final Settings conf; - - public SurefireSensor() { - this(null); - } - - public SurefireSensor(final Settings config) { - conf = config; - } - - @DependsUpon - public Class dependsUponCoverageSensors() { - return CoverageExtension.class; - } - - public boolean shouldExecuteOnProject(Project project) { - return ObjectiveC.KEY.equals(project.getLanguageKey()); - } - - public void analyse(Project project, SensorContext context) { - - /* - GitHub Issue #50 - Formerly we used SurefireUtils.getReportsDirectory(project). It seems that is this one: - http://grepcode.com/file/repo1.maven.org/maven2/org.codehaus.sonar.plugins/sonar-surefire-plugin/3.3.2/org/sonar/plugins/surefire/api/SurefireUtils.java?av=f#34 - However it turns out that the Java plugin contains its own version of SurefireUtils - that is very different (and does not contain a matching method). - That seems to be this one: http://svn.codehaus.org/sonar-plugins/tags/sonar-groovy-plugin-0.5/src/main/java/org/sonar/plugins/groovy/surefire/SurefireSensor.java - - The result is as follows: - - 1. At runtime getReportsDirectory(project) fails if you have the Java plugin installed - 2. At build time the new getReportsDirectory(project,settings) because I guess something in the build chain doesn't know about the Java plugin version - - So the implementation here reaches into the project properties and pulls the path out by itself. - */ - - collect(project, context, new File(reportPath())); - } - - protected void collect(Project project, SensorContext context, File reportsDir) { - LOG.info("parsing {}", reportsDir); - SUREFIRE_PARSER.collect(project, context, reportsDir); - } - - private static final SurefireParser SUREFIRE_PARSER = new SurefireParser(); - - @Override - public String toString() { - return "Objective-C SurefireSensor"; - } - - private String reportPath() { - String reportPath = conf.getString(REPORT_PATH_KEY); - if (reportPath == null) { - reportPath = DEFAULT_REPORT_PATH; - } - return reportPath; - } - -} \ No newline at end of file diff --git a/src/main/java/org/sonar/plugins/objectivec/violations/OCLintParser.java b/src/main/java/org/sonar/plugins/objectivec/violations/OCLintParser.java deleted file mode 100644 index a16b9278..00000000 --- a/src/main/java/org/sonar/plugins/objectivec/violations/OCLintParser.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec.violations; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; - -import javax.xml.stream.XMLStreamException; - -import org.slf4j.LoggerFactory; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.resources.Project; -import org.sonar.api.rules.Violation; -import org.sonar.api.utils.StaxParser; - -final class OCLintParser { - private final Project project; - private final SensorContext context; - - public OCLintParser(final Project p, final SensorContext c) { - project = p; - context = c; - } - - public Collection parseReport(final File file) { - Collection result; - try { - final InputStream reportStream = new FileInputStream(file); - result = parseReport(reportStream); - reportStream.close(); - } catch (final IOException e) { - LoggerFactory.getLogger(getClass()).error( - "Error processing file named {}", file, e); - result = new ArrayList(); - } - return result; - } - - public Collection parseReport(final InputStream inputStream) { - final Collection violations = new ArrayList(); - try { - final StaxParser parser = new StaxParser( - new OCLintXMLStreamHandler(violations, project, context)); - parser.parse(inputStream); - LoggerFactory.getLogger(getClass()).error( - "Reporting {} violations.", violations.size()); - } catch (final XMLStreamException e) { - LoggerFactory.getLogger(getClass()).error( - "Error while parsing XML stream.", e); - } - return violations; - } - -} diff --git a/src/main/java/org/sonar/plugins/objectivec/violations/OCLintRuleParser.java b/src/main/java/org/sonar/plugins/objectivec/violations/OCLintRuleParser.java deleted file mode 100644 index 427090c0..00000000 --- a/src/main/java/org/sonar/plugins/objectivec/violations/OCLintRuleParser.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec.violations; - -import java.io.BufferedReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.io.IOUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.sonar.api.ServerComponent; -import org.sonar.api.rules.Rule; -import org.sonar.api.rules.RulePriority; - -/** - * Largely copied from AndroidLint's equivalent class whose authors are Stephane - * Nicolas and Jerome Van Der Linden according to the class Javadoc. - * - */ -final class OCLintRuleParser implements ServerComponent { - - private static final int OCLINT_MINIMUM_PRIORITY = 4; - private static final Logger LOGGER = LoggerFactory - .getLogger(OCLintRuleParser.class); - - public List parse(final BufferedReader reader) throws IOException { - final List rules = new ArrayList(); - - final List listLines = IOUtils.readLines(reader); - - String previousLine = null; - Rule rule = null; - boolean inDescription = false; - for (String line : listLines) { - if (isLineIgnored(line)) { - inDescription = false; - } else if (line.matches("[\\-]{4,}.*")) { - LOGGER.debug("Rule found : {}", previousLine); - - // remove the rule name from the description of the previous - // rule - if (rule != null) { - final int index = rule.getDescription().lastIndexOf( - previousLine); - if (index > 0) { - rule.setDescription(rule.getDescription().substring(0, - index)); - } - } - - rule = Rule.create(); - rules.add(rule); - rule.setName(previousLine); - rule.setKey(previousLine); - } else if (line.matches("Summary:.*")) { - inDescription = true; - rule.setDescription(line.substring(line.indexOf(':') + 1)); - } else if (line.matches("Category:.*")) { - inDescription = true; - } else if (line.matches("Severity:.*")) { - inDescription = false; - final String severity = line.substring("Severity: ".length()); - // Rules are priority 1, 2 or 3 in OCLint files. - rule.setSeverity(RulePriority.values()[Integer.valueOf(severity)]); - } else { - if (inDescription) { - line = ruleDescriptionLink(line); - rule.setDescription(rule.getDescription() + "
" + line); - } - } - previousLine = line; - } - return rules; - } - - private boolean isLineIgnored(String line) { - return line.matches("\\=.*") || line.matches("Priority:.*"); - } - - private String ruleDescriptionLink(final String line) { - String result = line; - final int indexOfLink = line.indexOf("http://"); - if (0 <= indexOfLink) { - final String link = line.substring(indexOfLink); - final StringBuilder htmlText = new StringBuilder(""); - htmlText.append(link); - htmlText.append(""); - result = htmlText.toString(); - } - return result; - } -} diff --git a/src/main/java/org/sonar/plugins/objectivec/violations/OCLintRuleRepository.java b/src/main/java/org/sonar/plugins/objectivec/violations/OCLintRuleRepository.java deleted file mode 100644 index 47920cea..00000000 --- a/src/main/java/org/sonar/plugins/objectivec/violations/OCLintRuleRepository.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec.violations; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.List; - -import org.apache.commons.lang.CharEncoding; -import org.sonar.api.rules.Rule; -import org.sonar.api.rules.RuleRepository; -import org.sonar.api.utils.SonarException; -import org.sonar.plugins.objectivec.core.ObjectiveC; - -import com.google.common.io.Closeables; - -public final class OCLintRuleRepository extends RuleRepository { - public static final String REPOSITORY_KEY = "OCLint"; - public static final String REPOSITORY_NAME = REPOSITORY_KEY; - - private static final String RULES_FILE = "/org/sonar/plugins/oclint/rules.txt"; - - private final OCLintRuleParser ocLintRuleParser = new OCLintRuleParser(); - - public OCLintRuleRepository() { - super(OCLintRuleRepository.REPOSITORY_KEY, ObjectiveC.KEY); - setName(OCLintRuleRepository.REPOSITORY_NAME); - } - - @Override - public List createRules() { - BufferedReader reader = null; - try { - reader = new BufferedReader(new InputStreamReader(getClass() - .getResourceAsStream(RULES_FILE), CharEncoding.UTF_8)); - return ocLintRuleParser.parse(reader); - } catch (final IOException e) { - throw new SonarException("Fail to load the default OCLint rules.", - e); - } finally { - Closeables.closeQuietly(reader); - } - } -} diff --git a/src/main/java/org/sonar/plugins/objectivec/violations/OCLintSensor.java b/src/main/java/org/sonar/plugins/objectivec/violations/OCLintSensor.java deleted file mode 100644 index 4847905f..00000000 --- a/src/main/java/org/sonar/plugins/objectivec/violations/OCLintSensor.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec.violations; - -import java.io.File; -import java.util.Collection; - -import org.slf4j.LoggerFactory; -import org.sonar.api.batch.Sensor; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.batch.fs.FileSystem; -import org.sonar.api.config.Settings; -import org.sonar.api.resources.Project; -import org.sonar.api.rules.Violation; -import org.sonar.plugins.objectivec.ObjectiveCPlugin; -import org.sonar.plugins.objectivec.core.ObjectiveC; - -public final class OCLintSensor implements Sensor { - public static final String REPORT_PATH_KEY = ObjectiveCPlugin.PROPERTY_PREFIX - + ".oclint.report"; - public static final String DEFAULT_REPORT_PATH = "sonar-reports/oclint.xml"; - - private final Settings conf; - private final FileSystem fileSystem; - - public OCLintSensor(final FileSystem moduleFileSystem, final Settings config) { - this.conf = config; - this.fileSystem = moduleFileSystem; - } - - public boolean shouldExecuteOnProject(final Project project) { - - return project.isRoot() && fileSystem.languages().contains(ObjectiveC.KEY); - - } - - public void analyse(final Project project, final SensorContext context) { - final String projectBaseDir = project.getFileSystem().getBasedir() - .getPath(); - final OCLintParser parser = new OCLintParser(project, context); - saveViolations(parseReportIn(projectBaseDir, parser), context); - - } - - private void saveViolations(final Collection violations, - final SensorContext context) { - for (final Violation violation : violations) { - context.saveViolation(violation); - } - } - - private Collection parseReportIn(final String baseDir, - final OCLintParser parser) { - final StringBuilder reportFileName = new StringBuilder(baseDir); - reportFileName.append("/").append(reportPath()); - - LoggerFactory.getLogger(getClass()).info("Processing OCLint report {}", - reportFileName); - return parser.parseReport(new File(reportFileName.toString())); - } - - private String reportPath() { - String reportPath = conf.getString(REPORT_PATH_KEY); - if (reportPath == null) { - reportPath = DEFAULT_REPORT_PATH; - } - return reportPath; - } -} diff --git a/src/main/java/org/sonar/plugins/objectivec/violations/OCLintXMLStreamHandler.java b/src/main/java/org/sonar/plugins/objectivec/violations/OCLintXMLStreamHandler.java deleted file mode 100644 index 0847046b..00000000 --- a/src/main/java/org/sonar/plugins/objectivec/violations/OCLintXMLStreamHandler.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec.violations; - -import java.io.File; -import java.util.Collection; - -import javax.xml.stream.XMLStreamException; - -import org.codehaus.staxmate.in.SMHierarchicCursor; -import org.codehaus.staxmate.in.SMInputCursor; -import org.slf4j.LoggerFactory; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.resources.Project; -import org.sonar.api.rules.Rule; -import org.sonar.api.rules.RulePriority; -import org.sonar.api.rules.Violation; -import org.sonar.api.utils.StaxParser.XmlStreamHandler; - -final class OCLintXMLStreamHandler implements XmlStreamHandler { - private static final int PMD_MINIMUM_PRIORITY = 5; - private final Collection foundViolations; - private final Project project; - private final SensorContext context; - - public OCLintXMLStreamHandler(final Collection violations, - final Project p, final SensorContext c) { - foundViolations = violations; - project = p; - context = c; - } - - public void stream(final SMHierarchicCursor rootCursor) - throws XMLStreamException { - final SMInputCursor file = rootCursor.advance().childElementCursor( - "file"); - - while (null != file.getNext()) { - collectViolationsFor(file); - } - } - - private void collectViolationsFor(final SMInputCursor file) - throws XMLStreamException { - final String filePath = file.getAttrValue("name"); - LoggerFactory.getLogger(getClass()).debug( - "Collection violations for {}", filePath); - final org.sonar.api.resources.File resource = findResource(filePath); - if (fileExists(resource)) { - LoggerFactory.getLogger(getClass()).debug( - "File {} was found in the project.", filePath); - collectFileViolations(resource, file); - } - } - - private org.sonar.api.resources.File findResource(final String filePath) { - return org.sonar.api.resources.File.fromIOFile(new File(filePath), - project); - } - - private void collectFileViolations( - final org.sonar.api.resources.File resource, - final SMInputCursor file) throws XMLStreamException { - final SMInputCursor line = file.childElementCursor("violation"); - - while (null != line.getNext()) { - recordViolation(resource, line); - } - } - - private void recordViolation(final org.sonar.api.resources.File resource, - final SMInputCursor line) throws XMLStreamException { - final Rule rule = Rule.create(); - final Violation violation = Violation.create(rule, resource); - - // PMD Priorities are 1, 2, 3, 4, 5 RulePriority[0] is INFO - rule.setSeverity(RulePriority.values()[PMD_MINIMUM_PRIORITY - - Integer.valueOf(line.getAttrValue("priority"))]); - rule.setKey(line.getAttrValue("rule")); - rule.setRepositoryKey(OCLintRuleRepository.REPOSITORY_KEY); - - violation.setLineId(Integer.valueOf(line.getAttrValue("beginline"))); - - violation.setMessage(line.getElemStringValue()); - - foundViolations.add(violation); - } - - private boolean fileExists(final org.sonar.api.resources.File file) { - return context.getResource(file) != null; - } - -} diff --git a/src/main/resources/org/sonar/plugins/oclint/profile-oclint.xml b/src/main/resources/org/sonar/plugins/oclint/profile-oclint.xml deleted file mode 100644 index 35fa35d4..00000000 --- a/src/main/resources/org/sonar/plugins/oclint/profile-oclint.xml +++ /dev/null @@ -1,259 +0,0 @@ - - - OCLint - objc - - - OCLint - use early exits and continue - - - OCLint - avoid branching statement as last in loop - - - OCLint - bitwise operator in conditional - - - OCLint - broken null check - - - OCLint - broken nil check - - - OCLint - broken oddness check - - - OCLint - collapsible if statements - - - OCLint - constant conditional operator - - - OCLint - constant if expression - - - OCLint - high cyclomatic complexity - - - OCLint - dead code - - - OCLint - default label not last in switch statement - - - OCLint - double negative - - - OCLint - empty catch statement - - - OCLint - empty do/while statement - - - OCLint - empty else block - - - OCLint - empty finally statement - - - OCLint - empty for statement - - - OCLint - empty if statement - - - OCLint - empty switch statement - - - OCLint - empty try statement - - - OCLint - empty while statement - - - OCLint - feature envy - - - OCLint - for loop should be while loop - - - OCLint - goto statement - - - OCLint - inverted logic - - - OCLint - jumbled incrementer - - - OCLint - long class - - - OCLint - long line - - - OCLint - long method - - - OCLint - long variable name - - - OCLint - misplaced null check - - - OCLint - misplaced nil check - - - OCLint - missing break in switch statement - - - OCLint - multiple unary operator - - - OCLint - must override hash with isEqual - - - OCLint - high ncss method - - - OCLint - deep nested block - - - OCLint - non case label in switch statement - - - OCLint - high npath complexity - - - OCLint - replace with boxed expression - - - OCLint - replace with container literal - - - OCLint - replace with number literal - - - OCLint - replace with object subscripting - - - OCLint - parameter reassignment - - - OCLint - redundant conditional operator - - - OCLint - redundant if statement - - - OCLint - redundant local variable - - - OCLint - redundant nil check - - - OCLint - return from finally block - - - OCLint - short variable name - - - OCLint - switch statements don't need default when fully covered - - - OCLint - switch statements should have default - - - OCLint - throw exception from finally block - - - OCLint - too few branches in switch statement - - - OCLint - too many fields - - - OCLint - too many methods - - - OCLint - too many parameters - - - OCLint - unnecessary else statement - - - OCLint - unused local variable - - - OCLint - unused method parameter - - - OCLint - useless parentheses - - - OCLint - ivar assignment outside accessors or init - - - \ No newline at end of file diff --git a/src/main/resources/org/sonar/plugins/oclint/rules.txt b/src/main/resources/org/sonar/plugins/oclint/rules.txt deleted file mode 100644 index beb11d6b..00000000 --- a/src/main/resources/org/sonar/plugins/oclint/rules.txt +++ /dev/null @@ -1,509 +0,0 @@ -Available issues: - -OCLint -====== - -use early exits and continue ----------- - -Summary: - -Severity: 2 -Category: OCLint - -avoid branching statement as last in loop ----------- - -Summary: Having branching statement as the last statement inside a loop is very confusing, and could largely be forgetting of something and turning into a bug. - -Severity: 2 -Category: OCLint - -bitwise operator in conditional ----------- - -Summary: Checks for bitwise operations in conditionals. Although being written on purpose in some rare cases, bitwise operations are considered to be too “smart”. Smart code is not easy to understand. - -Severity: 3 -Category: OCLint - -broken null check ----------- - -Summary: The broken nil check in Objective-C in some cases returns just the opposite result. - -Severity: 4 -Category: OCLint - -broken nil check ----------- - -Summary: - -Severity: 4 -Category: OCLint - -broken oddness check ----------- - -Summary: Checking oddness by x%2==1 won’t work for negative numbers. Use x&1==1, or x%2!=0 instead. - -Severity: 3 -Category: OCLint - -collapsible if statements ----------- - -Summary: This rule detects instances where the conditions of two consecutive if statements can combined into one in order to increase code cleanness and readability. - -Severity: 3 -Category: OCLint - -constant conditional operator ----------- - -Summary: conditionaloperator whose conditionals are always true or always false are confusing. - -Severity: 3 -Category: OCLint - -constant if expression ----------- - -Summary: if statements whose conditionals are always true or always false are confusing. - -Severity: 3 -Category: OCLint - -high cyclomatic complexity ----------- - -Summary: - -Severity: 2 -Category: OCLint - -dead code ----------- - -Summary: Code after return, break, continue, and throw statements are unreachable and will never be executed. - -Severity: 3 -Category: OCLint - -default label not last in switch statement ----------- - -Summary: It is very confusing when default label is not the last label in a switch statement. - -Severity: 2 -Category: OCLint - -double negative ----------- - -Summary: There is no point in using a double negative, it is always positive. - -Severity: 3 -Category: OCLint - -empty catch statement ----------- - -Summary: This rule detects instances where an exception is caught, but nothing is done about it. - -Severity: 3 -Category: OCLint - -empty do/while statement ----------- - -Summary: This rule detects instances where a do-while statement does nothing. - -Severity: 3 -Category: OCLint - -empty else block ----------- - -Summary: - -Severity: 2 -Category: OCLint - -empty finally statement ----------- - -Summary: This rule detects instances where a finally statement does nothing. - -Severity: 3 -Category: OCLint - -empty for statement ----------- - -Summary: This rule detects instances where a for statement does nothing. - -Severity: 3 -Category: OCLint - -empty if statement ----------- - -Summary: This rule detects instances where a condition is checked, but nothing is done about it. - -Severity: 3 -Category: OCLint - -empty switch statement ----------- - -Summary: This rule detects instances where a switch statement does nothing. - -Severity: 3 -Category: OCLint - -empty try statement ----------- - -Summary: This rule detects instances where a try statement is empty. - -Severity: 3 -Category: OCLint - -empty while statement ----------- - -Summary: - -Severity: 3 -Category: OCLint - -feature envy ----------- - -Summary: - -Severity: 3 -Category: OCLint - -for loop should be while loop ----------- - -Summary: Under certain circumstances, some for loops can be simplified to while loops to make code more concise. - -Severity: 3 -Category: OCLint - -goto statement ----------- - -Summary: - -Severity: 3 -Category: OCLint - -inverted logic ----------- - -Summary: An inverted logic is hard to understand. - -Severity: 2 -Category: OCLint - -jumbled incrementer ----------- - -Summary: - -Severity: 2 -Category: OCLint - -long class ----------- - -Summary: Long class generally indicates that this class tries to so many things. Each class should do one thing and one thing well. - -Severity: 3 -Category: OCLint - -long line ----------- - -Summary: When number of characters for one line of code is very long, it largely harm the readability. Break long line of code into multiple lines. - -Severity: 2 -Category: OCLint - -long method ----------- - -Summary: Long method generally indicates that this method tries to so many things. Each method should do one thing and one thing well. - -Severity: 3 -Category: OCLint - -long variable name ----------- - -Summary: Variables with long names harm readability. - -Severity: 2 -Category: OCLint - -misplaced null check ----------- - -Summary: The nil check is misplaced. In Objective-C, sending a message to a nil pointer simply does nothing. But code readers may be confused about the misplaced nil check. - -Severity: 3 -Category: OCLint - -misplaced nil check ----------- - -Summary: - -Severity: 4 -Category: OCLint - -missing break in switch statement ----------- - -Summary: - -Severity: 2 -Category: OCLint - -multiple unary operator ----------- - -Summary: Multiple unary operator can always be confusing and should be simplified. - -Severity: 3 -Category: OCLint - -must override hash with isEqual ----------- - -Summary: - -Severity: 1 -Category: OCLint - -high ncss method ----------- - -Summary: This rule counts number of lines for a method by counting Non Commenting Source Statements (NCSS). NCSS only takes actual statements into consideration, in other words, ignores empty statements, empty blocks, closing brackets or semicolons after closing brackets. Meanwhile, statement that is break into multiple lines contribute only one count. - -Severity: 3 -Category: OCLint - -deep nested block ----------- - -Summary: This rule indicates blocks nested more deeply than the upper limit. - -Severity: 3 -Category: OCLint - -non case label in switch statement ----------- - -Summary: It is very confusing when default label is not the last label in a switch statement. - -Severity: 2 -Category: OCLint - -high npath complexity ----------- - -Summary: - -Severity: 2 -Category: OCLint - -replace with boxed expression ----------- - -Summary: This rule locates the places that can be migrated to the new Objective-C literals with boxed expressions. - -Severity: 1 -Category: OCLint - -replace with container literal ----------- - -Summary: This rule locates the places that can be migrated to the new Objective-C literals with container literals. - -Severity: 1 -Category: OCLint - -replace with number literal ----------- - -Summary: This rule locates the places that can be migrated to the new Objective-C literals with number literals. - -Severity: 1 -Category: OCLint - -replace with object subscripting ----------- - -Summary: - -Severity: 1 -Category: OCLint - -parameter reassignment ----------- - -Summary: Reassigning values to parameters is very problematic in most cases. - -Severity: 2 -Category: OCLint - -redundant conditional operator ----------- - -Summary: This rule detects three types of redundant conditional operators: - -Severity: 1 -Category: OCLint - -redundant if statement ----------- - -Summary: This rule detects unnecessary if statements. - -Severity: 1 -Category: OCLint - -redundant local variable ----------- - -Summary: This rule detects cases where a variable declaration immediately followed by a return of that variable. - -Severity: 1 -Category: OCLint - -redundant nil check ----------- - -Summary: - -Severity: 3 -Category: OCLint - -return from finally block ----------- - -Summary: Returning from a finally block is not recommended. - -Severity: 3 -Category: OCLint - -short variable name ----------- - -Summary: - -Severity: 2 -Category: OCLint - -switch statements don't need default when fully covered ----------- - -Summary: - -Severity: 3 -Category: OCLint - -switch statements should have default ----------- - -Summary: Switch statements should a default statement. - -Severity: 2 -Category: OCLint - -throw exception from finally block ----------- - -Summary: - -Severity: 3 -Category: OCLint - -too few branches in switch statement ----------- - -Summary: - -Severity: 2 -Category: OCLint - -too many fields ----------- - -Summary: A class with too many fields indicates it does too many things and is lack of proper abstraction. It can be resigned to have fewer fields. - -Severity: 3 -Category: OCLint - -too many methods ----------- - -Summary: A class with too many methods indicates it does too many things and hard to read and understand. It usually contains complicated code, and should be refactored. - -Severity: 3 -Category: OCLint - -too many parameters ----------- - -Summary: - -Severity: 3 -Category: OCLint - -unnecessary else statement ----------- - -Summary: When an if statement block ends with a return statement, or all branches in the if statement block end with return statements, then the else statement is unnecessary. The code in the else statement can be run without being in the block. - -Severity: 1 -Category: OCLint - -unused local variable ----------- - -Summary: This rule detects local variables that are declared, but not used. - -Severity: 0 -Category: OCLint - -unused method parameter ----------- - -Summary: - -Severity: 0 -Category: OCLint - -useless parentheses ----------- - -Summary: - -Severity: 1 -Category: OCLint - -ivar assignment outside accessors or init ----------- - -Summary: - -Severity: 2 -Category: OCLint - diff --git a/src/main/shell/run-sonar.sh b/src/main/shell/run-sonar.sh deleted file mode 100755 index f82d33ef..00000000 --- a/src/main/shell/run-sonar.sh +++ /dev/null @@ -1,303 +0,0 @@ -#!/bin/bash -## INSTALLATION: script to copy in your Xcode project in the same directory as the .xcodeproj file -## USAGE: ./run-sonar.sh -## DEBUG: ./run-sonar.sh -v -## WARNING: edit your project parameters in sonar-project.properties rather than modifying this script -# - -trap "echo 'Script interrupted by Ctrl+C'; stopProgress; exit 1" SIGHUP SIGINT SIGTERM - -function startProgress() { - while true - do - echo -n "." - sleep 5 - done -} - -function stopProgress() { - if [ "$vflag" = "" -a "$nflag" = "" ]; then - kill $PROGRESS_PID &>/dev/null - fi -} - -function testIsInstalled() { - - hash $1 2>/dev/null - if [ $? -eq 1 ]; then - echo >&2 "ERROR - $1 is not installed or not in your PATH"; exit 1; - fi -} - -function readParameter() { - - variable=$1 - shift - parameter=$1 - shift - - eval $variable="\"$(sed '/^\#/d' sonar-project.properties | grep $parameter | tail -n 1 | cut -d '=' -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')\"" -} - -# Run a set of commands with logging and error handling -function runCommand() { - - # 1st arg: redirect stdout - # 2nd arg: command to run - # 3rd..nth arg: args - redirect=$1 - shift - - command=$1 - shift - - if [ "$nflag" = "on" ]; then - # don't execute command, just echo it - echo - if [ "$redirect" = "/dev/stdout" ]; then - if [ "$vflag" = "on" ]; then - echo "+" $command "$@" - else - echo "+" $command "$@" "> /dev/null" - fi - elif [ "$redirect" != "no" ]; then - echo "+" $command "$@" "> $redirect" - else - echo "+" $command "$@" - fi - - elif [ "$vflag" = "on" ]; then - echo - - if [ "$redirect" = "/dev/stdout" ]; then - set -x #echo on - $command "$@" - returnValue=$? - set +x #echo off - elif [ "$redirect" != "no" ]; then - set -x #echo on - $command "$@" > $redirect - returnValue=$? - set +x #echo off - else - set -x #echo on - $command "$@" - returnValue=$? - set +x #echo off - fi - - if [[ $returnValue != 0 && $returnValue != 5 ]] ; then - stopProgress - echo "ERROR - Command '$command $@' failed with error code: $returnValue" - exit $returnValue - fi - else - - if [ "$redirect" = "/dev/stdout" ]; then - $command "$@" > /dev/null - elif [ "$redirect" != "no" ]; then - $command "$@" > $redirect - else - $command "$@" - fi - - returnValue=$? - if [[ $returnValue != 0 && $returnValue != 5 ]] ; then - stopProgress - echo "ERROR - Command '$command $@' failed with error code: $returnValue" - exit $? - fi - - - echo - fi -} - -## COMMAND LINE OPTIONS -vflag="" -nflag="" -oclint="on" -while [ $# -gt 0 ] -do - case "$1" in - -v) vflag=on;; - -n) nflag=on;; - -nooclint) oclint="";; - --) shift; break;; - -*) - echo >&2 "Usage: $0 [-v]" - exit 1;; - *) break;; # terminate while loop - esac - shift -done - -# Usage OK -echo "Running run-sonar.sh..." - -## CHECK PREREQUISITES - -# xctool, gcovr and oclint installed -testIsInstalled xctool -testIsInstalled gcovr -testIsInstalled oclint - -# sonar-project.properties in current directory -if [ ! -f sonar-project.properties ]; then - echo >&2 "ERROR - No sonar-project.properties in current directory"; exit 1; -fi - -## READ PARAMETERS from sonar-project.properties - -# Your .xcworkspace/.xcodeproj filename -workspaceFile=''; readParameter workspaceFile 'sonar.objectivec.workspace' -projectFile=''; readParameter projectFile 'sonar.objectivec.project' -if [[ "$workspaceFile" != "" ]] ; then - xctoolCmdPrefix="xctool -workspace $workspaceFile -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO" -else - xctoolCmdPrefix="xctool -project $projectFile -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO" -fi - -# Source directories for .h/.m files -srcDirs=''; readParameter srcDirs 'sonar.sources' -# The name of your application scheme in Xcode -appScheme=''; readParameter appScheme 'sonar.objectivec.appScheme' - -# The name of your test scheme in Xcode -testScheme=''; readParameter testScheme 'sonar.objectivec.testScheme' -# The file patterns to exclude from coverage report -excludedPathsFromCoverage=''; readParameter excludedPathsFromCoverage 'sonar.objectivec.excludedPathsFromCoverage' - -# Check for mandatory parameters -if [ -z "$projectFile" -o "$projectFile" = " " ]; then - - if [ ! -z "$workspaceFile" -a "$workspaceFile" != " " ]; then - echo >&2 "ERROR - sonar.objectivec.project parameter is missing in sonar-project.properties. You must specify which projects (comma-separated list) are application code within the workspace $workspaceFile." - else - echo >&2 "ERROR - sonar.objectivec.project parameter is missing in sonar-project.properties (name of your .xcodeproj)" - fi - exit 1 -fi -if [ -z "$srcDirs" -o "$srcDirs" = " " ]; then - echo >&2 "ERROR - sonar.sources parameter is missing in sonar-project.properties. You must specify which directories contain your .h/.m source files (comma-separated list)." - exit 1 -fi -if [ -z "$appScheme" -o "$appScheme" = " " ]; then - echo >&2 "ERROR - sonar.objectivec.appScheme parameter is missing in sonar-project.properties. You must specify which scheme is used to build your application." - exit 1 -fi - -if [ "$vflag" = "on" ]; then - echo "Xcode workspace file is: $workspaceFile" - echo "Xcode project file is: $projectFile" - echo "Xcode application scheme is: $appScheme" - echo "Xcode test scheme is: $testScheme" - echo "Excluded paths from coverage are: $excludedPathsFromCoverage" -fi - -## SCRIPT - -# Start progress indicator in the background -if [ "$vflag" = "" -a "$nflag" = "" ]; then - startProgress & - # Save PID - PROGRESS_PID=$! -fi - -# Create sonar-reports/ for reports output -if [[ ! (-d "sonar-reports") && ("$nflag" != "on") ]]; then - if [ "$vflag" = "on" ]; then - echo 'Creating directory sonar-reports/' - fi - mkdir sonar-reports - if [[ $? != 0 ]] ; then - stopProgress - exit $? - fi -fi - -# Extracting project information needed later -echo -n 'Extracting Xcode project information' -runCommand /dev/stdout $xctoolCmdPrefix -scheme "$appScheme" clean -runCommand /dev/stdout $xctoolCmdPrefix -scheme "$appScheme" -reporter json-compilation-database:compile_commands.json build - -# Unit tests and coverage -if [ "$testScheme" = "" ]; then - echo 'Skipping tests as no test scheme has been provided!' - - # Put default xml files with no tests and no coverage... - echo "" > sonar-reports/TEST-report.xml - echo "" > sonar-reports/coverage.xml -else - - echo -n 'Running tests using xctool' - runCommand sonar-reports/TEST-report.xml $xctoolCmdPrefix -scheme "$testScheme" -reporter junit GCC_GENERATE_TEST_COVERAGE_FILES=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES test - - echo -n 'Computing coverage report' - - # We do it for every xcodeproject (in case of workspaces) - - # Extract the path to the .gcno/.gcda coverage files - echo $projectFile | sed -n 1'p' | tr ',' '\n' > tmpFileRunSonarSh - while read projectName; do - - coverageFilesPath=$(grep 'command' compile_commands.json | sed 's#^.*-o \\/#\/#;s#",##' | grep "${projectName%%.*}.build" | awk 'NR<2' | sed 's/\\\//\//g' | sed 's/\\\\//g' | xargs -0 dirname) - if [ "$vflag" = "on" ]; then - echo - echo "Path for .gcno/.gcda coverage files is: $coverageFilesPath" - fi - - # Build the --exclude flags - excludedCommandLineFlags="" - if [ ! -z "$excludedPathsFromCoverage" -a "$excludedPathsFromCoverage" != " " ]; then - echo $excludedPathsFromCoverage | sed -n 1'p' | tr ',' '\n' > tmpFileRunSonarSh2 - while read word; do - excludedCommandLineFlags+=" --exclude $word" - done < tmpFileRunSonarSh2 - rm -rf tmpFileRunSonarSh2 - fi - if [ "$vflag" = "on" ]; then - echo "Command line exclusion flags for gcovr is:$excludedCommandLineFlags" - fi - - # Run gcovr with the right options - runCommand "sonar-reports/coverage-${projectName%%.*}.xml" gcovr -r . "$coverageFilesPath" $excludedCommandLineFlags --xml - - done < tmpFileRunSonarSh - rm -rf tmpFileRunSonarSh - -fi - -if [ "$oclint" = "on" ]; then - - # OCLint - echo -n 'Running OCLint...' - - # Build the --include flags - currentDirectory=${PWD##*/} - includedCommandLineFlags="" - echo "$srcDirs" | sed -n 1'p' | tr ',' '\n' > tmpFileRunSonarSh - while read word; do - includedCommandLineFlags+=" --include .*/${currentDirectory}/${word}" - done < tmpFileRunSonarSh - rm -rf tmpFileRunSonarSh - if [ "$vflag" = "on" ]; then - echo - echo -n "Path included in oclint analysis is:$includedCommandLineFlags" - fi - - # Run OCLint with the right set of compiler options - maxPriority=10000 - runCommand no oclint-json-compilation-database $includedCommandLineFlags -- -max-priority-1 $maxPriority -max-priority-2 $maxPriority -max-priority-3 $maxPriority -report-type pmd -o sonar-reports/oclint.xml -else - echo 'Skipping OCLint (test purposes only!)' -fi - -# SonarQube -echo -n 'Running SonarQube using SonarQube Runner' -runCommand /dev/stdout sonar-runner - -# Kill progress indicator -stopProgress - -exit 0 diff --git a/src/test/java/org/sonar/plugins/objectivec/coverage/CoberturaMeasuresPersistorTest.java b/src/test/java/org/sonar/plugins/objectivec/coverage/CoberturaMeasuresPersistorTest.java deleted file mode 100644 index 8ac0339b..00000000 --- a/src/test/java/org/sonar/plugins/objectivec/coverage/CoberturaMeasuresPersistorTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec.coverage; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Test; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.measures.CoverageMeasuresBuilder; -import org.sonar.api.measures.Measure; -import org.sonar.api.resources.Project; -import org.sonar.api.resources.ProjectFileSystem; -import org.sonar.api.resources.Resource; - -public final class CoberturaMeasuresPersistorTest { - - @Test - public void shouldNotPersistMeasuresForUnknownFiles() { - final Project project = new Project("Test"); - - final SensorContext context = mock(SensorContext.class); - final ProjectFileSystem fileSystem = mock(ProjectFileSystem.class); - final Map measures = new HashMap(); - measures.put("DummyResource", CoverageMeasuresBuilder.create()); - - - when(fileSystem.getBasedir()).thenReturn(new File(".")); - - project.setFileSystem(fileSystem); - - final CoverageMeasuresPersistor testedPersistor = new CoverageMeasuresPersistor(project, context); - testedPersistor.saveMeasures(measures); - - verify(context, never()).saveMeasure(any(Resource.class), any(Measure.class)); - } - - @Test - public void shouldPersistMeasuresForKnownFiles() { - final Project project = new Project("Test"); - final org.sonar.api.resources.File dummyFile = new org.sonar.api.resources.File("dummy/test"); - final SensorContext context = mock(SensorContext.class); - final ProjectFileSystem fileSystem = mock(ProjectFileSystem.class); - final List sourceDirs = new ArrayList(); - final Map measures = new HashMap(); - final CoverageMeasuresBuilder measureBuilder = CoverageMeasuresBuilder.create(); - - sourceDirs.add(new File("/dummy")); - measures.put("/dummy/test", measureBuilder); - measureBuilder.setHits(99, 99); - measureBuilder.setConditions(99, 99, 1); - - when(fileSystem.getSourceDirs()).thenReturn(sourceDirs); - when(context.getResource(any(Resource.class))).thenReturn(dummyFile); - when(fileSystem.getBasedir()).thenReturn(new File(".")); - - project.setFileSystem(fileSystem); - - final CoverageMeasuresPersistor testedPersistor = new CoverageMeasuresPersistor(project, context); - testedPersistor.saveMeasures(measures); - - for (final Measure measure : measureBuilder.createMeasures()) { - verify(context, times(1)).saveMeasure(eq(org.sonar.api.resources.File.fromIOFile(new File(project.getFileSystem().getBasedir(), "dummy/test"), project)), eq(measure)); - } - } - -} diff --git a/src/test/java/org/sonar/plugins/objectivec/coverage/CoberturaParserTest.java b/src/test/java/org/sonar/plugins/objectivec/coverage/CoberturaParserTest.java deleted file mode 100644 index f3d6be1e..00000000 --- a/src/test/java/org/sonar/plugins/objectivec/coverage/CoberturaParserTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec.coverage; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.util.Map; - -import org.apache.tools.ant.filters.StringInputStream; -import org.junit.Test; -import org.sonar.api.measures.CoverageMeasuresBuilder; - -public final class CoberturaParserTest { - private final String VALID_REPORT_FILE_PATH = "FILEPATH"; - private final String VALID_REPORT = "."; - - @Test - public void parseReportShouldReturnAnEmptyMapWhenTheReportIsInvalid() { - final CoberturaParser coberturaParser = new CoberturaParser(); - final Map measures = coberturaParser.parseReport(new StringInputStream("")); - - assertTrue(measures.isEmpty()); - } - - @Test - public void parseReportShouldReturnAnEmptyMapWhenTheFileIsInvalid() { - final CoberturaParser coberturaParser = new CoberturaParser(); - final Map measures = coberturaParser.parseReport(new File("")); - - assertTrue(measures.isEmpty()); - } - - @Test - public void parseReportShouldReturnAMapOfFileToMeasuresWhenTheReportIsValid() { - final CoberturaParser coberturaParser = new CoberturaParser(); - final Map measures = coberturaParser.parseReport(new StringInputStream(VALID_REPORT)); - - assertNotNull(measures.get(VALID_REPORT_FILE_PATH)); - } - -} diff --git a/src/test/java/org/sonar/plugins/objectivec/coverage/CoberturaSensorTest.java b/src/test/java/org/sonar/plugins/objectivec/coverage/CoberturaSensorTest.java deleted file mode 100644 index 84922956..00000000 --- a/src/test/java/org/sonar/plugins/objectivec/coverage/CoberturaSensorTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec.coverage; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.junit.Before; -import org.junit.Test; -import org.sonar.api.batch.fs.FileSystem; -import org.sonar.api.config.Settings; -import org.sonar.api.resources.Project; -import org.sonar.api.scan.filesystem.ModuleFileSystem; -import org.sonar.plugins.objectivec.core.ObjectiveC; - -import java.util.SortedSet; -import java.util.TreeSet; - -public final class CoberturaSensorTest { - - private Settings settings; - - @Before - public void setUp() { - settings = new Settings(); - } - - @Test - public void shouldExecuteOnProjectShouldBeTrueWhenProjectIsObjc() { - final Project project = new Project("Test"); - - FileSystem fileSystem = mock(FileSystem.class); - SortedSet languages = new TreeSet(); - languages.add(ObjectiveC.KEY); - when(fileSystem.languages()).thenReturn(languages); - - final CoberturaSensor testedSensor = new CoberturaSensor(fileSystem, settings); - - assertTrue(testedSensor.shouldExecuteOnProject(project)); - } - - @Test - public void shouldExecuteOnProjectShouldBeFalseWhenProjectIsSomethingElse() { - final Project project = new Project("Test"); - settings.setProperty("sonar.language", "Test"); - - FileSystem fileSystem = mock(FileSystem.class); - SortedSet languages = new TreeSet(); - languages.add("Test"); - when(fileSystem.languages()).thenReturn(languages); - - final CoberturaSensor testedSensor = new CoberturaSensor(fileSystem, settings); - - assertFalse(testedSensor.shouldExecuteOnProject(project)); - } - -} diff --git a/src/test/java/org/sonar/plugins/objectivec/coverage/CoberturaXMLStreamHandlerTest.java b/src/test/java/org/sonar/plugins/objectivec/coverage/CoberturaXMLStreamHandlerTest.java deleted file mode 100644 index 1b9f3e6a..00000000 --- a/src/test/java/org/sonar/plugins/objectivec/coverage/CoberturaXMLStreamHandlerTest.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec.coverage; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.HashMap; -import java.util.Map; - -import javax.xml.stream.XMLStreamException; - -import org.apache.tools.ant.filters.StringInputStream; -import org.junit.Test; -import org.sonar.api.measures.CoverageMeasuresBuilder; -import org.sonar.api.utils.StaxParser; - -public final class CoberturaXMLStreamHandlerTest { - private final String EMPTY_REPORT = "."; - private final String VALID_REPORT = "."; - private final String FILE_PATH = "FILEPATH"; - private final int NO_HIT_LINE = 25; - private final int NO_BRANCH_LINE = 29; - private final int BRANCH_LINE = 35; - - @Test - public void streamLeavesTheMapEmptyWhenNoLinesAreFound() throws XMLStreamException { - final Map parseResults = new HashMap(); - final StaxParser parser = new StaxParser(new CoberturaXMLStreamHandler(parseResults)); - - parser.parse(new StringInputStream(EMPTY_REPORT)); - - assertTrue(parseResults.isEmpty()); - } - - @Test - public void streamAddsACoverageMeasureBuilderForClassesInTheReport() throws XMLStreamException { - final Map parseResults = new HashMap(); - final StaxParser parser = new StaxParser(new CoberturaXMLStreamHandler(parseResults)); - - parser.parse(new StringInputStream(VALID_REPORT)); - - assertNotNull(parseResults.get(FILE_PATH)); - } - - @Test - public void streamRecords0HitsForLinesWithNoHits() throws XMLStreamException { - final Map parseResults = new HashMap(); - final StaxParser parser = new StaxParser(new CoberturaXMLStreamHandler(parseResults)); - - parser.parse(new StringInputStream(VALID_REPORT)); - - assertEquals(Integer.valueOf(0), parseResults.get(FILE_PATH).getHitsByLine().get(NO_HIT_LINE)); - } - - @Test - public void streamRecordsHitsForLinesWithNoBranch() throws XMLStreamException { - final Map parseResults = new HashMap(); - final StaxParser parser = new StaxParser(new CoberturaXMLStreamHandler(parseResults)); - - parser.parse(new StringInputStream(VALID_REPORT)); - - assertEquals(Integer.valueOf(1), parseResults.get(FILE_PATH).getHitsByLine().get(NO_BRANCH_LINE)); - } - - @Test - public void streamRecordsHitsForLinesWithBranch() throws XMLStreamException { - final Map parseResults = new HashMap(); - final StaxParser parser = new StaxParser(new CoberturaXMLStreamHandler(parseResults)); - - parser.parse(new StringInputStream(VALID_REPORT)); - - assertEquals(Integer.valueOf(10), parseResults.get(FILE_PATH).getHitsByLine().get(BRANCH_LINE)); - } - - @Test - public void streamRecordsConditionsForLinesWithBranch() throws XMLStreamException { - final Map parseResults = new HashMap(); - final StaxParser parser = new StaxParser(new CoberturaXMLStreamHandler(parseResults)); - - parser.parse(new StringInputStream(VALID_REPORT)); - - assertEquals(Integer.valueOf(2), parseResults.get(FILE_PATH).getConditionsByLine().get(BRANCH_LINE)); - } - - @Test - public void streamRecordsConditionsHitsForLinesWithBranch() throws XMLStreamException { - final Map parseResults = new HashMap(); - final StaxParser parser = new StaxParser(new CoberturaXMLStreamHandler(parseResults)); - - parser.parse(new StringInputStream(VALID_REPORT)); - - assertEquals(Integer.valueOf(1), parseResults.get(FILE_PATH).getCoveredConditionsByLine().get(BRANCH_LINE)); - } - -} diff --git a/src/test/java/org/sonar/plugins/objectivec/violations/OCLintParserTest.java b/src/test/java/org/sonar/plugins/objectivec/violations/OCLintParserTest.java deleted file mode 100644 index 12730013..00000000 --- a/src/test/java/org/sonar/plugins/objectivec/violations/OCLintParserTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec.violations; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.apache.tools.ant.filters.StringInputStream; -import org.junit.Test; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.resources.Project; -import org.sonar.api.resources.ProjectFileSystem; -import org.sonar.api.resources.Resource; -import org.sonar.api.rules.Violation; - -public class OCLintParserTest { - private final String VALID_REPORT = "An operation on an Immutable object (String, BigDecimal or BigInteger) won't change the object itself"; - - @Test - public void parseReportShouldReturnAnEmptyCollectionWhenTheReportIsInvalid() { - final OCLintParser testedParser = new OCLintParser(null, null); - final Collection violations = testedParser.parseReport(new StringInputStream("")); - - assertTrue(violations.isEmpty()); - } - - @Test - public void parseReportShouldReturnAnEmptyMapWhenTheFileIsInvalid() { - final OCLintParser testedParser = new OCLintParser(null, null); - final Collection violations = testedParser.parseReport(new File("")); - - assertTrue(violations.isEmpty()); - } - - @Test - public void parseReportShouldReturnACollectionOfViolationsWhenTheReportIsNotEmpty() { - final Project project = new Project("Test"); - final org.sonar.api.resources.File dummyFile = new org.sonar.api.resources.File("dummy/test"); - final SensorContext context = mock(SensorContext.class); - final ProjectFileSystem fileSystem = mock(ProjectFileSystem.class); - final List sourceDirs = new ArrayList(); - - final OCLintParser testedParser = new OCLintParser(project, context); - - sourceDirs.add(new File("/dummy")); - when(fileSystem.getSourceDirs()).thenReturn(sourceDirs); - when(fileSystem.getBasedir()).thenReturn(new File(".")); - when(context.getResource(any(Resource.class))).thenReturn(dummyFile); - project.setFileSystem(fileSystem); - - final Collection violations = testedParser.parseReport(new StringInputStream(VALID_REPORT)); - assertFalse(violations.isEmpty()); - } - - -} diff --git a/src/test/java/org/sonar/plugins/objectivec/violations/OCLintSensorTest.java b/src/test/java/org/sonar/plugins/objectivec/violations/OCLintSensorTest.java deleted file mode 100644 index 52bd2ec8..00000000 --- a/src/test/java/org/sonar/plugins/objectivec/violations/OCLintSensorTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec.violations; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.junit.Before; -import org.junit.Test; -import org.sonar.api.batch.fs.FileSystem; -import org.sonar.api.config.Settings; -import org.sonar.api.resources.Project; -import org.sonar.plugins.objectivec.core.ObjectiveC; - -import java.util.SortedSet; -import java.util.TreeSet; - -public final class OCLintSensorTest { - - private Settings settings; - - @Before - public void setUp() { - settings = new Settings(); - } - - @Test - public void shouldExecuteOnProjectShouldBeTrueWhenProjectIsObjc() { - final Project project = new Project("Test"); - - FileSystem fileSystem = mock(FileSystem.class); - SortedSet languages = new TreeSet(); - languages.add(ObjectiveC.KEY); - when(fileSystem.languages()).thenReturn(languages); - - final OCLintSensor testedSensor = new OCLintSensor(fileSystem, settings); - - assertTrue(testedSensor.shouldExecuteOnProject(project)); - } - - @Test - public void shouldExecuteOnProjectShouldBeFalseWhenProjectIsSomethingElse() { - final Project project = new Project("Test"); - - FileSystem fileSystem = mock(FileSystem.class); - SortedSet languages = new TreeSet(); - languages.add("Test"); - when(fileSystem.languages()).thenReturn(languages); - - final OCLintSensor testedSensor = new OCLintSensor(fileSystem, settings); - - assertFalse(testedSensor.shouldExecuteOnProject(project)); - } - -} diff --git a/src/test/java/org/sonar/plugins/objectivec/violations/OCLintXMLStreamHandlerTest.java b/src/test/java/org/sonar/plugins/objectivec/violations/OCLintXMLStreamHandlerTest.java deleted file mode 100644 index 888aeba1..00000000 --- a/src/test/java/org/sonar/plugins/objectivec/violations/OCLintXMLStreamHandlerTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec.violations; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import javax.xml.stream.XMLStreamException; - -import org.apache.tools.ant.filters.StringInputStream; -import org.junit.Test; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.batch.fs.FileSystem; -import org.sonar.api.resources.Project; -import org.sonar.api.resources.ProjectFileSystem; -import org.sonar.api.resources.Resource; -import org.sonar.api.rules.RulePriority; -import org.sonar.api.rules.Violation; -import org.sonar.api.utils.StaxParser; - -public class OCLintXMLStreamHandlerTest { - private static final String EMPTY_REPORT = ""; - private static final String DESCRIPTION = "TEST DESCRIPTION"; - private static final Integer VIOLATION_LINE = Integer.valueOf(99); - private static final String RULE_KEY = "TEST RULE"; - private static final String VALID_REPORT = "" + DESCRIPTION + ""; - private ProjectBuilder projectBuilder; - - @Test - public void streamLeavesTheCollectionEmptyWhenNoLinesAreFound() throws XMLStreamException { - final Collection parseResults = new ArrayList(); - final StaxParser parser = new StaxParser(new OCLintXMLStreamHandler(parseResults, null, null)); - - parser.parse(new StringInputStream(EMPTY_REPORT)); - - assertTrue(parseResults.isEmpty()); - } - - @Test - public void streamAddAviolationForALineInTheReport() throws XMLStreamException { - final org.sonar.api.resources.File dummyFile = new org.sonar.api.resources.File("test"); - givenAProject().containingSourceDirectory("dummy"); - final SensorContext context = mock(SensorContext.class); - - final Collection parseResults = new ArrayList(); - final StaxParser parser = new StaxParser(new OCLintXMLStreamHandler(parseResults, project(), context)); - - when(context.getResource(any(Resource.class))).thenReturn(dummyFile); - - parser.parse(new StringInputStream(VALID_REPORT)); - - assertFalse(parseResults.isEmpty()); - } - - private Project project() { - Project project = givenAProject().project(); - ProjectFileSystem fileSystem = mock(ProjectFileSystem.class); - project.setFileSystem(fileSystem); - when(fileSystem.getBasedir()).thenReturn(new File(".")); - return project; - } - - private ProjectBuilder givenAProject() { - projectBuilder = new ProjectBuilder(); - return projectBuilder; - } - -} diff --git a/src/test/java/org/sonar/plugins/objectivec/violations/ProjectBuilder.java b/src/test/java/org/sonar/plugins/objectivec/violations/ProjectBuilder.java deleted file mode 100644 index 9f6bbebb..00000000 --- a/src/test/java/org/sonar/plugins/objectivec/violations/ProjectBuilder.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Sonar Objective-C Plugin - * Copyright (C) 2012 OCTO Technology - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.objectivec.violations; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import org.sonar.api.resources.Project; -import org.sonar.api.resources.ProjectFileSystem; - -final class ProjectBuilder { - private final Project project = new Project("Test"); - private final ProjectFileSystem fileSystem = mock(ProjectFileSystem.class); - private final List sourceDirs = new ArrayList(); - - public ProjectBuilder() { - project.setFileSystem(fileSystem); - when(fileSystem.getSourceDirs()).thenReturn(sourceDirs); - when(fileSystem.getBasedir()).thenReturn(new File(".")); - } - - public Project project() { - return project; - } - - public void containingSourceDirectory(final String d) { - sourceDirs.add(new File(d)); - } -} diff --git a/src/test/shell/configuration.test b/src/test/shell/configuration.test deleted file mode 100644 index e313ee4d..00000000 --- a/src/test/shell/configuration.test +++ /dev/null @@ -1,36 +0,0 @@ -# 1. Missing sonar.sources parameter -tee sonar-project.properties | cat > /dev/null; $RUNSONAR_HOME/run-sonar.sh -v -n -<<< -sonar.objectivec.project=Application.xcodeproj -sonar.objectivec.appScheme=Application ->>>2 -ERROR - sonar.sources parameter is missing in sonar-project.properties. You must specify which directories contain your .h/.m source files (comma-separated list). ->>>= !0 - -# 2. Missing sonar.objectivec.project parameter (no workspace) -tee sonar-project.properties | cat > /dev/null; $RUNSONAR_HOME/run-sonar.sh -v -n -<<< -sonar.sources=src -sonar.objectivec.appScheme=Application ->>>2 -ERROR - sonar.objectivec.project parameter is missing in sonar-project.properties (name of your .xcodeproj) ->>>= !0 - -# 3. Missing sonar.objectivec.project parameter (w/ workspace) -tee sonar-project.properties | cat > /dev/null; $RUNSONAR_HOME/run-sonar.sh -v -n -<<< -sonar.sources=src -sonar.objectivec.workspace=Application.xcworkspace -sonar.objectivec.appScheme=Application ->>>2 -ERROR - sonar.objectivec.project parameter is missing in sonar-project.properties. You must specify which projects (comma-separated list) are application code within the workspace Application.xcworkspace. ->>>= !0 - -# 4. Missing sonar.objectivec.appScheme parameter -tee sonar-project.properties | cat > /dev/null; $RUNSONAR_HOME/run-sonar.sh -v -n -<<< -sonar.sources=src -sonar.objectivec.project=Application.xcodeproj ->>>2 -ERROR - sonar.objectivec.appScheme parameter is missing in sonar-project.properties. You must specify which scheme is used to build your application. ->>>= !0 diff --git a/src/test/shell/nominal.test b/src/test/shell/nominal.test deleted file mode 100644 index 96f330d2..00000000 --- a/src/test/shell/nominal.test +++ /dev/null @@ -1,369 +0,0 @@ -# 0. Setup default compile_commands.json -tee compile_commands.json | cat > /dev/null -<<< -[ - { - "command" : "blablabla -o \/Users\/user\/Library\/Developer\/Xcode\/DerivedData\/myApplication-hevorauelspmmeblhdabohacuurg\/Build\/Intermediates\/Application.build\/Debug-iphonesimulator\/Application.build\/Objects-normal\/i386\/myFile.o", - "directory" : "titi", - "file" : "myFile.m" - } -] ->>>= 0 - -# 1. Nominal file -tee sonar-project.properties | cat > /dev/null; $RUNSONAR_HOME/run-sonar.sh -v -n -<<< -sonar.sources=src -sonar.objectivec.project=Application.xcodeproj -sonar.objectivec.appScheme=Application -sonar.objectivec.testScheme=ApplicationTests -sonar.objectivec.excludedPathsFromCoverage=.*Tests.*,.*3rdParty.* ->>> -Running run-sonar.sh... -Xcode workspace file is: -Xcode project file is: Application.xcodeproj -Xcode application scheme is: Application -Xcode test scheme is: ApplicationTests -Excluded paths from coverage are: .*Tests.*,.*3rdParty.* -Extracting Xcode project information -+ xctool -project Application.xcodeproj -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme Application clean - -+ xctool -project Application.xcodeproj -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme Application -reporter json-compilation-database:compile_commands.json build -Running tests using xctool -+ xctool -project Application.xcodeproj -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme ApplicationTests -reporter junit GCC_GENERATE_TEST_COVERAGE_FILES=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES test > sonar-reports/TEST-report.xml -Computing coverage report -Path for .gcno/.gcda coverage files is: /Users/user/Library/Developer/Xcode/DerivedData/myApplication-hevorauelspmmeblhdabohacuurg/Build/Intermediates/Application.build/Debug-iphonesimulator/Application.build/Objects-normal/i386 -Command line exclusion flags for gcovr is: --exclude .*Tests.* --exclude .*3rdParty.* - -+ gcovr -r . /Users/user/Library/Developer/Xcode/DerivedData/myApplication-hevorauelspmmeblhdabohacuurg/Build/Intermediates/Application.build/Debug-iphonesimulator/Application.build/Objects-normal/i386 --exclude .*Tests.* --exclude .*3rdParty.* --xml > sonar-reports/coverage-Application.xml -Running OCLint... -Path included in oclint analysis is: --include .*/shell/src.* -+ oclint-json-compilation-database --include .*/shell/src.* -- -report-type pmd -o sonar-reports/oclint.xml -Running SonarQube using SonarQube Runner -+ sonar-runner ->>>= 0 - -# 1bis. Nominal file not verbose -tee sonar-project.properties | cat > /dev/null; $RUNSONAR_HOME/run-sonar.sh -n -<<< -sonar.sources=src -sonar.objectivec.project=Application.xcodeproj -sonar.objectivec.appScheme=Application -sonar.objectivec.testScheme=ApplicationTests -sonar.objectivec.excludedPathsFromCoverage=.*Tests.*,.*3rdParty.* ->>> -Running run-sonar.sh... -Extracting Xcode project information -+ xctool -project Application.xcodeproj -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme Application clean > /dev/null - -+ xctool -project Application.xcodeproj -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme Application -reporter json-compilation-database:compile_commands.json build > /dev/null -Running tests using xctool -+ xctool -project Application.xcodeproj -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme ApplicationTests -reporter junit GCC_GENERATE_TEST_COVERAGE_FILES=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES test > sonar-reports/TEST-report.xml -Computing coverage report -+ gcovr -r . /Users/user/Library/Developer/Xcode/DerivedData/myApplication-hevorauelspmmeblhdabohacuurg/Build/Intermediates/Application.build/Debug-iphonesimulator/Application.build/Objects-normal/i386 --exclude .*Tests.* --exclude .*3rdParty.* --xml > sonar-reports/coverage-Application.xml -Running OCLint... -+ oclint-json-compilation-database --include .*/shell/src.* -- -report-type pmd -o sonar-reports/oclint.xml -Running SonarQube using SonarQube Runner -+ sonar-runner > /dev/null ->>>= 0 - -# 2. Testing various spaces in filenames, schemes etc. -tee sonar-project.properties | cat > /dev/null; $RUNSONAR_HOME/run-sonar.sh -v -n -<<< -sonar.sources=src -sonar.objectivec.project=my Application.xcodeproj -sonar.objectivec.appScheme=my Application -sonar.objectivec.testScheme=Application tests -sonar.objectivec.excludedPathsFromCoverage=.*Tests.*,.*3rd Party.* ->>> -Running run-sonar.sh... -Xcode workspace file is: -Xcode project file is: my Application.xcodeproj -Xcode application scheme is: my Application -Xcode test scheme is: Application tests -Excluded paths from coverage are: .*Tests.*,.*3rd Party.* -Extracting Xcode project information -+ xctool -project my Application.xcodeproj -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme my Application clean - -+ xctool -project my Application.xcodeproj -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme my Application -reporter json-compilation-database:compile_commands.json build -Running tests using xctool -+ xctool -project my Application.xcodeproj -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme Application tests -reporter junit GCC_GENERATE_TEST_COVERAGE_FILES=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES test > sonar-reports/TEST-report.xml -Computing coverage report -Path for .gcno/.gcda coverage files is: -Command line exclusion flags for gcovr is: --exclude .*Tests.* --exclude .*3rd Party.* - -+ gcovr -r . --exclude .*Tests.* --exclude .*3rd Party.* --xml > sonar-reports/coverage-my Application.xml -Running OCLint... -Path included in oclint analysis is: --include .*/shell/src.* -+ oclint-json-compilation-database --include .*/shell/src.* -- -report-type pmd -o sonar-reports/oclint.xml -Running SonarQube using SonarQube Runner -+ sonar-runner ->>>= 0 - -# 3. Testing usage of a Xcode workspace -tee sonar-project.properties | cat > /dev/null; $RUNSONAR_HOME/run-sonar.sh -v -n -<<< -sonar.sources=src -sonar.objectivec.workspace=Application.xcworkspace -sonar.objectivec.project=Application.xcodeproj -sonar.objectivec.appScheme=Application -sonar.objectivec.testScheme=ApplicationTests -sonar.objectivec.excludedPathsFromCoverage=.*Tests.*,.*3rdParty.* ->>> -Running run-sonar.sh... -Xcode workspace file is: Application.xcworkspace -Xcode project file is: Application.xcodeproj -Xcode application scheme is: Application -Xcode test scheme is: ApplicationTests -Excluded paths from coverage are: .*Tests.*,.*3rdParty.* -Extracting Xcode project information -+ xctool -workspace Application.xcworkspace -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme Application clean - -+ xctool -workspace Application.xcworkspace -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme Application -reporter json-compilation-database:compile_commands.json build -Running tests using xctool -+ xctool -workspace Application.xcworkspace -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme ApplicationTests -reporter junit GCC_GENERATE_TEST_COVERAGE_FILES=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES test > sonar-reports/TEST-report.xml -Computing coverage report -Path for .gcno/.gcda coverage files is: /Users/user/Library/Developer/Xcode/DerivedData/myApplication-hevorauelspmmeblhdabohacuurg/Build/Intermediates/Application.build/Debug-iphonesimulator/Application.build/Objects-normal/i386 -Command line exclusion flags for gcovr is: --exclude .*Tests.* --exclude .*3rdParty.* - -+ gcovr -r . /Users/user/Library/Developer/Xcode/DerivedData/myApplication-hevorauelspmmeblhdabohacuurg/Build/Intermediates/Application.build/Debug-iphonesimulator/Application.build/Objects-normal/i386 --exclude .*Tests.* --exclude .*3rdParty.* --xml > sonar-reports/coverage-Application.xml -Running OCLint... -Path included in oclint analysis is: --include .*/shell/src.* -+ oclint-json-compilation-database --include .*/shell/src.* -- -report-type pmd -o sonar-reports/oclint.xml -Running SonarQube using SonarQube Runner -+ sonar-runner ->>>= 0 - -# 4. Testing usage of multiple source directories -tee sonar-project.properties | cat > /dev/null; $RUNSONAR_HOME/run-sonar.sh -v -n -<<< -sonar.sources=src1,src2 -sonar.objectivec.project=Application.xcodeproj -sonar.objectivec.appScheme=Application -sonar.objectivec.testScheme=ApplicationTests -sonar.objectivec.excludedPathsFromCoverage=.*Tests.*,.*3rdParty.* ->>> -Running run-sonar.sh... -Xcode workspace file is: -Xcode project file is: Application.xcodeproj -Xcode application scheme is: Application -Xcode test scheme is: ApplicationTests -Excluded paths from coverage are: .*Tests.*,.*3rdParty.* -Extracting Xcode project information -+ xctool -project Application.xcodeproj -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme Application clean - -+ xctool -project Application.xcodeproj -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme Application -reporter json-compilation-database:compile_commands.json build -Running tests using xctool -+ xctool -project Application.xcodeproj -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme ApplicationTests -reporter junit GCC_GENERATE_TEST_COVERAGE_FILES=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES test > sonar-reports/TEST-report.xml -Computing coverage report -Path for .gcno/.gcda coverage files is: /Users/user/Library/Developer/Xcode/DerivedData/myApplication-hevorauelspmmeblhdabohacuurg/Build/Intermediates/Application.build/Debug-iphonesimulator/Application.build/Objects-normal/i386 -Command line exclusion flags for gcovr is: --exclude .*Tests.* --exclude .*3rdParty.* - -+ gcovr -r . /Users/user/Library/Developer/Xcode/DerivedData/myApplication-hevorauelspmmeblhdabohacuurg/Build/Intermediates/Application.build/Debug-iphonesimulator/Application.build/Objects-normal/i386 --exclude .*Tests.* --exclude .*3rdParty.* --xml > sonar-reports/coverage-Application.xml -Running OCLint... -Path included in oclint analysis is: --include .*/shell/src1.* --include .*/shell/src2.* -+ oclint-json-compilation-database --include .*/shell/src1.* --include .*/shell/src2.* -- -report-type pmd -o sonar-reports/oclint.xml -Running SonarQube using SonarQube Runner -+ sonar-runner ->>>= 0 - -# x. Testing usage of -nooclint -tee sonar-project.properties | cat > /dev/null; $RUNSONAR_HOME/run-sonar.sh -v -n -nooclint -<<< -sonar.sources=src -sonar.objectivec.project=Application.xcodeproj -sonar.objectivec.appScheme=Application -sonar.objectivec.testScheme=ApplicationTests -sonar.objectivec.excludedPathsFromCoverage=.*Tests.*,.*3rdParty.* ->>> -Running run-sonar.sh... -Xcode workspace file is: -Xcode project file is: Application.xcodeproj -Xcode application scheme is: Application -Xcode test scheme is: ApplicationTests -Excluded paths from coverage are: .*Tests.*,.*3rdParty.* -Extracting Xcode project information -+ xctool -project Application.xcodeproj -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme Application clean - -+ xctool -project Application.xcodeproj -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme Application -reporter json-compilation-database:compile_commands.json build -Running tests using xctool -+ xctool -project Application.xcodeproj -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme ApplicationTests -reporter junit GCC_GENERATE_TEST_COVERAGE_FILES=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES test > sonar-reports/TEST-report.xml -Computing coverage report -Path for .gcno/.gcda coverage files is: /Users/user/Library/Developer/Xcode/DerivedData/myApplication-hevorauelspmmeblhdabohacuurg/Build/Intermediates/Application.build/Debug-iphonesimulator/Application.build/Objects-normal/i386 -Command line exclusion flags for gcovr is: --exclude .*Tests.* --exclude .*3rdParty.* - -+ gcovr -r . /Users/user/Library/Developer/Xcode/DerivedData/myApplication-hevorauelspmmeblhdabohacuurg/Build/Intermediates/Application.build/Debug-iphonesimulator/Application.build/Objects-normal/i386 --exclude .*Tests.* --exclude .*3rdParty.* --xml > sonar-reports/coverage-Application.xml -Skipping OCLint (test purposes only!) -Running SonarQube using SonarQube Runner -+ sonar-runner ->>>= 0 - -# x. No test scheme provided -tee sonar-project.properties | cat > /dev/null; $RUNSONAR_HOME/run-sonar.sh -v -n -<<< -sonar.sources=src -sonar.objectivec.project=Application.xcodeproj -sonar.objectivec.appScheme=Application -sonar.objectivec.excludedPathsFromCoverage=.*Tests.*,.*3rdParty.* ->>> -Running run-sonar.sh... -Xcode workspace file is: -Xcode project file is: Application.xcodeproj -Xcode application scheme is: Application -Xcode test scheme is: -Excluded paths from coverage are: .*Tests.*,.*3rdParty.* -Extracting Xcode project information -+ xctool -project Application.xcodeproj -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme Application clean - -+ xctool -project Application.xcodeproj -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme Application -reporter json-compilation-database:compile_commands.json build -Skipping tests as no test scheme has been provided! -Running OCLint... -Path included in oclint analysis is: --include .*/shell/src.* -+ oclint-json-compilation-database --include .*/shell/src.* -- -report-type pmd -o sonar-reports/oclint.xml -Running SonarQube using SonarQube Runner -+ sonar-runner ->>>= 0 - -# x. No excluded path from coverage provided -tee sonar-project.properties | cat > /dev/null; $RUNSONAR_HOME/run-sonar.sh -v -n -<<< -sonar.sources=src -sonar.objectivec.project=Application.xcodeproj -sonar.objectivec.appScheme=Application -sonar.objectivec.testScheme=ApplicationTests ->>> -Running run-sonar.sh... -Xcode workspace file is: -Xcode project file is: Application.xcodeproj -Xcode application scheme is: Application -Xcode test scheme is: ApplicationTests -Excluded paths from coverage are: -Extracting Xcode project information -+ xctool -project Application.xcodeproj -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme Application clean - -+ xctool -project Application.xcodeproj -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme Application -reporter json-compilation-database:compile_commands.json build -Running tests using xctool -+ xctool -project Application.xcodeproj -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme ApplicationTests -reporter junit GCC_GENERATE_TEST_COVERAGE_FILES=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES test > sonar-reports/TEST-report.xml -Computing coverage report -Path for .gcno/.gcda coverage files is: /Users/user/Library/Developer/Xcode/DerivedData/myApplication-hevorauelspmmeblhdabohacuurg/Build/Intermediates/Application.build/Debug-iphonesimulator/Application.build/Objects-normal/i386 -Command line exclusion flags for gcovr is: - -+ gcovr -r . /Users/user/Library/Developer/Xcode/DerivedData/myApplication-hevorauelspmmeblhdabohacuurg/Build/Intermediates/Application.build/Debug-iphonesimulator/Application.build/Objects-normal/i386 --xml > sonar-reports/coverage-Application.xml -Running OCLint... -Path included in oclint analysis is: --include .*/shell/src.* -+ oclint-json-compilation-database --include .*/shell/src.* -- -report-type pmd -o sonar-reports/oclint.xml -Running SonarQube using SonarQube Runner -+ sonar-runner ->>>= 0 - - -# 5. Setup specific compile_commands.json -tee compile_commands.json | cat > /dev/null -<<< -[ - { - "command" : "blablabla -o \/Users\/user\/Library\/Developer\/Xcode\/DerivedData\/myApplication-hevorauelspmmeblhdabohacuurg\/Build\/Intermediates\/MyDependency.build\/Debug-iphonesimulator\/MyDependency.build\/Objects-normal\/i386\/myFile.o", - "directory" : "titi", - "file" : "myFile.m" - } - { - "command" : "blablabla -o \/Users\/user\/Library\/Developer\/Xcode\/DerivedData\/myApplication-hevorauelspmmeblhdabohacuurg\/Build\/Intermediates\/Application.build\/Debug-iphonesimulator\/Application.build\/Objects-normal\/i386\/myFile.o", - "directory" : "titi", - "file" : "myFile.m" - } -] ->>>= 0 - -# 6. Testing filtering of external projects in workspace -tee sonar-project.properties | cat > /dev/null; $RUNSONAR_HOME/run-sonar.sh -v -n -<<< -sonar.sources=src -sonar.objectivec.workspace=Application.xcworkspace -sonar.objectivec.project=Application.xcodeproj -sonar.objectivec.appScheme=Application -sonar.objectivec.testScheme=ApplicationTests -sonar.objectivec.excludedPathsFromCoverage=.*Tests.*,.*3rdParty.* ->>> -Running run-sonar.sh... -Xcode workspace file is: Application.xcworkspace -Xcode project file is: Application.xcodeproj -Xcode application scheme is: Application -Xcode test scheme is: ApplicationTests -Excluded paths from coverage are: .*Tests.*,.*3rdParty.* -Extracting Xcode project information -+ xctool -workspace Application.xcworkspace -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme Application clean - -+ xctool -workspace Application.xcworkspace -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme Application -reporter json-compilation-database:compile_commands.json build -Running tests using xctool -+ xctool -workspace Application.xcworkspace -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme ApplicationTests -reporter junit GCC_GENERATE_TEST_COVERAGE_FILES=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES test > sonar-reports/TEST-report.xml -Computing coverage report -Path for .gcno/.gcda coverage files is: /Users/user/Library/Developer/Xcode/DerivedData/myApplication-hevorauelspmmeblhdabohacuurg/Build/Intermediates/Application.build/Debug-iphonesimulator/Application.build/Objects-normal/i386 -Command line exclusion flags for gcovr is: --exclude .*Tests.* --exclude .*3rdParty.* - -+ gcovr -r . /Users/user/Library/Developer/Xcode/DerivedData/myApplication-hevorauelspmmeblhdabohacuurg/Build/Intermediates/Application.build/Debug-iphonesimulator/Application.build/Objects-normal/i386 --exclude .*Tests.* --exclude .*3rdParty.* --xml > sonar-reports/coverage-Application.xml -Running OCLint... -Path included in oclint analysis is: --include .*/shell/src.* -+ oclint-json-compilation-database --include .*/shell/src.* -- -report-type pmd -o sonar-reports/oclint.xml -Running SonarQube using SonarQube Runner -+ sonar-runner ->>>= 0 - -# 7. Setup specific compile_commands.json with 2 projects in workspace -tee compile_commands.json | cat > /dev/null -<<< -[ - { - "command" : "blablabla -o \/Users\/user\/Library\/Developer\/Xcode\/DerivedData\/myApplication-hevorauelspmmeblhdabohacuurg\/Build\/Intermediates\/Application1.build\/Debug-iphonesimulator\/Application1.build\/Objects-normal\/i386\/myFile.o", - "directory" : "titi", - "file" : "myFile.m" - } - { - "command" : "blablabla -o \/Users\/user\/Library\/Developer\/Xcode\/DerivedData\/myApplication-hevorauelspmmeblhdabohacuurg\/Build\/Intermediates\/Application2.build\/Debug-iphonesimulator\/Application2.build\/Objects-normal\/i386\/myFile.o", - "directory" : "titi", - "file" : "myFile.m" - } -] ->>>= 0 - -# 8. Testing filtering of external projects in workspace -tee sonar-project.properties | cat > /dev/null; $RUNSONAR_HOME/run-sonar.sh -v -n -<<< -sonar.sources=src -sonar.objectivec.workspace=Application.xcworkspace -sonar.objectivec.project=Application1.xcodeproj,Application2.xcodeproj -sonar.objectivec.appScheme=Application -sonar.objectivec.testScheme=ApplicationTests -sonar.objectivec.excludedPathsFromCoverage=.*Tests.*,.*3rdParty.* ->>> -Running run-sonar.sh... -Xcode workspace file is: Application.xcworkspace -Xcode project file is: Application1.xcodeproj,Application2.xcodeproj -Xcode application scheme is: Application -Xcode test scheme is: ApplicationTests -Excluded paths from coverage are: .*Tests.*,.*3rdParty.* -Extracting Xcode project information -+ xctool -workspace Application.xcworkspace -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme Application clean - -+ xctool -workspace Application.xcworkspace -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme Application -reporter json-compilation-database:compile_commands.json build -Running tests using xctool -+ xctool -workspace Application.xcworkspace -sdk iphonesimulator ARCHS=i386 VALID_ARCHS=i386 CURRENT_ARCH=i386 ONLY_ACTIVE_ARCH=NO -scheme ApplicationTests -reporter junit GCC_GENERATE_TEST_COVERAGE_FILES=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES test > sonar-reports/TEST-report.xml -Computing coverage report -Path for .gcno/.gcda coverage files is: /Users/user/Library/Developer/Xcode/DerivedData/myApplication-hevorauelspmmeblhdabohacuurg/Build/Intermediates/Application1.build/Debug-iphonesimulator/Application1.build/Objects-normal/i386 -Command line exclusion flags for gcovr is: --exclude .*Tests.* --exclude .*3rdParty.* - -+ gcovr -r . /Users/user/Library/Developer/Xcode/DerivedData/myApplication-hevorauelspmmeblhdabohacuurg/Build/Intermediates/Application1.build/Debug-iphonesimulator/Application1.build/Objects-normal/i386 --exclude .*Tests.* --exclude .*3rdParty.* --xml > sonar-reports/coverage-Application1.xml - -Path for .gcno/.gcda coverage files is: /Users/user/Library/Developer/Xcode/DerivedData/myApplication-hevorauelspmmeblhdabohacuurg/Build/Intermediates/Application2.build/Debug-iphonesimulator/Application2.build/Objects-normal/i386 -Command line exclusion flags for gcovr is: --exclude .*Tests.* --exclude .*3rdParty.* - -+ gcovr -r . /Users/user/Library/Developer/Xcode/DerivedData/myApplication-hevorauelspmmeblhdabohacuurg/Build/Intermediates/Application2.build/Debug-iphonesimulator/Application2.build/Objects-normal/i386 --exclude .*Tests.* --exclude .*3rdParty.* --xml > sonar-reports/coverage-Application2.xml -Running OCLint... -Path included in oclint analysis is: --include .*/shell/src.* -+ oclint-json-compilation-database --include .*/shell/src.* -- -report-type pmd -o sonar-reports/oclint.xml -Running SonarQube using SonarQube Runner -+ sonar-runner ->>>= 0 - - - - diff --git a/src/test/shell/usage.test b/src/test/shell/usage.test deleted file mode 100644 index 5f613c80..00000000 --- a/src/test/shell/usage.test +++ /dev/null @@ -1,34 +0,0 @@ -# 1. Incorrect usage -$RUNSONAR_HOME/run-sonar.sh -titi ->>>2 /Usage: .*run-sonar\.sh \[-v\]/ ->>>= !0 - -# 2. Correct usage -rm -rf sonar-project.properties; $RUNSONAR_HOME/run-sonar.sh ->>> /Running run-sonar.sh\.\.\./ ->>>= !0 - -# 3. Correct usage and verbose -rm -rf sonar-project.properties; $RUNSONAR_HOME/run-sonar.sh -v ->>> /Running run-sonar.sh\.\.\./ ->>>= !0 - -# 4. xctool not installed -# export PATH="/usr/bin:/bin:/usr/sbin:/Users/cpicat/.cabal/bin"; $RUNSONAR_HOME/run-sonar.sh -# >>>2 /ERROR - xctool is not installed or not in your PATH/ -# >>>= !0 - -# 5. gcovr not installed -# mv /Applications/InstalledSoftware/gcovr /Applications/InstalledSoftware/gcovr2; $RUNSONAR_HOME//run-sonar.sh; mv /Applications/InstalledSoftware/gcovr2 /Applications/InstalledSoftware/gcovr -# >>>2 /ERROR - gcovr is not installed or not in your PATH/ -# >>>= 0 - -# 6. oclint not installed -# mv /Applications/InstalledSoftware/oclint-0.8.dev.2888e0f/bin/oclint /Applications/InstalledSoftware/oclint-0.8.dev.2888e0f/bin/oclint2; $RUNSONAR_HOME/run-sonar.sh; mv /Applications/InstalledSoftware/oclint-0.8.dev.2888e0f/bin/oclint2 /Applications/InstalledSoftware/oclint-0.8.dev.2888e0f/bin/oclint -# >>>2 /ERROR - oclint is not installed or not in your PATH/ -# >>>= !0 - -# 7. No sonar-project.properties in current directory -$RUNSONAR_HOME/run-sonar.sh ->>>2 /ERROR - No sonar-project.properties in current directory/ ->>>= !0 diff --git a/sslr-objective-c-toolkit/pom.xml b/sslr-objective-c-toolkit/pom.xml new file mode 100644 index 00000000..425c1e8d --- /dev/null +++ b/sslr-objective-c-toolkit/pom.xml @@ -0,0 +1,121 @@ + + 4.0.0 + + + org.sonarqubecommunity.objectivec + objective-c + 0.5.0-SNAPSHOT + + + sslr-objective-c-toolkit + + SonarQube Objective-C (Community) :: SSLR Toolkit + + + + org.codehaus.sonar + sonar-plugin-api + provided + + + ${project.groupId} + objective-c-squid + ${project.version} + + + org.sonarsource.sslr + sslr-toolkit + + + ch.qos.logback + logback-classic + + + junit + junit + test + + + org.easytesting + fest-assert + test + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + org.sonar.objectivec.toolkit.ObjectiveCToolkit + + + + + + org.sonatype.plugins + jarjar-maven-plugin + + + package + + jarjar + + + + ${project.groupId}:objective-c-squid + org.sonarsource.sslr:sslr-core + org.sonarsource.sslr:sslr-xpath + jaxen:jaxen + org.sonarsource.sslr:sslr-toolkit + org.sonarsource.sslr-squid-bridge:sslr-squid-bridge + org.codehaus.sonar:sonar-colorizer + org.codehaus.sonar:sonar-channel + org.slf4j:slf4j-api + org.slf4j:jcl-over-slf4j + ch.qos.logback:logback-classic + ch.qos.logback:logback-core + commons-io:commons-io + commons-lang:commons-lang + com.google.guava:guava + + + + *.** + + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + + + enforce-size + + enforce + + verify + + + + 3500000 + 3400000 + + ${project.build.directory}/${project.build.finalName}.jar + + + + + + + + + + diff --git a/sslr-objective-c-toolkit/src/main/java/org/sonar/objectivec/toolkit/ObjectiveCConfigurationModel.java b/sslr-objective-c-toolkit/src/main/java/org/sonar/objectivec/toolkit/ObjectiveCConfigurationModel.java new file mode 100644 index 00000000..1194f1a2 --- /dev/null +++ b/sslr-objective-c-toolkit/src/main/java/org/sonar/objectivec/toolkit/ObjectiveCConfigurationModel.java @@ -0,0 +1,48 @@ +/* + * SonarQube Objective-C (Community) :: SSLR Toolkit + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.objectivec.toolkit; + +import com.google.common.base.Charsets; +import com.sonar.sslr.impl.Parser; +import org.sonar.colorizer.Tokenizer; +import org.sonar.objectivec.ObjectiveCConfiguration; +import org.sonar.objectivec.parser.ObjectiveCParser; +import org.sonar.sslr.toolkit.AbstractConfigurationModel; +import org.sonar.sslr.toolkit.ConfigurationProperty; + +import java.util.Collections; +import java.util.List; + +public class ObjectiveCConfigurationModel extends AbstractConfigurationModel { + @Override + public List getProperties() { + return Collections.emptyList(); + } + + @Override + public Parser doGetParser() { + return ObjectiveCParser.create(new ObjectiveCConfiguration(Charsets.UTF_8)); + } + + @Override + public List doGetTokenizers() { + return Collections.emptyList(); + } +} diff --git a/sslr-objective-c-toolkit/src/main/java/org/sonar/objectivec/toolkit/ObjectiveCToolkit.java b/sslr-objective-c-toolkit/src/main/java/org/sonar/objectivec/toolkit/ObjectiveCToolkit.java new file mode 100644 index 00000000..bdf46b5d --- /dev/null +++ b/sslr-objective-c-toolkit/src/main/java/org/sonar/objectivec/toolkit/ObjectiveCToolkit.java @@ -0,0 +1,33 @@ +/* + * SonarQube Objective-C (Community) :: SSLR Toolkit + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.objectivec.toolkit; + +import org.sonar.sslr.toolkit.Toolkit; + +public final class ObjectiveCToolkit { + private ObjectiveCToolkit() { + // Prevents outside instantiation + } + + public static void main(String[] args) { + Toolkit toolkit = new Toolkit("SSLR :: Objective-C (Community) :: Toolkit", new ObjectiveCConfigurationModel()); + toolkit.run(); + } +} diff --git a/sslr-objective-c-toolkit/src/test/java/org/sonar/objectivec/toolkit/ObjectiveCConfigurationModelTest.java b/sslr-objective-c-toolkit/src/test/java/org/sonar/objectivec/toolkit/ObjectiveCConfigurationModelTest.java new file mode 100644 index 00000000..be5156fa --- /dev/null +++ b/sslr-objective-c-toolkit/src/test/java/org/sonar/objectivec/toolkit/ObjectiveCConfigurationModelTest.java @@ -0,0 +1,37 @@ +/* + * SonarQube Objective-C (Community) :: SSLR Toolkit + * Copyright (C) 2012-2016 OCTO Technology, Backelite, and contributors + * mailto:sonarqube@googlegroups.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.objectivec.toolkit; + +import org.junit.Test; + +import static org.fest.assertions.Assertions.assertThat; + +public class ObjectiveCConfigurationModelTest { + @Test + public void getProperties() { + ObjectiveCConfigurationModel model = new ObjectiveCConfigurationModel(); + assertThat(model.getProperties()).isEmpty(); + } + + @Test + public void getTokenizers() { + assertThat(new ObjectiveCConfigurationModel().getTokenizers()).isEmpty(); + } +} diff --git a/updateRules.groovy b/updateRules.groovy deleted file mode 100644 index f3a86fda..00000000 --- a/updateRules.groovy +++ /dev/null @@ -1,217 +0,0 @@ -// Update rules.txt and profile-clint.xml from OCLint documentation -// Severity is determined from the category - -@Grab(group='org.codehaus.groovy.modules.http-builder', - module='http-builder', version='0.7') - -import groovyx.net.http.* -import groovy.xml.MarkupBuilder - -def splitCamelCase(value) { - value.replaceAll( - String.format("%s|%s|%s", - "(?<=[A-Z])(?=[A-Z][a-z])", - "(?<=[^A-Z])(?=[A-Z])", - "(?<=[A-Za-z])(?=[^A-Za-z])" - ), - " " - ).toLowerCase() -} - - -def parseCategory(url, name, severity) { - - def result = [] - - def http = new HTTPBuilder(url) - def html = http.get([:]) - - def root = html."**".find { it.@id.toString().contains(name)} - root."**".findAll { it.@class.toString() == 'section'}.each {rule -> - - def entry = [:] - - - def ruleName = splitCamelCase(rule.H2.text() - '¶').capitalize() - - // Original name - entry.originalName = null - try { - def sourceHttp = new HTTPBuilder(rule."**".findAll {it.name() == 'A'}.last().@href) - def sourceHtml = sourceHttp.get[:] - - def found = sourceHtml."**".find {it.name() == "TR" && it.text().contains("return\"")}.text() - def match = found =~ /"([^"]*)"/ - entry.originalName = match[0][1] - - } catch (Exception e) { - - } - - if (entry.originalName) { - - // Name - entry.name = ruleName - - - println "Retrieving rule $entry.originalName" - - // Summary - entry.summary = rule.P[1].text() - - // Severity - entry.severity = severity - - result.add entry - } else { - println "Unable to retrieve rule with name $entry.name" - } - } - - result -} - -def writeRulesTxt(rules, file) { - - def text = "Available issues:\n" + - "\n" + - "OCLint\n" + - "======\n\n" - - rules.each {rule -> - if (rule.name != '') { - text += rule.originalName + '\n' - text += '----------\n' - text += '\n' - - // Summary - text += "Summary: $rule.summary\n" - text += '\n' - - text += "Severity: $rule.severity\n" - text += "Category: OCLint\n" - - text += '\n' - } - } - - file.text = text -} - -def readRulesTxt(file) { - - def result = [] - - def previousLine = '' - def rule = null - file.eachLine {line -> - - if (line.startsWith('--')) { - rule = [:] - rule.originalName = previousLine.trim() - rule.name = rule.originalName - } - - if (line.startsWith('Summary:') && rule) { - rule.summary = (line - 'Summary:').trim() - } - - if (line.startsWith('Severity:') && rule) { - rule.severity = Integer.parseInt((line - 'Severity:').trim()) - } - - if (line.startsWith('Category:') && rule) { - rule.category = (line - 'Category:').trim() - result.add rule - rule = null - } - - previousLine = line - } - - result - -} - -def writeProfileOCLint(rls, file) { - def writer = new StringWriter() - def xml = new MarkupBuilder(writer) - xml.profile() { - name "OCLint" - language "objc" - rules { - rls.each {rl -> - rule { - repositoryKey "OCLint" - key rl.originalName - } - } - } - } - - file.text = "\n" + writer.toString() - -} - -def mergeRules(existingRules, freshRules) { - - def result = [] - - // Update existing rules - existingRules.each {rule -> - - def freshRule = freshRules.find {it.originalName?.trim() == rule.originalName?.trim()} - if (freshRule) { - - println "Updating rule [$rule.originalName]" - rule.severity = freshRule.severity - rule.category = freshRule.category - rule.summary = freshRule.summary - } - - if (!result.find {it.originalName?.trim() == rule.originalName?.trim()}) { - result.add rule - } else { - println "Skipping rule [$rule.originalName]" - } - } - - // Add new rules (if any) - freshRules.each {rule -> - - def existingRule = existingRules.find {it.originalName?.trim() == rule.originalName?.trim()} - if (!existingRule) { - result.add rule - } - } - - result -} - -// Files -File rulesTxt = new File('src/main/resources/org/sonar/plugins/oclint/rules.txt') -File profileXml = new File('src/main/resources/org/sonar/plugins/oclint/profile-oclint.xml') - - -// Parse OCLint online documentation -def rules = [] - -rules.addAll parseCategory("http://docs.oclint.org/en/dev/rules/basic.html", "basic", 3) -rules.addAll parseCategory("http://docs.oclint.org/en/dev/rules/convention.html", "convention", 2) -rules.addAll parseCategory("http://docs.oclint.org/en/dev/rules/empty.html", "empty", 3) -rules.addAll parseCategory("http://docs.oclint.org/en/dev/rules/migration.html", "migration", 1) -rules.addAll parseCategory("http://docs.oclint.org/en/dev/rules/naming.html", "naming", 2) -rules.addAll parseCategory("http://docs.oclint.org/en/dev/rules/redundant.html", "redundant", 1) -rules.addAll parseCategory("http://docs.oclint.org/en/dev/rules/size.html", "size", 3) -rules.addAll parseCategory("http://docs.oclint.org/en/dev/rules/unused.html", "unused", 0) -println "${rules.size()} rules found" - - -// Read existing rules -def existingRules = readRulesTxt(rulesTxt) - -// Update existing rules with fresh rules -def finalRules = mergeRules(existingRules, rules) - -writeRulesTxt(finalRules, rulesTxt) -writeProfileOCLint(finalRules, profileXml) \ No newline at end of file